templar_vault_kernel/actions/
mod.rs

1//! Kernel action dispatch for vault state transitions.
2//!
3//! This module defines the public `KernelAction` enum and a dispatcher that
4//! applies actions to `VaultState` and returns effects.
5
6extern crate alloc;
7
8use core::mem;
9
10use crate::effects::{KernelEffect, KernelEvent, WithdrawalSkipReason};
11use crate::error::{InvalidConfigCode, InvalidStateCode, KernelError};
12use crate::{
13    math::number::Number,
14    restrictions::{RestrictionKind, Restrictions},
15};
16use crate::{
17    state::{
18        op_state::{AllocationPlanEntry, OpState, PayoutState, TargetId},
19        queue::{compute_idle_settlement, is_past_cooldown, QueueError, WithdrawQueue},
20        vault::{FeeAccrualAnchor, VaultConfig, VaultState},
21    },
22    transitions::TransitionResult,
23};
24use crate::{
25    transitions::{start_withdrawal, TransitionError, WithdrawalRequest},
26    types::{Address, TimestampNs},
27};
28use alloc::vec;
29use alloc::vec::Vec;
30
31use crate::fee::FeesSpec;
32use crate::math::wad::{
33    compute_fee_shares_from_assets, compute_management_fee_shares, total_assets_for_fee_accrual,
34};
35#[cfg(any(feature = "action-recovery", test))]
36use crate::transitions::stop_withdrawal;
37
38#[cfg(any(feature = "action-allocation-lifecycle", test))]
39use crate::transitions::{complete_allocation, start_allocation};
40#[cfg(any(feature = "action-refresh-lifecycle", test))]
41use crate::transitions::{complete_refresh, start_refresh};
42
43/// Result of applying a kernel action.
44#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
45#[derive(Clone, PartialEq, Eq)]
46pub struct KernelResult {
47    pub state: VaultState,
48    pub effects: Vec<KernelEffect>,
49}
50
51impl KernelResult {
52    #[must_use]
53    pub fn new(state: VaultState, effects: Vec<KernelEffect>) -> Self {
54        Self { state, effects }
55    }
56}
57
58/// Outcome for payout settlement.
59#[templar_vault_macros::vault_derive(borsh, serde, postcard)]
60#[derive(Clone, PartialEq, Eq)]
61pub enum PayoutOutcome {
62    Success,
63    Failure,
64}
65
66/// Planned payout details for satisfying a queued withdrawal from idle assets.
67#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
68#[derive(Clone, PartialEq, Eq)]
69pub struct IdlePayoutPlan {
70    pub op_id: u64,
71    pub request_id: u64,
72    pub owner: Address,
73    pub receiver: Address,
74    pub assets_out: u128,
75    pub burn_shares: u128,
76}
77
78#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
79#[derive(Clone, PartialEq, Eq)]
80enum WithdrawalQueueOutcome {
81    None,
82    CoolingDown { requested_at_ns: TimestampNs },
83    InsufficientLiquidity,
84    Ready(WithdrawalRequest),
85}
86
87#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
88#[derive(Clone, Copy, PartialEq, Eq)]
89pub(crate) struct PendingWithdrawalHead {
90    pub(crate) id: u64,
91    pub(crate) owner: Address,
92    pub(crate) receiver: Address,
93    pub(crate) escrow_shares: u128,
94    pub(crate) expected_assets: u128,
95    pub(crate) requested_at_ns: TimestampNs,
96}
97
98#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
99#[derive(Clone, PartialEq, Eq)]
100enum WithdrawalHeadOutcome {
101    Skip(WithdrawalSkipReason),
102    CoolingDown { requested_at_ns: TimestampNs },
103    InsufficientLiquidity,
104    Ready,
105}
106
107#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
108#[derive(Clone, Copy, PartialEq, Eq)]
109pub(crate) struct PayoutSettlement {
110    pub(crate) burn_shares: u128,
111    pub(crate) refund_shares: u128,
112    pub(crate) completed_amount: u128,
113    pub(crate) success: bool,
114}
115
116#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
117#[derive(Clone, PartialEq, Eq)]
118#[cfg(any(feature = "action-recovery", test))]
119pub(crate) struct EmergencyResetOutcome {
120    pub(crate) state: VaultState,
121    pub(crate) op_id: u64,
122    pub(crate) from_code: u32,
123    pub(crate) refund_owner: Option<Address>,
124    pub(crate) refund_shares: u128,
125}
126
127#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
128#[derive(Clone, Copy, PartialEq, Eq)]
129pub(crate) struct WithdrawalRequestPlan {
130    pub(crate) owner: Address,
131    pub(crate) receiver: Address,
132    pub(crate) shares: u128,
133    pub(crate) expected_assets: u128,
134}
135
136#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
137#[derive(Clone, Copy, PartialEq, Eq)]
138#[cfg(any(feature = "action-sync-external", test))]
139struct ExternalAssetSyncPlan {
140    new_external_assets: u128,
141    new_total_assets: u128,
142}
143
144/// Plan an idle-funded payout from the current vault state.
145///
146/// Returns an error when the current idle liquidity cannot produce an actionable
147/// payout for the queue head.
148pub fn plan_idle_payout(
149    state: &VaultState,
150    min_withdrawal_assets: u128,
151) -> Result<IdlePayoutPlan, KernelError> {
152    planning::plan_idle_payout(state, min_withdrawal_assets)
153}
154
155/// Kernel actions supported by the dispatcher.
156///
157/// These actions drive the vault state machine. Each action validates preconditions,
158/// updates state, and returns effects to be executed by the chain-specific runtime.
159#[templar_vault_macros::vault_derive(borsh, serde, postcard)]
160#[derive(Clone, PartialEq, Eq)]
161pub enum KernelAction {
162    /// Begin allocating idle assets to external markets according to a plan.
163    ///
164    /// Transition: Idle -> Allocating
165    BeginAllocating {
166        op_id: u64,
167        plan: Vec<AllocationPlanEntry>,
168        now_ns: TimestampNs,
169    },
170
171    /// Deposit assets into the vault and mint shares to the receiver.
172    Deposit {
173        owner: Address,
174        receiver: Address,
175        assets_in: u128,
176        min_shares_out: u128,
177        now_ns: TimestampNs,
178    },
179
180    AtomicWithdraw {
181        owner: Address,
182        receiver: Address,
183        operator: Address,
184        assets_out: u128,
185        max_shares_burned: u128,
186        now_ns: TimestampNs,
187    },
188
189    AtomicRedeem {
190        owner: Address,
191        receiver: Address,
192        operator: Address,
193        shares: u128,
194        min_assets_out: u128,
195        now_ns: TimestampNs,
196    },
197
198    /// Request a withdrawal by escrowing shares in the queue.
199    RequestWithdraw {
200        owner: Address,
201        receiver: Address,
202        shares: u128,
203        min_assets_out: u128,
204        now_ns: TimestampNs,
205    },
206
207    /// Execute the next pending withdrawal from the queue.
208    ///
209    /// Transition: Idle -> Withdrawing
210    ExecuteWithdraw { now_ns: TimestampNs },
211
212    /// Begin refreshing external market balances.
213    ///
214    /// Transition: Idle -> Refreshing
215    BeginRefreshing {
216        op_id: u64,
217        plan: Vec<TargetId>,
218        now_ns: TimestampNs,
219    },
220
221    /// Complete an allocation operation.
222    ///
223    /// Transition: Allocating -> Idle or Withdrawing
224    FinishAllocating { op_id: u64, now_ns: TimestampNs },
225
226    /// Sync external asset balances during an active operation.
227    SyncExternalAssets {
228        new_external_assets: u128,
229        op_id: u64,
230        now_ns: TimestampNs,
231    },
232
233    RebalanceWithdraw {
234        op_id: u64,
235        amount: u128,
236        now_ns: TimestampNs,
237    },
238
239    /// Complete a refresh operation.
240    ///
241    /// Transition: Refreshing -> Idle
242    FinishRefreshing { op_id: u64, now_ns: TimestampNs },
243
244    /// Abort a refresh operation (e.g., on external call failure).
245    ///
246    /// Transition: Refreshing -> Idle
247    AbortRefreshing { op_id: u64 },
248
249    /// Settle a payout after asset transfer attempt.
250    ///
251    /// Transition: Payout -> Idle
252    SettlePayout { op_id: u64, outcome: PayoutOutcome },
253
254    /// Abort an allocation operation (e.g., on external call failure).
255    ///
256    /// Transition: Allocating -> Idle
257    AbortAllocating { op_id: u64 },
258
259    /// Abort a withdrawal operation (e.g., on external call failure).
260    ///
261    /// Transition: Withdrawing -> Idle
262    AbortWithdrawing { op_id: u64 },
263
264    /// Refresh fee calculations and mint fee shares.
265    RefreshFees { now_ns: TimestampNs },
266
267    /// Emit a pause-state update for executor-owned pause configuration.
268    Pause { paused: bool },
269
270    /// Emergency reset: force the vault back to Idle from any non-Idle state.
271    ///
272    /// Unlike the regular abort actions, this does not require op_id matching.
273    /// For Withdrawing/Payout states, escrowed shares are refunded to the owner
274    /// and the queue head is dequeued.
275    ///
276    /// Authorization (Owner-only, timelock-gated) must be enforced by the executor.
277    EmergencyReset,
278}
279
280impl KernelAction {
281    #[must_use]
282    pub fn begin_allocating(
283        op_id: u64,
284        plan: Vec<AllocationPlanEntry>,
285        now_ns: TimestampNs,
286    ) -> Self {
287        Self::BeginAllocating {
288            op_id,
289            plan,
290            now_ns,
291        }
292    }
293
294    #[must_use]
295    pub fn deposit(
296        owner: Address,
297        receiver: Address,
298        assets_in: u128,
299        min_shares_out: u128,
300        now_ns: TimestampNs,
301    ) -> Self {
302        Self::Deposit {
303            owner,
304            receiver,
305            assets_in,
306            min_shares_out,
307            now_ns,
308        }
309    }
310
311    #[must_use]
312    pub fn atomic_withdraw(
313        owner: Address,
314        receiver: Address,
315        operator: Address,
316        assets_out: u128,
317        max_shares_burned: u128,
318        now_ns: TimestampNs,
319    ) -> Self {
320        Self::AtomicWithdraw {
321            owner,
322            receiver,
323            operator,
324            assets_out,
325            max_shares_burned,
326            now_ns,
327        }
328    }
329
330    #[must_use]
331    pub fn atomic_redeem(
332        owner: Address,
333        receiver: Address,
334        operator: Address,
335        shares: u128,
336        min_assets_out: u128,
337        now_ns: TimestampNs,
338    ) -> Self {
339        Self::AtomicRedeem {
340            owner,
341            receiver,
342            operator,
343            shares,
344            min_assets_out,
345            now_ns,
346        }
347    }
348
349    #[must_use]
350    pub fn request_withdraw(
351        owner: Address,
352        receiver: Address,
353        shares: u128,
354        min_assets_out: u128,
355        now_ns: TimestampNs,
356    ) -> Self {
357        Self::RequestWithdraw {
358            owner,
359            receiver,
360            shares,
361            min_assets_out,
362            now_ns,
363        }
364    }
365
366    #[must_use]
367    pub fn execute_withdraw(now_ns: TimestampNs) -> Self {
368        Self::ExecuteWithdraw { now_ns }
369    }
370
371    #[must_use]
372    pub fn begin_refreshing(op_id: u64, plan: Vec<TargetId>, now_ns: TimestampNs) -> Self {
373        Self::BeginRefreshing {
374            op_id,
375            plan,
376            now_ns,
377        }
378    }
379
380    #[must_use]
381    pub fn finish_allocating(op_id: u64, now_ns: TimestampNs) -> Self {
382        Self::FinishAllocating { op_id, now_ns }
383    }
384
385    #[must_use]
386    pub fn sync_external_assets(
387        new_external_assets: u128,
388        op_id: u64,
389        now_ns: TimestampNs,
390    ) -> Self {
391        Self::SyncExternalAssets {
392            new_external_assets,
393            op_id,
394            now_ns,
395        }
396    }
397
398    #[must_use]
399    pub fn rebalance_withdraw(op_id: u64, amount: u128, now_ns: TimestampNs) -> Self {
400        Self::RebalanceWithdraw {
401            op_id,
402            amount,
403            now_ns,
404        }
405    }
406
407    #[must_use]
408    pub fn finish_refreshing(op_id: u64, now_ns: TimestampNs) -> Self {
409        Self::FinishRefreshing { op_id, now_ns }
410    }
411
412    #[must_use]
413    pub fn abort_refreshing(op_id: u64) -> Self {
414        Self::AbortRefreshing { op_id }
415    }
416
417    #[must_use]
418    pub fn settle_payout(op_id: u64, outcome: PayoutOutcome) -> Self {
419        Self::SettlePayout { op_id, outcome }
420    }
421
422    #[must_use]
423    pub fn abort_allocating(op_id: u64) -> Self {
424        Self::AbortAllocating { op_id }
425    }
426
427    #[must_use]
428    pub fn abort_withdrawing(op_id: u64) -> Self {
429        Self::AbortWithdrawing { op_id }
430    }
431
432    #[must_use]
433    pub fn refresh_fees(now_ns: TimestampNs) -> Self {
434        Self::RefreshFees { now_ns }
435    }
436
437    #[must_use]
438    pub fn pause(paused: bool) -> Self {
439        Self::Pause { paused }
440    }
441
442    #[must_use]
443    pub const fn emergency_reset() -> Self {
444        Self::EmergencyReset
445    }
446
447    #[must_use]
448    pub const fn op_id(&self) -> Option<u64> {
449        match self {
450            Self::BeginAllocating { op_id, .. }
451            | Self::BeginRefreshing { op_id, .. }
452            | Self::FinishAllocating { op_id, .. }
453            | Self::SyncExternalAssets { op_id, .. }
454            | Self::RebalanceWithdraw { op_id, .. }
455            | Self::FinishRefreshing { op_id, .. }
456            | Self::AbortRefreshing { op_id }
457            | Self::SettlePayout { op_id, .. }
458            | Self::AbortAllocating { op_id, .. }
459            | Self::AbortWithdrawing { op_id, .. } => Some(*op_id),
460            Self::Deposit { .. }
461            | Self::AtomicWithdraw { .. }
462            | Self::AtomicRedeem { .. }
463            | Self::RequestWithdraw { .. }
464            | Self::ExecuteWithdraw { .. }
465            | Self::RefreshFees { .. }
466            | Self::Pause { .. }
467            | Self::EmergencyReset => None,
468        }
469    }
470
471    #[must_use]
472    pub const fn timestamp_ns(&self) -> Option<TimestampNs> {
473        match self {
474            Self::BeginAllocating { now_ns, .. }
475            | Self::Deposit { now_ns, .. }
476            | Self::AtomicWithdraw { now_ns, .. }
477            | Self::AtomicRedeem { now_ns, .. }
478            | Self::RequestWithdraw { now_ns, .. }
479            | Self::ExecuteWithdraw { now_ns }
480            | Self::BeginRefreshing { now_ns, .. }
481            | Self::FinishAllocating { now_ns, .. }
482            | Self::SyncExternalAssets { now_ns, .. }
483            | Self::RebalanceWithdraw { now_ns, .. }
484            | Self::FinishRefreshing { now_ns, .. }
485            | Self::RefreshFees { now_ns } => Some(*now_ns),
486            Self::AbortRefreshing { .. }
487            | Self::SettlePayout { .. }
488            | Self::AbortAllocating { .. }
489            | Self::AbortWithdrawing { .. }
490            | Self::Pause { .. }
491            | Self::EmergencyReset => None,
492        }
493    }
494}
495
496/// Effective totals after applying virtual share/asset offsets.
497///
498/// Named fields prevent callers from confusing supply vs assets.
499#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
500#[derive(Clone, Copy, PartialEq, Eq)]
501pub struct EffectiveTotals {
502    pub supply: u128,
503    pub assets: u128,
504}
505
506/// Compute effective totals including virtual shares/assets for conversion math.
507pub fn effective_totals(state: &VaultState, config: &VaultConfig) -> EffectiveTotals {
508    conversions::effective_totals(state, config)
509}
510
511/// Convert an asset amount to shares (floor rounding — fewer shares, favors vault).
512pub fn convert_to_shares(state: &VaultState, config: &VaultConfig, assets: u128) -> u128 {
513    conversions::convert_to_shares(state, config, assets)
514}
515
516/// Convert a share amount to assets (floor rounding — fewer assets, favors vault).
517pub fn convert_to_assets(state: &VaultState, config: &VaultConfig, shares: u128) -> u128 {
518    conversions::convert_to_assets(state, config, shares)
519}
520
521/// Convert an asset amount to shares (ceil rounding — more shares, favors user).
522///
523/// Used by ERC-4626 `preview_withdraw` to compute shares burned (rounds against user).
524pub fn convert_to_shares_ceil(state: &VaultState, config: &VaultConfig, assets: u128) -> u128 {
525    conversions::convert_to_shares_ceil(state, config, assets)
526}
527
528/// Convert a share amount to assets (ceil rounding — more assets, favors user).
529///
530/// Used by ERC-4626 `preview_mint` to compute assets needed (rounds against user).
531pub fn convert_to_assets_ceil(state: &VaultState, config: &VaultConfig, shares: u128) -> u128 {
532    conversions::convert_to_assets_ceil(state, config, shares)
533}
534
535/// Convert assets to shares and reject quotients above the operation's legal cap.
536pub fn convert_to_shares_bounded(
537    state: &VaultState,
538    config: &VaultConfig,
539    assets: u128,
540    cap: u128,
541    error: InvalidStateCode,
542) -> Result<u128, KernelError> {
543    conversions::convert_to_shares_bounded(state, config, assets, cap, error)
544}
545
546/// Convert shares to assets and reject quotients above the operation's legal cap.
547pub fn convert_to_assets_bounded(
548    state: &VaultState,
549    config: &VaultConfig,
550    shares: u128,
551    cap: u128,
552    error: InvalidStateCode,
553) -> Result<u128, KernelError> {
554    conversions::convert_to_assets_bounded(state, config, shares, cap, error)
555}
556
557/// Convert shares to redeemable assets without exceeding real pro-rata backing.
558pub fn convert_to_redeem_assets(state: &VaultState, config: &VaultConfig, shares: u128) -> u128 {
559    conversions::convert_to_redeem_assets(state, config, shares)
560}
561
562/// Convert shares to redeemable assets and enforce an operation cap.
563pub fn convert_to_redeem_assets_bounded(
564    state: &VaultState,
565    config: &VaultConfig,
566    shares: u128,
567    cap: u128,
568    error: InvalidStateCode,
569) -> Result<u128, KernelError> {
570    conversions::convert_to_redeem_assets_bounded(state, config, shares, cap, error)
571}
572
573/// Convert withdrawal assets to shares without consuming remaining holders' backing.
574pub fn convert_to_withdraw_shares_ceil_bounded(
575    state: &VaultState,
576    config: &VaultConfig,
577    assets: u128,
578    cap: u128,
579    error: InvalidStateCode,
580) -> Result<u128, KernelError> {
581    conversions::convert_to_withdraw_shares_ceil_bounded(state, config, assets, cap, error)
582}
583
584/// Return shares withdrawable against available assets on both virtual and real bases.
585pub fn convert_to_withdrawable_shares(
586    state: &VaultState,
587    config: &VaultConfig,
588    assets: u128,
589) -> u128 {
590    conversions::convert_to_withdrawable_shares(state, config, assets)
591}
592
593/// Convert assets to shares with ceil rounding and reject quotients above the operation's cap.
594pub fn convert_to_shares_ceil_bounded(
595    state: &VaultState,
596    config: &VaultConfig,
597    assets: u128,
598    cap: u128,
599    error: InvalidStateCode,
600) -> Result<u128, KernelError> {
601    conversions::convert_to_shares_ceil_bounded(state, config, assets, cap, error)
602}
603
604/// Convert shares to assets with ceil rounding and reject quotients above the operation's cap.
605pub fn convert_to_assets_ceil_bounded(
606    state: &VaultState,
607    config: &VaultConfig,
608    shares: u128,
609    cap: u128,
610    error: InvalidStateCode,
611) -> Result<u128, KernelError> {
612    conversions::convert_to_assets_ceil_bounded(state, config, shares, cap, error)
613}
614
615/// Preview the shares minted for a deposit of `assets` using kernel conversions.
616#[inline]
617#[must_use]
618pub fn preview_deposit_shares(state: &VaultState, config: &VaultConfig, assets: u128) -> u128 {
619    convert_to_shares(state, config, assets)
620}
621
622/// Preview the assets redeemed for `shares` using kernel conversions.
623#[inline]
624#[must_use]
625pub fn preview_withdraw_assets(state: &VaultState, config: &VaultConfig, shares: u128) -> u128 {
626    convert_to_redeem_assets(state, config, shares)
627}
628
629#[cfg(any(feature = "action-recovery", feature = "action-sync-external", test))]
630fn require_active_op_id(
631    op_state: &OpState,
632    provided: u64,
633    error_code: InvalidStateCode,
634) -> Result<(), KernelError> {
635    let active = match op_state.op_id() {
636        Some(active) => active,
637        None => return Err(KernelError::from(error_code)),
638    };
639    if active != provided {
640        return Err(KernelError::OpIdMismatch {
641            expected: active,
642            actual: provided,
643        });
644    }
645    Ok(())
646}
647
648/// Validate that a destructured op_id matches the provided one.
649#[inline]
650fn check_op_id(expected: u64, actual: u64) -> Result<(), KernelError> {
651    if expected != actual {
652        return Err(KernelError::OpIdMismatch { expected, actual });
653    }
654    Ok(())
655}
656
657/// Validate that the withdrawal queue head matches the expected owner/receiver/escrow.
658///
659/// Used by both `AbortWithdrawing` and `SettlePayout` to ensure consistency
660/// between the op-state and the queue.
661pub(crate) fn validate_queue_head(
662    queue: &WithdrawQueue,
663    request_id: u64,
664    owner: &Address,
665    receiver: &Address,
666    escrow_shares: u128,
667) -> Result<(), KernelError> {
668    let Some((head_id, pending)) = queue.head() else {
669        return Err(KernelError::NoPendingWithdrawals);
670    };
671    if head_id != request_id
672        || pending.owner != *owner
673        || pending.receiver != *receiver
674        || pending.escrow_shares != escrow_shares
675    {
676        return Err(KernelError::from(
677            InvalidStateCode::WithdrawalQueueHeadMismatch,
678        ));
679    }
680    Ok(())
681}
682
683/// Push a `TransferShares` effect to refund escrowed shares to an owner.
684///
685/// No-op if `shares` is zero.
686#[inline]
687fn push_refund_shares(
688    effects: &mut Vec<KernelEffect>,
689    escrow: Address,
690    owner: Address,
691    shares: u128,
692) {
693    if shares > 0 {
694        effects.push(KernelEffect::TransferShares {
695            from: escrow,
696            to: owner,
697            shares,
698        });
699    }
700}
701
702#[inline]
703fn map_transition_result<T>(result: Result<T, TransitionError>) -> Result<T, KernelError> {
704    result.map_err(KernelError::Transition)
705}
706
707#[inline]
708fn apply_transition_result(
709    mut state: VaultState,
710    result: Result<TransitionResult, TransitionError>,
711) -> Result<KernelResult, KernelError> {
712    let result = map_transition_result(result)?;
713    state.op_state = result.new_state;
714    Ok(KernelResult::new(state, result.effects))
715}
716
717#[inline]
718fn map_queue_error(err: QueueError) -> KernelError {
719    match err {
720        QueueError::QueueFull { current, max } => KernelError::QueueFull { current, max },
721        QueueError::CacheOverflow => {
722            KernelError::from(InvalidStateCode::WithdrawalQueueCacheOverflow)
723        }
724        QueueError::WithdrawalNotFound { .. } => {
725            KernelError::from(InvalidStateCode::WithdrawalQueueMissingEntry)
726        }
727        QueueError::QueueEmpty => KernelError::from(InvalidStateCode::UnexpectedEmptyQueue),
728        QueueError::InvariantViolation { .. } => {
729            KernelError::from(InvalidStateCode::WithdrawalQueueInvariantViolation)
730        }
731    }
732}
733
734/// Process a deposit: validate restrictions, convert assets→shares, update totals.
735#[allow(clippy::too_many_arguments)]
736fn handle_deposit(
737    mut state: VaultState,
738    config: &VaultConfig,
739    restrictions: Option<&Restrictions>,
740    self_id: &Address,
741    owner: Address,
742    receiver: Address,
743    assets_in: u128,
744    min_shares_out: u128,
745    now_ns: TimestampNs,
746) -> Result<KernelResult, KernelError> {
747    enforce_restrictions(config, restrictions, self_id, &owner)?;
748    enforce_restrictions(config, restrictions, self_id, &receiver)?;
749    if !state.is_idle() {
750        return Err(KernelError::from(InvalidStateCode::DepositRequiresIdle));
751    }
752    if assets_in == 0 {
753        return Err(KernelError::ZeroAmount);
754    }
755
756    let mut effects = Vec::new();
757    #[cfg(any(feature = "action-refresh-fees", test))]
758    if should_refresh_fees_for_value_transfer(&state, config, now_ns) {
759        let mut refresh = handle_refresh_fees(state, config, now_ns)?;
760        state = refresh.state;
761        effects.append(&mut refresh.effects);
762    }
763
764    let shares_out = convert_to_shares_bounded(
765        &state,
766        config,
767        assets_in,
768        u128::MAX.saturating_sub(state.total_shares),
769        InvalidStateCode::MintOverflowTotalShares,
770    )?;
771    if shares_out == 0 {
772        return Err(KernelError::ZeroAmount);
773    }
774    if shares_out < min_shares_out {
775        return Err(KernelError::Slippage {
776            min: min_shares_out,
777            actual: shares_out,
778        });
779    }
780
781    state.total_assets = state
782        .total_assets
783        .checked_add(assets_in)
784        .ok_or_else(|| KernelError::from(InvalidStateCode::DepositOverflowTotalAssets))?;
785    state.idle_assets = state
786        .idle_assets
787        .checked_add(assets_in)
788        .ok_or_else(|| KernelError::from(InvalidStateCode::DepositOverflowIdleAssets))?;
789    state.total_shares = state
790        .total_shares
791        .checked_add(shares_out)
792        .ok_or_else(|| KernelError::from(InvalidStateCode::MintOverflowTotalShares))?;
793    state.fee_anchor = FeeAccrualAnchor::new(state.total_assets, now_ns);
794
795    effects.extend([
796        KernelEffect::TransferAssetsFrom {
797            from: owner,
798            to: *self_id,
799            amount: assets_in,
800        },
801        KernelEffect::MintShares {
802            owner: receiver,
803            shares: shares_out,
804        },
805        KernelEffect::EmitEvent {
806            event: crate::effects::KernelEvent::DepositProcessed {
807                owner,
808                receiver,
809                assets_in,
810                shares_out,
811            },
812        },
813    ]);
814
815    Ok(KernelResult::new(state, effects))
816}
817
818#[inline]
819pub fn should_refresh_fees_for_value_transfer(
820    state: &VaultState,
821    config: &VaultConfig,
822    now_ns: TimestampNs,
823) -> bool {
824    if state.total_shares == 0 || !config.fees.has_active_slot_fees() {
825        return false;
826    }
827    if now_ns > state.fee_anchor.timestamp_ns {
828        return true;
829    }
830    now_ns == state.fee_anchor.timestamp_ns && performance_fee_is_due(state, config)
831}
832
833/// Returns true when a performance fee is accrued against the fee anchor
834/// right now. The evaluation window is the anchor's own timestamp: without a
835/// `max_total_assets_growth_rate` cap any gain over the anchor is
836/// fee-relevant and due immediately. With a cap configured, the
837/// zero-elapsed-time window clamps the fee base back to the anchor, so an
838/// equal-time gain accrues no fee and the prior anchor must be preserved.
839#[inline]
840fn performance_fee_is_due(state: &VaultState, config: &VaultConfig) -> bool {
841    state.total_shares > 0
842        && !config.fees.performance.fee_wad.is_zero()
843        && config.fees.max_total_assets_growth_rate.is_none()
844        && state.total_assets > state.fee_anchor.total_assets
845}
846
847/// Shares minted and anchor produced by one fee-accrual pass.
848#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
849#[derive(Clone, Copy, PartialEq, Eq)]
850pub struct FeeAccrualOutcome {
851    pub management_shares: u128,
852    pub performance_shares: u128,
853    pub new_total_shares: u128,
854    pub new_anchor: FeeAccrualAnchor,
855}
856
857/// Fee accrual would push total shares past `u128::MAX`.
858#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
859#[derive(Clone, Copy, PartialEq, Eq)]
860pub struct FeeAccrualOverflow;
861
862/// Compute fee shares and the replacement anchor for one accrual pass.
863///
864/// Callers retain their own state, timestamp, and effect guards.
865pub fn compute_fee_accrual(
866    current_assets: u128,
867    total_shares: u128,
868    anchor: FeeAccrualAnchor,
869    fees: &FeesSpec,
870    now_ns: TimestampNs,
871) -> Result<FeeAccrualOutcome, FeeAccrualOverflow> {
872    if !fees.has_active_slot_fees() {
873        return Ok(FeeAccrualOutcome {
874            management_shares: 0,
875            performance_shares: 0,
876            new_total_shares: total_shares,
877            new_anchor: FeeAccrualAnchor::new(current_assets, now_ns),
878        });
879    }
880
881    let fee_assets_base = total_assets_for_fee_accrual(
882        current_assets,
883        anchor.total_assets,
884        anchor.timestamp_ns.as_u64(),
885        now_ns.as_u64(),
886        fees.max_total_assets_growth_rate,
887    );
888    let management_shares = compute_management_fee_shares(
889        fee_assets_base,
890        current_assets,
891        total_shares,
892        fees.management.fee_wad,
893        anchor.timestamp_ns.as_u64(),
894        now_ns.as_u64(),
895    );
896    let remaining = u128::MAX.saturating_sub(total_shares);
897    if management_shares > Number::from(remaining) {
898        return Err(FeeAccrualOverflow);
899    }
900    let management_shares = management_shares.as_u128_trunc();
901    let supply_after_management = total_shares
902        .checked_add(management_shares)
903        .ok_or(FeeAccrualOverflow)?;
904
905    let profit = fee_assets_base.saturating_sub(anchor.total_assets);
906    let performance_fee_assets = fees.performance.fee_wad.apply_floored(Number::from(profit));
907    let performance_shares = compute_fee_shares_from_assets(
908        performance_fee_assets,
909        Number::from(current_assets),
910        Number::from(supply_after_management),
911    );
912    let remaining = u128::MAX.saturating_sub(supply_after_management);
913    if performance_shares > Number::from(remaining) {
914        return Err(FeeAccrualOverflow);
915    }
916    let performance_shares = performance_shares.as_u128_trunc();
917    let new_total_shares = supply_after_management
918        .checked_add(performance_shares)
919        .ok_or(FeeAccrualOverflow)?;
920
921    Ok(FeeAccrualOutcome {
922        management_shares,
923        performance_shares,
924        new_total_shares,
925        new_anchor: FeeAccrualAnchor::new(current_assets, now_ns),
926    })
927}
928
929fn refresh_fees_before_value_transfer(
930    state: VaultState,
931    config: &VaultConfig,
932    now_ns: TimestampNs,
933) -> Result<(VaultState, Vec<KernelEffect>), KernelError> {
934    if should_refresh_fees_for_value_transfer(&state, config, now_ns) {
935        #[cfg(any(feature = "action-refresh-fees", test))]
936        {
937            let result = handle_refresh_fees(state, config, now_ns)?;
938            return Ok((result.state, result.effects));
939        }
940        #[cfg(not(any(feature = "action-refresh-fees", test)))]
941        return Err(KernelError::NotImplemented);
942    }
943    Ok((state, Vec::new()))
944}
945
946#[inline]
947fn push_atomic_burn_shares(
948    effects: &mut Vec<KernelEffect>,
949    owner: Address,
950    operator: Address,
951    shares: u128,
952) {
953    if operator == owner {
954        effects.push(KernelEffect::BurnShares { owner, shares });
955    } else {
956        effects.push(KernelEffect::BurnSharesFrom {
957            spender: operator,
958            owner,
959            shares,
960        });
961    }
962}
963
964#[inline]
965fn enforce_withdrawal_actors(
966    config: &VaultConfig,
967    restrictions: Option<&Restrictions>,
968    self_id: &Address,
969    owner: &Address,
970    receiver: &Address,
971) -> Result<(), KernelError> {
972    enforce_restrictions(config, restrictions, self_id, owner)?;
973    enforce_restrictions(config, restrictions, self_id, receiver)
974}
975
976#[inline]
977fn require_idle_with_nonzero_amount(
978    state: &VaultState,
979    idle_error: InvalidStateCode,
980    amount: u128,
981) -> Result<(), KernelError> {
982    if !state.is_idle() {
983        return Err(KernelError::from(idle_error));
984    }
985    if amount == 0 {
986        return Err(KernelError::ZeroAmount);
987    }
988    Ok(())
989}
990
991#[inline]
992fn restricted_withdraw_actor(
993    restrictions: Option<&Restrictions>,
994    self_id: &Address,
995    owner: &Address,
996    receiver: &Address,
997) -> Option<RestrictionKind> {
998    restrictions
999        .and_then(|r| r.is_restricted(owner))
1000        .or_else(|| restrictions.and_then(|r| r.is_restricted_allowing_self(receiver, self_id)))
1001}
1002
1003#[inline]
1004fn pending_withdrawal_skip_reason(
1005    restrictions: Option<&Restrictions>,
1006    self_id: &Address,
1007    owner: &Address,
1008    receiver: &Address,
1009    expected_assets: u128,
1010) -> Option<WithdrawalSkipReason> {
1011    if restricted_withdraw_actor(restrictions, self_id, owner, receiver).is_some() {
1012        Some(WithdrawalSkipReason::Restricted)
1013    } else if expected_assets == 0 {
1014        Some(WithdrawalSkipReason::ZeroExpectedAssets)
1015    } else {
1016        None
1017    }
1018}
1019
1020fn dequeue_skipped_withdrawal(
1021    state: &mut VaultState,
1022    self_id: &Address,
1023    skipped_effects: &mut Vec<KernelEffect>,
1024    reason: WithdrawalSkipReason,
1025) -> Result<(), KernelError> {
1026    let (pending_id, pending) = state
1027        .withdraw_queue
1028        .dequeue()
1029        .ok_or(KernelError::NoPendingWithdrawals)?;
1030    push_refund_shares(
1031        skipped_effects,
1032        *self_id,
1033        pending.owner,
1034        pending.escrow_shares,
1035    );
1036    skipped_effects.push(KernelEffect::EmitEvent {
1037        event: KernelEvent::WithdrawalSkipped {
1038            id: pending_id,
1039            owner: pending.owner,
1040            receiver: pending.receiver,
1041            escrow_shares: pending.escrow_shares,
1042            expected_assets: pending.expected_assets,
1043            reason,
1044        },
1045    });
1046    Ok(())
1047}
1048
1049#[inline]
1050pub(crate) fn pending_withdrawal_head(state: &VaultState) -> Option<PendingWithdrawalHead> {
1051    state
1052        .withdraw_queue
1053        .head()
1054        .map(|(id, pending)| PendingWithdrawalHead {
1055            id,
1056            owner: pending.owner,
1057            receiver: pending.receiver,
1058            escrow_shares: pending.escrow_shares,
1059            expected_assets: pending.expected_assets,
1060            requested_at_ns: pending.requested_at_ns,
1061        })
1062}
1063
1064#[inline]
1065fn classify_withdrawal_head(
1066    head: PendingWithdrawalHead,
1067    config: &VaultConfig,
1068    restrictions: Option<&Restrictions>,
1069    self_id: &Address,
1070    now_ns: TimestampNs,
1071    available_assets: u128,
1072) -> WithdrawalHeadOutcome {
1073    if let Some(reason) = pending_withdrawal_skip_reason(
1074        restrictions,
1075        self_id,
1076        &head.owner,
1077        &head.receiver,
1078        head.expected_assets,
1079    ) {
1080        WithdrawalHeadOutcome::Skip(reason)
1081    } else if !is_past_cooldown(head.requested_at_ns, now_ns, config.withdrawal_cooldown_ns) {
1082        WithdrawalHeadOutcome::CoolingDown {
1083            requested_at_ns: head.requested_at_ns,
1084        }
1085    } else if !has_actionable_withdrawal_liquidity(head.expected_assets, available_assets) {
1086        WithdrawalHeadOutcome::InsufficientLiquidity
1087    } else {
1088        WithdrawalHeadOutcome::Ready
1089    }
1090}
1091
1092#[inline]
1093fn has_actionable_withdrawal_liquidity(expected_assets: u128, available_assets: u128) -> bool {
1094    available_assets >= expected_assets
1095}
1096
1097#[inline]
1098pub(crate) fn withdrawal_request_from_head(
1099    state: &mut VaultState,
1100    head: PendingWithdrawalHead,
1101) -> WithdrawalRequest {
1102    WithdrawalRequest {
1103        op_id: state.allocate_op_id(),
1104        request_id: head.id,
1105        amount: head.expected_assets,
1106        receiver: head.receiver,
1107        owner: head.owner,
1108        escrow_shares: head.escrow_shares,
1109    }
1110}
1111
1112#[inline]
1113fn plan_withdrawal_request(
1114    state: &VaultState,
1115    config: &VaultConfig,
1116    owner: Address,
1117    receiver: Address,
1118    shares: u128,
1119    min_assets_out: u128,
1120) -> Result<WithdrawalRequestPlan, KernelError> {
1121    let expected_assets = convert_to_redeem_assets_bounded(
1122        state,
1123        config,
1124        shares,
1125        state.total_assets,
1126        InvalidStateCode::RequestWithdrawExpectedAssetsExceedTotalAssets,
1127    )?;
1128    if expected_assets < min_assets_out {
1129        return Err(KernelError::Slippage {
1130            min: min_assets_out,
1131            actual: expected_assets,
1132        });
1133    }
1134    if expected_assets < config.min_withdrawal_assets {
1135        return Err(KernelError::MinWithdrawal {
1136            amount: expected_assets,
1137            min: config.min_withdrawal_assets,
1138        });
1139    }
1140
1141    Ok(WithdrawalRequestPlan {
1142        owner,
1143        receiver,
1144        shares,
1145        expected_assets,
1146    })
1147}
1148
1149#[inline]
1150pub(crate) fn apply_withdrawal_request_plan(
1151    mut state: VaultState,
1152    config: &VaultConfig,
1153    self_id: &Address,
1154    request_plan: WithdrawalRequestPlan,
1155    now_ns: TimestampNs,
1156) -> Result<KernelResult, KernelError> {
1157    let id = state
1158        .withdraw_queue
1159        .enqueue(
1160            request_plan.owner,
1161            request_plan.receiver,
1162            request_plan.shares,
1163            request_plan.expected_assets,
1164            now_ns,
1165            config.max_pending_withdrawals,
1166        )
1167        .map_err(map_queue_error)?;
1168
1169    let effects = vec![
1170        KernelEffect::TransferShares {
1171            from: request_plan.owner,
1172            to: *self_id,
1173            shares: request_plan.shares,
1174        },
1175        KernelEffect::EmitEvent {
1176            event: crate::effects::KernelEvent::WithdrawalRequested {
1177                id,
1178                owner: request_plan.owner,
1179                receiver: request_plan.receiver,
1180                shares: request_plan.shares,
1181                expected_assets: request_plan.expected_assets,
1182            },
1183        },
1184    ];
1185
1186    Ok(KernelResult::new(state, effects))
1187}
1188
1189#[inline]
1190#[cfg(any(feature = "action-sync-external", test))]
1191fn ensure_sync_external_state_allowed(op_state: &OpState) -> Result<(), KernelError> {
1192    match op_state {
1193        OpState::Allocating(_) | OpState::Withdrawing(_) | OpState::Refreshing(_) => Ok(()),
1194        _ => Err(KernelError::from(
1195            InvalidStateCode::SyncExternalRequiresAllowedStates,
1196        )),
1197    }
1198}
1199
1200#[inline]
1201#[cfg(any(feature = "action-sync-external", test))]
1202fn plan_external_asset_sync(
1203    state: &VaultState,
1204    new_external_assets: u128,
1205) -> Result<ExternalAssetSyncPlan, KernelError> {
1206    let new_total_assets = state
1207        .idle_assets
1208        .checked_add(new_external_assets)
1209        .ok_or_else(|| KernelError::from(InvalidStateCode::SyncExternalOverflowIdlePlusExternal))?;
1210
1211    Ok(ExternalAssetSyncPlan {
1212        new_external_assets,
1213        new_total_assets,
1214    })
1215}
1216
1217fn next_withdrawal_queue_outcome(
1218    state: &mut VaultState,
1219    config: &VaultConfig,
1220    restrictions: Option<&Restrictions>,
1221    self_id: &Address,
1222    now_ns: TimestampNs,
1223    skipped_effects: &mut Vec<KernelEffect>,
1224) -> Result<WithdrawalQueueOutcome, KernelError> {
1225    loop {
1226        let Some(head) = pending_withdrawal_head(state) else {
1227            return Ok(WithdrawalQueueOutcome::None);
1228        };
1229
1230        match classify_withdrawal_head(
1231            head,
1232            config,
1233            restrictions,
1234            self_id,
1235            now_ns,
1236            state.idle_assets,
1237        ) {
1238            WithdrawalHeadOutcome::Skip(reason) => {
1239                dequeue_skipped_withdrawal(state, self_id, skipped_effects, reason)?;
1240            }
1241            WithdrawalHeadOutcome::CoolingDown { requested_at_ns } => {
1242                return Ok(WithdrawalQueueOutcome::CoolingDown { requested_at_ns });
1243            }
1244            WithdrawalHeadOutcome::InsufficientLiquidity => {
1245                return Ok(WithdrawalQueueOutcome::InsufficientLiquidity);
1246            }
1247            WithdrawalHeadOutcome::Ready => {
1248                return Ok(WithdrawalQueueOutcome::Ready(withdrawal_request_from_head(
1249                    state, head,
1250                )));
1251            }
1252        }
1253    }
1254}
1255
1256#[allow(clippy::too_many_arguments)]
1257fn handle_atomic_withdraw(
1258    state: VaultState,
1259    config: &VaultConfig,
1260    restrictions: Option<&Restrictions>,
1261    self_id: &Address,
1262    owner: Address,
1263    receiver: Address,
1264    operator: Address,
1265    assets_out: u128,
1266    max_shares_burned: u128,
1267    now_ns: TimestampNs,
1268) -> Result<KernelResult, KernelError> {
1269    enforce_withdrawal_actors(config, restrictions, self_id, &owner, &receiver)?;
1270    require_idle_with_nonzero_amount(
1271        &state,
1272        InvalidStateCode::AtomicWithdrawRequiresIdle,
1273        assets_out,
1274    )?;
1275    let (mut state, mut effects) = refresh_fees_before_value_transfer(state, config, now_ns)?;
1276
1277    let shares = convert_to_withdraw_shares_ceil_bounded(
1278        &state,
1279        config,
1280        assets_out,
1281        state.total_shares,
1282        InvalidStateCode::AtomicWithdrawBurnExceedsTotalShares,
1283    )?;
1284    if shares == 0 {
1285        return Err(KernelError::ZeroAmount);
1286    }
1287    if shares > max_shares_burned {
1288        return Err(KernelError::Slippage {
1289            min: max_shares_burned,
1290            actual: shares,
1291        });
1292    }
1293
1294    if assets_out > state.idle_assets {
1295        return Err(KernelError::from(
1296            InvalidStateCode::AtomicWithdrawExceedsIdleAssets,
1297        ));
1298    }
1299    state.total_shares = state
1300        .total_shares
1301        .checked_sub(shares)
1302        .ok_or_else(|| KernelError::from(InvalidStateCode::AtomicWithdrawBurnExceedsTotalShares))?;
1303    state.idle_assets = state
1304        .idle_assets
1305        .checked_sub(assets_out)
1306        .ok_or_else(|| KernelError::from(InvalidStateCode::AtomicWithdrawExceedsIdleAssets))?;
1307    state.total_assets = state
1308        .total_assets
1309        .checked_sub(assets_out)
1310        .ok_or_else(|| KernelError::from(InvalidStateCode::AtomicWithdrawTotalAssetsUnderflow))?;
1311
1312    push_atomic_burn_shares(&mut effects, owner, operator, shares);
1313    effects.push(KernelEffect::TransferAssets {
1314        to: receiver,
1315        amount: assets_out,
1316    });
1317    effects.push(KernelEffect::EmitEvent {
1318        event: KernelEvent::AtomicWithdrawProcessed {
1319            owner,
1320            receiver,
1321            shares_burned: shares,
1322            assets_out,
1323        },
1324    });
1325    Ok(KernelResult::new(state, effects))
1326}
1327
1328#[allow(clippy::too_many_arguments)]
1329fn handle_atomic_redeem(
1330    state: VaultState,
1331    config: &VaultConfig,
1332    restrictions: Option<&Restrictions>,
1333    self_id: &Address,
1334    owner: Address,
1335    receiver: Address,
1336    operator: Address,
1337    shares: u128,
1338    min_assets_out: u128,
1339    now_ns: TimestampNs,
1340) -> Result<KernelResult, KernelError> {
1341    enforce_withdrawal_actors(config, restrictions, self_id, &owner, &receiver)?;
1342    require_idle_with_nonzero_amount(&state, InvalidStateCode::AtomicWithdrawRequiresIdle, shares)?;
1343
1344    let (mut state, mut effects) = refresh_fees_before_value_transfer(state, config, now_ns)?;
1345
1346    let assets_out = convert_to_redeem_assets_bounded(
1347        &state,
1348        config,
1349        shares,
1350        state.idle_assets,
1351        InvalidStateCode::AtomicWithdrawExceedsIdleAssets,
1352    )?;
1353    if assets_out == 0 {
1354        return Err(KernelError::ZeroAmount);
1355    }
1356    if assets_out < min_assets_out {
1357        return Err(KernelError::Slippage {
1358            min: min_assets_out,
1359            actual: assets_out,
1360        });
1361    }
1362    if assets_out > state.idle_assets {
1363        return Err(KernelError::from(
1364            InvalidStateCode::AtomicWithdrawExceedsIdleAssets,
1365        ));
1366    }
1367
1368    state.total_shares = state
1369        .total_shares
1370        .checked_sub(shares)
1371        .ok_or_else(|| KernelError::from(InvalidStateCode::AtomicWithdrawBurnExceedsTotalShares))?;
1372    state.idle_assets = state
1373        .idle_assets
1374        .checked_sub(assets_out)
1375        .ok_or_else(|| KernelError::from(InvalidStateCode::AtomicWithdrawExceedsIdleAssets))?;
1376    state.total_assets = state
1377        .total_assets
1378        .checked_sub(assets_out)
1379        .ok_or_else(|| KernelError::from(InvalidStateCode::AtomicWithdrawTotalAssetsUnderflow))?;
1380
1381    push_atomic_burn_shares(&mut effects, owner, operator, shares);
1382    effects.push(KernelEffect::TransferAssets {
1383        to: receiver,
1384        amount: assets_out,
1385    });
1386    effects.push(KernelEffect::EmitEvent {
1387        event: KernelEvent::AtomicWithdrawProcessed {
1388            owner,
1389            receiver,
1390            shares_burned: shares,
1391            assets_out,
1392        },
1393    });
1394    Ok(KernelResult::new(state, effects))
1395}
1396
1397/// Enqueue a withdrawal request: validate, compute expected assets, escrow shares.
1398#[allow(clippy::too_many_arguments)]
1399fn handle_request_withdraw(
1400    state: VaultState,
1401    config: &VaultConfig,
1402    restrictions: Option<&Restrictions>,
1403    self_id: &Address,
1404    owner: Address,
1405    receiver: Address,
1406    shares: u128,
1407    min_assets_out: u128,
1408    now_ns: TimestampNs,
1409) -> Result<KernelResult, KernelError> {
1410    if !config.is_max_pending_valid() {
1411        return Err(KernelError::from(
1412            InvalidConfigCode::MaxPendingWithdrawalsExceedsLimit,
1413        ));
1414    }
1415
1416    enforce_withdrawal_actors(config, restrictions, self_id, &owner, &receiver)?;
1417    require_idle_with_nonzero_amount(
1418        &state,
1419        InvalidStateCode::RequestWithdrawRequiresIdle,
1420        shares,
1421    )?;
1422
1423    let (state, mut effects) = refresh_fees_before_value_transfer(state, config, now_ns)?;
1424    let request_plan =
1425        plan_withdrawal_request(&state, config, owner, receiver, shares, min_assets_out)?;
1426    let mut result = apply_withdrawal_request_plan(state, config, self_id, request_plan, now_ns)?;
1427    effects.append(&mut result.effects);
1428    result.effects = effects;
1429    Ok(result)
1430}
1431
1432/// Execute the next queued withdrawal after cooldown.
1433fn handle_execute_withdraw(
1434    mut state: VaultState,
1435    config: &VaultConfig,
1436    restrictions: Option<&Restrictions>,
1437    self_id: &Address,
1438    now_ns: TimestampNs,
1439) -> Result<KernelResult, KernelError> {
1440    if !state.op_state.is_idle() {
1441        let error_code = if state.op_state.is_withdrawing() {
1442            InvalidStateCode::ExecuteWithdrawRequiresIdleUseCallbacks
1443        } else {
1444            InvalidStateCode::ExecuteWithdrawRequiresIdle
1445        };
1446        return Err(KernelError::from(error_code));
1447    }
1448
1449    if is_globally_paused(config, restrictions) {
1450        return Err(KernelError::Restricted(RestrictionKind::Paused));
1451    }
1452
1453    let mut skipped_effects = Vec::new();
1454    match next_withdrawal_queue_outcome(
1455        &mut state,
1456        config,
1457        restrictions,
1458        self_id,
1459        now_ns,
1460        &mut skipped_effects,
1461    )? {
1462        WithdrawalQueueOutcome::None => {
1463            if skipped_effects.is_empty() {
1464                Err(KernelError::NoPendingWithdrawals)
1465            } else {
1466                Ok(KernelResult::new(state, skipped_effects))
1467            }
1468        }
1469        WithdrawalQueueOutcome::CoolingDown { requested_at_ns } => {
1470            if skipped_effects.is_empty() {
1471                Err(KernelError::Cooldown {
1472                    requested_at: requested_at_ns.into(),
1473                    now: now_ns.into(),
1474                    cooldown_ns: config.withdrawal_cooldown_ns,
1475                })
1476            } else {
1477                Ok(KernelResult::new(state, skipped_effects))
1478            }
1479        }
1480        WithdrawalQueueOutcome::InsufficientLiquidity => {
1481            if skipped_effects.is_empty() {
1482                Err(KernelError::from(
1483                    InvalidStateCode::WithdrawalLiquidityBelowMinimum,
1484                ))
1485            } else {
1486                Ok(KernelResult::new(state, skipped_effects))
1487            }
1488        }
1489        WithdrawalQueueOutcome::Ready(request) => {
1490            let transition = start_withdrawal(mem::take(&mut state.op_state), request);
1491            let mut result = apply_transition_result(state, transition)?;
1492            skipped_effects.append(&mut result.effects);
1493            result.effects = skipped_effects;
1494            Ok(result)
1495        }
1496    }
1497}
1498
1499/// Start an allocation: transition to Allocating and decrement idle assets.
1500#[cfg(any(feature = "action-allocation-lifecycle", test))]
1501fn handle_begin_allocating(
1502    mut state: VaultState,
1503    op_id: u64,
1504    plan: Vec<AllocationPlanEntry>,
1505) -> Result<KernelResult, KernelError> {
1506    let result = map_transition_result(start_allocation(
1507        mem::take(&mut state.op_state),
1508        plan,
1509        op_id,
1510    ))?;
1511
1512    // Compute allocation total from the plan and decrement idle_assets.
1513    let alloc_total = match result.new_state.as_allocating() {
1514        Some(allocating) => allocating.remaining,
1515        None => {
1516            return Err(KernelError::from(
1517                InvalidStateCode::StartAllocationMustReturnAllocating,
1518            ))
1519        }
1520    };
1521
1522    if alloc_total > state.idle_assets {
1523        return Err(KernelError::from(
1524            InvalidStateCode::AllocationPlanExceedsIdleAssets,
1525        ));
1526    }
1527
1528    state.idle_assets -= alloc_total;
1529    state.sync_total_assets();
1530    state.op_state = result.new_state;
1531    Ok(KernelResult::new(state, result.effects))
1532}
1533
1534/// Finish an allocation without advancing the withdrawal queue.
1535#[cfg(any(feature = "action-allocation-lifecycle", test))]
1536fn handle_finish_allocating(
1537    mut state: VaultState,
1538    _config: &VaultConfig,
1539    _restrictions: Option<&Restrictions>,
1540    _self_id: &Address,
1541    op_id: u64,
1542    _now_ns: TimestampNs,
1543) -> Result<KernelResult, KernelError> {
1544    let transition = complete_allocation(mem::take(&mut state.op_state), op_id, None);
1545    apply_transition_result(state, transition)
1546}
1547
1548#[cfg(any(feature = "action-sync-external", test))]
1549fn handle_sync_external_assets(
1550    mut state: VaultState,
1551    new_external_assets: u128,
1552    op_id: u64,
1553) -> Result<KernelResult, KernelError> {
1554    require_active_op_id(
1555        &state.op_state,
1556        op_id,
1557        InvalidStateCode::SyncExternalRequiresActiveOp,
1558    )?;
1559
1560    ensure_sync_external_state_allowed(&state.op_state)?;
1561    let sync_plan = plan_external_asset_sync(&state, new_external_assets)?;
1562
1563    state.external_assets = sync_plan.new_external_assets;
1564    state.total_assets = sync_plan.new_total_assets;
1565
1566    let total_assets = state.total_assets;
1567    Ok(KernelResult::new(
1568        state,
1569        vec![KernelEffect::EmitEvent {
1570            event: crate::effects::KernelEvent::ExternalAssetsSynced {
1571                op_id,
1572                new_external_assets: sync_plan.new_external_assets,
1573                total_assets,
1574            },
1575        }],
1576    ))
1577}
1578
1579#[cfg(any(feature = "action-sync-external", test))]
1580fn handle_rebalance_withdraw(
1581    mut state: VaultState,
1582    op_id: u64,
1583    amount: u128,
1584) -> Result<KernelResult, KernelError> {
1585    match &state.op_state {
1586        OpState::Idle => {}
1587        OpState::Allocating(_) => {
1588            require_active_op_id(
1589                &state.op_state,
1590                op_id,
1591                InvalidStateCode::SyncExternalRequiresActiveOp,
1592            )?;
1593        }
1594        _ => {
1595            return Err(KernelError::from(
1596                InvalidStateCode::RebalanceWithdrawRequiresIdle,
1597            ));
1598        }
1599    }
1600
1601    if amount > state.external_assets {
1602        return Err(KernelError::from(
1603            InvalidStateCode::RebalanceWithdrawExceedsExternalAssets,
1604        ));
1605    }
1606
1607    state.external_assets -= amount;
1608    state.idle_assets = state
1609        .idle_assets
1610        .checked_add(amount)
1611        .ok_or_else(|| KernelError::from(InvalidStateCode::RebalanceWithdrawOverflowsIdleAssets))?;
1612    state.sync_total_assets();
1613
1614    let new_external_assets = state.external_assets;
1615    let total_assets = state.total_assets;
1616    Ok(KernelResult::new(
1617        state,
1618        vec![KernelEffect::EmitEvent {
1619            event: crate::effects::KernelEvent::ExternalAssetsSynced {
1620                op_id,
1621                new_external_assets,
1622                total_assets,
1623            },
1624        }],
1625    ))
1626}
1627
1628#[cfg(any(feature = "action-recovery", test))]
1629fn handle_abort_refreshing(mut state: VaultState, op_id: u64) -> Result<KernelResult, KernelError> {
1630    require_active_op_id(
1631        &state.op_state,
1632        op_id,
1633        InvalidStateCode::AbortRefreshingRequiresActiveOp,
1634    )?;
1635
1636    if !matches!(state.op_state, OpState::Refreshing(_)) {
1637        return Err(KernelError::from(
1638            InvalidStateCode::AbortRefreshingRequiresRefreshing,
1639        ));
1640    }
1641
1642    state.op_state = OpState::Idle;
1643    Ok(KernelResult::new(state, vec![]))
1644}
1645
1646#[cfg(any(feature = "action-recovery", test))]
1647fn handle_abort_allocating(mut state: VaultState, op_id: u64) -> Result<KernelResult, KernelError> {
1648    let alloc = match &state.op_state {
1649        OpState::Allocating(s) => s,
1650        _ => {
1651            return Err(KernelError::from(
1652                InvalidStateCode::AbortAllocatingRequiresAllocating,
1653            ))
1654        }
1655    };
1656
1657    check_op_id(alloc.op_id, op_id)?;
1658    state.restore_to_idle(alloc.remaining);
1659    state.op_state = OpState::Idle;
1660    Ok(KernelResult::new(state, vec![]))
1661}
1662
1663#[cfg(any(feature = "action-recovery", test))]
1664fn handle_abort_withdrawing(
1665    mut state: VaultState,
1666    self_id: &Address,
1667    op_id: u64,
1668) -> Result<KernelResult, KernelError> {
1669    let withdraw = match &state.op_state {
1670        OpState::Withdrawing(s) => s,
1671        _ => {
1672            return Err(KernelError::from(
1673                InvalidStateCode::AbortWithdrawingRequiresWithdrawing,
1674            ))
1675        }
1676    };
1677
1678    check_op_id(withdraw.op_id, op_id)?;
1679    validate_queue_head(
1680        &state.withdraw_queue,
1681        withdraw.request_id,
1682        &withdraw.owner,
1683        &withdraw.receiver,
1684        withdraw.escrow_shares,
1685    )?;
1686
1687    state.restore_to_idle(withdraw.collected);
1688
1689    let result = map_transition_result(stop_withdrawal(
1690        mem::take(&mut state.op_state),
1691        op_id,
1692        *self_id,
1693    ))?;
1694    state.op_state = result.new_state;
1695    state.withdraw_queue.dequeue();
1696    Ok(KernelResult::new(state, result.effects))
1697}
1698
1699#[inline]
1700pub(crate) fn plan_payout_settlement(
1701    payout: &PayoutState,
1702    outcome: PayoutOutcome,
1703) -> Result<PayoutSettlement, KernelError> {
1704    match outcome {
1705        PayoutOutcome::Success => {
1706            let burn_shares = payout.burn_shares;
1707            let refund_shares = payout
1708                .escrow_shares
1709                .checked_sub(payout.burn_shares)
1710                .ok_or_else(|| {
1711                    KernelError::from(InvalidStateCode::PayoutSuccessSettlementMismatch)
1712                })?;
1713            Ok(PayoutSettlement {
1714                burn_shares,
1715                refund_shares,
1716                completed_amount: payout.amount,
1717                success: true,
1718            })
1719        }
1720        PayoutOutcome::Failure => Ok(PayoutSettlement {
1721            burn_shares: 0,
1722            refund_shares: payout.escrow_shares,
1723            completed_amount: 0,
1724            success: false,
1725        }),
1726    }
1727}
1728
1729pub(crate) fn apply_payout_settlement(
1730    state: &mut VaultState,
1731    payout: &PayoutState,
1732    settlement: PayoutSettlement,
1733    escrow_address: Address,
1734    effects: &mut Vec<KernelEffect>,
1735) -> Result<(), KernelError> {
1736    if settlement.burn_shares > 0 {
1737        effects.push(KernelEffect::BurnShares {
1738            owner: escrow_address,
1739            shares: settlement.burn_shares,
1740        });
1741        state.total_shares = state
1742            .total_shares
1743            .checked_sub(settlement.burn_shares)
1744            .ok_or_else(|| KernelError::from(InvalidStateCode::PayoutBurnExceedsTotalShares))?;
1745    }
1746
1747    push_refund_shares(
1748        effects,
1749        escrow_address,
1750        payout.owner,
1751        settlement.refund_shares,
1752    );
1753
1754    if settlement.success {
1755        state.idle_assets = state
1756            .idle_assets
1757            .checked_sub(payout.amount)
1758            .ok_or_else(|| KernelError::from(InvalidStateCode::PayoutFailureRestoreIdleMismatch))?;
1759        state.sync_total_assets();
1760    }
1761
1762    state.op_state = OpState::Idle;
1763    Ok(())
1764}
1765
1766/// Settle a payout after asset transfer attempt (success or failure).
1767fn handle_settle_payout(
1768    mut state: VaultState,
1769    self_id: &Address,
1770    op_id: u64,
1771    outcome: PayoutOutcome,
1772) -> Result<KernelResult, KernelError> {
1773    let payout = match mem::take(&mut state.op_state) {
1774        OpState::Payout(s) => s,
1775        _ => {
1776            return Err(KernelError::from(
1777                InvalidStateCode::SettlePayoutRequiresPayout,
1778            ))
1779        }
1780    };
1781
1782    check_op_id(payout.op_id, op_id)?;
1783
1784    validate_queue_head(
1785        &state.withdraw_queue,
1786        payout.request_id,
1787        &payout.owner,
1788        &payout.receiver,
1789        payout.escrow_shares,
1790    )?;
1791
1792    let escrow_address = *self_id;
1793    let mut effects = Vec::new();
1794
1795    let settlement = plan_payout_settlement(&payout, outcome)?;
1796    apply_payout_settlement(
1797        &mut state,
1798        &payout,
1799        settlement,
1800        escrow_address,
1801        &mut effects,
1802    )?;
1803
1804    effects.push(KernelEffect::EmitEvent {
1805        event: KernelEvent::PayoutCompleted {
1806            op_id,
1807            success: settlement.success,
1808            burn_shares: settlement.burn_shares,
1809            refund_shares: settlement.refund_shares,
1810            amount: settlement.completed_amount,
1811        },
1812    });
1813
1814    state.withdraw_queue.dequeue();
1815    Ok(KernelResult::new(state, effects))
1816}
1817
1818#[cfg(any(feature = "action-refresh-fees", test))]
1819fn handle_refresh_fees(
1820    mut state: VaultState,
1821    config: &VaultConfig,
1822    now_ns: TimestampNs,
1823) -> Result<KernelResult, KernelError> {
1824    if !state.is_idle() {
1825        return Err(KernelError::from(InvalidStateCode::RefreshFeesRequiresIdle));
1826    }
1827
1828    // Reject backwards time to prevent fee calculation issues
1829    if now_ns < state.fee_anchor.timestamp_ns {
1830        return Err(KernelError::from(
1831            InvalidStateCode::FeeRefreshTimestampMustAdvance,
1832        ));
1833    }
1834
1835    let cur_total_assets = state.total_assets;
1836    let anchor = state.fee_anchor;
1837    let mut effects = Vec::new();
1838
1839    // An equal-timestamp refresh is permitted only when an actual performance
1840    // fee is due right now, so a gain booked at the anchor timestamp cannot
1841    // bypass fee crystallization via a same-ledger withdrawal or refresh.
1842    // When the configured growth-rate cap excludes the equal-time gain from
1843    // fee accrual, no fee is chargeable at zero elapsed time and the refresh
1844    // is rejected instead of re-anchoring that gain away uncharged.
1845    if now_ns == anchor.timestamp_ns && !performance_fee_is_due(&state, config) {
1846        return Err(KernelError::from(
1847            InvalidStateCode::FeeRefreshTimestampMustAdvance,
1848        ));
1849    }
1850    if state.total_shares > 0 && anchor.is_uninitialized() && cur_total_assets == 0 {
1851        state.fee_anchor = FeeAccrualAnchor::new(cur_total_assets, now_ns);
1852        effects.push(KernelEffect::EmitEvent {
1853            event: crate::effects::KernelEvent::FeesRefreshed {
1854                now_ns: now_ns.into(),
1855                total_assets: cur_total_assets,
1856            },
1857        });
1858        return Ok(KernelResult::new(state, effects));
1859    }
1860
1861    let accrual = compute_fee_accrual(
1862        cur_total_assets,
1863        state.total_shares,
1864        anchor,
1865        &config.fees,
1866        now_ns,
1867    )
1868    .map_err(|_| KernelError::from(InvalidStateCode::FeeMintOverflowTotalSupply))?;
1869
1870    if accrual.management_shares > 0 {
1871        effects.push(KernelEffect::MintShares {
1872            owner: config.fees.management.recipient,
1873            shares: accrual.management_shares,
1874        });
1875    }
1876    if accrual.performance_shares > 0 {
1877        effects.push(KernelEffect::MintShares {
1878            owner: config.fees.performance.recipient,
1879            shares: accrual.performance_shares,
1880        });
1881    }
1882
1883    state.total_shares = accrual.new_total_shares;
1884    state.fee_anchor = accrual.new_anchor;
1885
1886    effects.push(KernelEffect::EmitEvent {
1887        event: crate::effects::KernelEvent::FeesRefreshed {
1888            now_ns: now_ns.into(),
1889            total_assets: cur_total_assets,
1890        },
1891    });
1892
1893    Ok(KernelResult::new(state, effects))
1894}
1895
1896#[cfg(any(feature = "action-recovery", test))]
1897pub(crate) fn plan_emergency_reset(
1898    mut state: VaultState,
1899) -> Result<EmergencyResetOutcome, KernelError> {
1900    let prev_state = mem::take(&mut state.op_state);
1901    let from_code = prev_state.kind_code();
1902    let op_id = match prev_state.op_id() {
1903        Some(op_id) => op_id,
1904        None => {
1905            return Err(KernelError::from(
1906                InvalidStateCode::EmergencyResetAlreadyIdle,
1907            ))
1908        }
1909    };
1910
1911    let mut refund_owner = None;
1912    let mut refund_shares = 0;
1913
1914    match prev_state {
1915        OpState::Idle => {
1916            return Err(KernelError::from(
1917                InvalidStateCode::EmergencyResetAlreadyIdle,
1918            ))
1919        }
1920        OpState::Refreshing(_) => {
1921            // No assets in-flight, just reset.
1922        }
1923        OpState::Allocating(alloc) => {
1924            // Restore unallocated assets back to idle.
1925            state.restore_to_idle(alloc.remaining);
1926        }
1927        OpState::Withdrawing(w) => {
1928            refund_owner = Some(w.owner);
1929            refund_shares = w.escrow_shares;
1930            // Restore any collected assets back to idle.
1931            state.restore_to_idle(w.collected);
1932            state.withdraw_queue.dequeue();
1933        }
1934        OpState::Payout(p) => {
1935            refund_owner = Some(p.owner);
1936            refund_shares = p.escrow_shares;
1937            // Restore payout amount back to idle.
1938            state.restore_to_idle(p.amount);
1939            state.withdraw_queue.dequeue();
1940        }
1941    }
1942
1943    state.op_state = OpState::Idle;
1944    state.fee_anchor = FeeAccrualAnchor::new(state.total_assets, state.fee_anchor.timestamp_ns);
1945
1946    Ok(EmergencyResetOutcome {
1947        state,
1948        op_id,
1949        from_code,
1950        refund_owner,
1951        refund_shares,
1952    })
1953}
1954
1955#[cfg(any(feature = "action-recovery", test))]
1956pub(crate) fn handle_emergency_reset(
1957    state: VaultState,
1958    self_id: &Address,
1959) -> Result<KernelResult, KernelError> {
1960    let outcome = plan_emergency_reset(state)?;
1961    let mut effects = Vec::new();
1962    if let Some(owner) = outcome.refund_owner {
1963        push_refund_shares(&mut effects, *self_id, owner, outcome.refund_shares);
1964    }
1965    effects.push(KernelEffect::EmitEvent {
1966        event: KernelEvent::EmergencyResetCompleted {
1967            op_id: outcome.op_id,
1968            from_state: outcome.from_code,
1969        },
1970    });
1971
1972    Ok(KernelResult::new(outcome.state, effects))
1973}
1974
1975/// Apply a kernel action to state, returning updated state and effects.
1976#[allow(unused_mut)]
1977pub fn apply_action(
1978    mut state: VaultState,
1979    config: &VaultConfig,
1980    restrictions: Option<&Restrictions>,
1981    self_id: &Address,
1982    action: KernelAction,
1983) -> Result<KernelResult, KernelError> {
1984    dispatch::apply_action(state, config, restrictions, self_id, action)
1985}
1986
1987fn enforce_restrictions(
1988    config: &VaultConfig,
1989    restrictions: Option<&Restrictions>,
1990    self_id: &Address,
1991    actor: &Address,
1992) -> Result<(), KernelError> {
1993    access::enforce_restrictions(config, restrictions, self_id, actor)
1994}
1995
1996#[inline]
1997fn is_globally_paused(config: &VaultConfig, restrictions: Option<&Restrictions>) -> bool {
1998    let _ = restrictions;
1999    config.paused
2000}
2001
2002mod planning {
2003    use super::*;
2004
2005    pub(super) fn plan_idle_payout(
2006        state: &VaultState,
2007        min_withdrawal_assets: u128,
2008    ) -> Result<IdlePayoutPlan, KernelError> {
2009        let (request_owner, request_receiver, request_escrow, request_expected) = state
2010            .withdraw_queue
2011            .head()
2012            .map(|(_, request)| {
2013                (
2014                    request.owner,
2015                    request.receiver,
2016                    request.escrow_shares,
2017                    request.expected_assets,
2018                )
2019            })
2020            .ok_or_else(|| KernelError::from(InvalidStateCode::UnexpectedEmptyQueue))?;
2021
2022        let withdrawing = match &state.op_state {
2023            OpState::Withdrawing(withdrawing) => withdrawing,
2024            _ => {
2025                return Err(KernelError::from(
2026                    InvalidStateCode::ExecuteWithdrawRequiresIdleUseCallbacks,
2027                ))
2028            }
2029        };
2030
2031        if request_owner != withdrawing.owner
2032            || request_receiver != withdrawing.receiver
2033            || request_escrow != withdrawing.escrow_shares
2034        {
2035            return Err(KernelError::from(
2036                InvalidStateCode::WithdrawalQueueHeadMismatch,
2037            ));
2038        }
2039
2040        let available_assets = state.idle_assets;
2041        let _ = min_withdrawal_assets;
2042        if !has_actionable_withdrawal_liquidity(request_expected, available_assets) {
2043            return Err(KernelError::from(
2044                InvalidStateCode::WithdrawalLiquidityBelowMinimum,
2045            ));
2046        }
2047
2048        let Some(settlement) =
2049            compute_idle_settlement(request_escrow, request_expected, state.idle_assets)
2050        else {
2051            return Err(KernelError::from(
2052                InvalidStateCode::WithdrawalLiquidityBelowMinimum,
2053            ));
2054        };
2055
2056        if settlement.assets_out == 0 {
2057            return Err(KernelError::from(
2058                InvalidStateCode::WithdrawalLiquidityBelowMinimum,
2059            ));
2060        }
2061
2062        Ok(IdlePayoutPlan {
2063            op_id: withdrawing.op_id,
2064            request_id: withdrawing.request_id,
2065            owner: withdrawing.owner,
2066            receiver: withdrawing.receiver,
2067            assets_out: settlement.assets_out,
2068            burn_shares: settlement.settlement.to_burn,
2069        })
2070    }
2071}
2072
2073mod conversions {
2074    use super::*;
2075
2076    pub(super) fn effective_totals(state: &VaultState, config: &VaultConfig) -> EffectiveTotals {
2077        EffectiveTotals {
2078            supply: state
2079                .total_shares
2080                .saturating_add(config.virtual_shares.max(1)),
2081            assets: state
2082                .total_assets
2083                .saturating_add(config.virtual_assets.max(1)),
2084        }
2085    }
2086
2087    #[inline]
2088    fn real_basis_active(config: &VaultConfig, real_denominator: u128) -> bool {
2089        config.virtual_assets != 0 && real_denominator != 0
2090    }
2091
2092    #[inline(never)]
2093    fn virtual_basis_quote(
2094        state: &VaultState,
2095        config: &VaultConfig,
2096        amount: u128,
2097        to_shares: bool,
2098        round_up: bool,
2099    ) -> Number {
2100        let t = effective_totals(state, config);
2101        let (numerator, denominator) = if to_shares {
2102            (t.supply, t.assets)
2103        } else {
2104            (t.assets, t.supply)
2105        };
2106        Number::mul_div_with_rounding(
2107            Number::from(amount),
2108            Number::from(numerator),
2109            Number::from(denominator),
2110            round_up,
2111        )
2112    }
2113
2114    #[inline(never)]
2115    fn dual_basis_quote(
2116        state: &VaultState,
2117        config: &VaultConfig,
2118        amount: u128,
2119        to_shares: bool,
2120        round_up: bool,
2121    ) -> Number {
2122        let virtual_quote = virtual_basis_quote(state, config, amount, to_shares, round_up);
2123        let (real_numerator, real_denominator) = if to_shares {
2124            (state.total_shares, state.total_assets)
2125        } else {
2126            (state.total_assets, state.total_shares)
2127        };
2128        if !real_basis_active(config, real_denominator) {
2129            return virtual_quote;
2130        }
2131        let real_quote = Number::mul_div_with_rounding(
2132            Number::from(amount),
2133            Number::from(real_numerator),
2134            Number::from(real_denominator),
2135            round_up,
2136        );
2137        if to_shares {
2138            virtual_quote.max(real_quote)
2139        } else {
2140            virtual_quote.min(real_quote)
2141        }
2142    }
2143
2144    pub(super) fn convert_to_shares(
2145        state: &VaultState,
2146        config: &VaultConfig,
2147        assets: u128,
2148    ) -> u128 {
2149        u128::from(virtual_basis_quote(state, config, assets, true, false))
2150    }
2151
2152    pub(super) fn convert_to_shares_bounded(
2153        state: &VaultState,
2154        config: &VaultConfig,
2155        assets: u128,
2156        cap: u128,
2157        error: InvalidStateCode,
2158    ) -> Result<u128, KernelError> {
2159        bounded_u128(
2160            virtual_basis_quote(state, config, assets, true, false),
2161            cap,
2162            error,
2163        )
2164    }
2165
2166    pub(super) fn convert_to_assets(
2167        state: &VaultState,
2168        config: &VaultConfig,
2169        shares: u128,
2170    ) -> u128 {
2171        u128::from(virtual_basis_quote(state, config, shares, false, false))
2172    }
2173
2174    pub(super) fn convert_to_assets_bounded(
2175        state: &VaultState,
2176        config: &VaultConfig,
2177        shares: u128,
2178        cap: u128,
2179        error: InvalidStateCode,
2180    ) -> Result<u128, KernelError> {
2181        bounded_u128(
2182            virtual_basis_quote(state, config, shares, false, false),
2183            cap,
2184            error,
2185        )
2186    }
2187
2188    pub(super) fn convert_to_redeem_assets(
2189        state: &VaultState,
2190        config: &VaultConfig,
2191        shares: u128,
2192    ) -> u128 {
2193        dual_basis_quote(state, config, shares, false, false).as_u128_saturating()
2194    }
2195
2196    pub(super) fn convert_to_redeem_assets_bounded(
2197        state: &VaultState,
2198        config: &VaultConfig,
2199        shares: u128,
2200        cap: u128,
2201        error: InvalidStateCode,
2202    ) -> Result<u128, KernelError> {
2203        bounded_u128(
2204            dual_basis_quote(state, config, shares, false, false),
2205            cap,
2206            error,
2207        )
2208    }
2209
2210    pub(super) fn convert_to_shares_ceil(
2211        state: &VaultState,
2212        config: &VaultConfig,
2213        assets: u128,
2214    ) -> u128 {
2215        u128::from(virtual_basis_quote(state, config, assets, true, true))
2216    }
2217
2218    pub(super) fn convert_to_shares_ceil_bounded(
2219        state: &VaultState,
2220        config: &VaultConfig,
2221        assets: u128,
2222        cap: u128,
2223        error: InvalidStateCode,
2224    ) -> Result<u128, KernelError> {
2225        bounded_u128(
2226            virtual_basis_quote(state, config, assets, true, true),
2227            cap,
2228            error,
2229        )
2230    }
2231    pub(super) fn convert_to_withdraw_shares_ceil_bounded(
2232        state: &VaultState,
2233        config: &VaultConfig,
2234        assets: u128,
2235        cap: u128,
2236        error: InvalidStateCode,
2237    ) -> Result<u128, KernelError> {
2238        bounded_u128(
2239            dual_basis_quote(state, config, assets, true, true),
2240            cap,
2241            error,
2242        )
2243    }
2244
2245    pub(super) fn convert_to_withdrawable_shares(
2246        state: &VaultState,
2247        config: &VaultConfig,
2248        assets: u128,
2249    ) -> u128 {
2250        dual_basis_quote(state, config, assets, true, false).as_u128_saturating()
2251    }
2252
2253    pub(super) fn convert_to_assets_ceil(
2254        state: &VaultState,
2255        config: &VaultConfig,
2256        shares: u128,
2257    ) -> u128 {
2258        u128::from(virtual_basis_quote(state, config, shares, false, true))
2259    }
2260
2261    pub(super) fn convert_to_assets_ceil_bounded(
2262        state: &VaultState,
2263        config: &VaultConfig,
2264        shares: u128,
2265        cap: u128,
2266        error: InvalidStateCode,
2267    ) -> Result<u128, KernelError> {
2268        bounded_u128(
2269            virtual_basis_quote(state, config, shares, false, true),
2270            cap,
2271            error,
2272        )
2273    }
2274
2275    fn bounded_u128(
2276        quotient: Number,
2277        cap: u128,
2278        error: InvalidStateCode,
2279    ) -> Result<u128, KernelError> {
2280        if quotient > Number::from(cap) {
2281            return Err(KernelError::from(error));
2282        }
2283        Ok(quotient.as_u128_trunc())
2284    }
2285}
2286
2287mod access {
2288    use super::*;
2289
2290    pub(super) fn enforce_restrictions(
2291        config: &VaultConfig,
2292        restrictions: Option<&Restrictions>,
2293        _self_id: &Address,
2294        actor: &Address,
2295    ) -> Result<(), KernelError> {
2296        if config.paused {
2297            return Err(KernelError::Restricted(RestrictionKind::Paused));
2298        }
2299        if let Some(restrictions) = restrictions {
2300            if let Some(kind) = restrictions.is_restricted(actor) {
2301                return Err(KernelError::Restricted(kind));
2302            }
2303        }
2304        Ok(())
2305    }
2306}
2307
2308mod dispatch {
2309    use super::*;
2310
2311    #[allow(unused_mut)]
2312    #[allow(clippy::too_many_lines)]
2313    pub(super) fn apply_action(
2314        mut state: VaultState,
2315        config: &VaultConfig,
2316        restrictions: Option<&Restrictions>,
2317        self_id: &Address,
2318        action: KernelAction,
2319    ) -> Result<KernelResult, KernelError> {
2320        match action {
2321            KernelAction::Deposit {
2322                owner,
2323                receiver,
2324                assets_in,
2325                min_shares_out,
2326                now_ns,
2327            } => handle_deposit(
2328                state,
2329                config,
2330                restrictions,
2331                self_id,
2332                owner,
2333                receiver,
2334                assets_in,
2335                min_shares_out,
2336                now_ns,
2337            ),
2338
2339            KernelAction::AtomicWithdraw {
2340                owner,
2341                receiver,
2342                operator,
2343                assets_out,
2344                max_shares_burned,
2345                now_ns,
2346            } => handle_atomic_withdraw(
2347                state,
2348                config,
2349                restrictions,
2350                self_id,
2351                owner,
2352                receiver,
2353                operator,
2354                assets_out,
2355                max_shares_burned,
2356                now_ns,
2357            ),
2358
2359            KernelAction::AtomicRedeem {
2360                owner,
2361                receiver,
2362                operator,
2363                shares,
2364                min_assets_out,
2365                now_ns,
2366            } => handle_atomic_redeem(
2367                state,
2368                config,
2369                restrictions,
2370                self_id,
2371                owner,
2372                receiver,
2373                operator,
2374                shares,
2375                min_assets_out,
2376                now_ns,
2377            ),
2378
2379            KernelAction::RequestWithdraw {
2380                owner,
2381                receiver,
2382                shares,
2383                min_assets_out,
2384                now_ns,
2385            } => handle_request_withdraw(
2386                state,
2387                config,
2388                restrictions,
2389                self_id,
2390                owner,
2391                receiver,
2392                shares,
2393                min_assets_out,
2394                now_ns,
2395            ),
2396
2397            KernelAction::ExecuteWithdraw { now_ns } => {
2398                handle_execute_withdraw(state, config, restrictions, self_id, now_ns)
2399            }
2400
2401            #[cfg(any(feature = "action-allocation-lifecycle", test))]
2402            KernelAction::BeginAllocating { op_id, plan, .. } => {
2403                handle_begin_allocating(state, op_id, plan)
2404            }
2405            #[cfg(not(any(feature = "action-allocation-lifecycle", test)))]
2406            KernelAction::BeginAllocating { .. } => Err(KernelError::NotImplemented),
2407
2408            #[cfg(any(feature = "action-allocation-lifecycle", test))]
2409            KernelAction::FinishAllocating { op_id, now_ns } => {
2410                handle_finish_allocating(state, config, restrictions, self_id, op_id, now_ns)
2411            }
2412            #[cfg(not(any(feature = "action-allocation-lifecycle", test)))]
2413            KernelAction::FinishAllocating { .. } => Err(KernelError::NotImplemented),
2414
2415            #[cfg(any(feature = "action-refresh-lifecycle", test))]
2416            KernelAction::BeginRefreshing { op_id, plan, .. } => {
2417                let transition = start_refresh(mem::take(&mut state.op_state), plan, op_id);
2418                apply_transition_result(state, transition)
2419            }
2420            #[cfg(not(any(feature = "action-refresh-lifecycle", test)))]
2421            KernelAction::BeginRefreshing { .. } => Err(KernelError::NotImplemented),
2422
2423            #[cfg(any(feature = "action-refresh-lifecycle", test))]
2424            KernelAction::FinishRefreshing { op_id, .. } => {
2425                let transition = complete_refresh(mem::take(&mut state.op_state), op_id);
2426                apply_transition_result(state, transition)
2427            }
2428            #[cfg(not(any(feature = "action-refresh-lifecycle", test)))]
2429            KernelAction::FinishRefreshing { .. } => Err(KernelError::NotImplemented),
2430
2431            #[cfg(any(feature = "action-sync-external", test))]
2432            KernelAction::SyncExternalAssets {
2433                new_external_assets,
2434                op_id,
2435                ..
2436            } => handle_sync_external_assets(state, new_external_assets, op_id),
2437            #[cfg(not(any(feature = "action-sync-external", test)))]
2438            KernelAction::SyncExternalAssets { .. } => Err(KernelError::NotImplemented),
2439
2440            #[cfg(any(feature = "action-sync-external", test))]
2441            KernelAction::RebalanceWithdraw { op_id, amount, .. } => {
2442                handle_rebalance_withdraw(state, op_id, amount)
2443            }
2444            #[cfg(not(any(feature = "action-sync-external", test)))]
2445            KernelAction::RebalanceWithdraw { .. } => Err(KernelError::NotImplemented),
2446
2447            #[cfg(any(feature = "action-recovery", test))]
2448            KernelAction::AbortRefreshing { op_id } => handle_abort_refreshing(state, op_id),
2449            #[cfg(not(any(feature = "action-recovery", test)))]
2450            KernelAction::AbortRefreshing { .. } => Err(KernelError::NotImplemented),
2451
2452            #[cfg(any(feature = "action-recovery", test))]
2453            KernelAction::AbortAllocating { op_id } => handle_abort_allocating(state, op_id),
2454            #[cfg(not(any(feature = "action-recovery", test)))]
2455            KernelAction::AbortAllocating { .. } => Err(KernelError::NotImplemented),
2456
2457            #[cfg(any(feature = "action-recovery", test))]
2458            KernelAction::AbortWithdrawing { op_id } => {
2459                handle_abort_withdrawing(state, self_id, op_id)
2460            }
2461            #[cfg(not(any(feature = "action-recovery", test)))]
2462            KernelAction::AbortWithdrawing { .. } => Err(KernelError::NotImplemented),
2463
2464            KernelAction::SettlePayout { op_id, outcome } => {
2465                handle_settle_payout(state, self_id, op_id, outcome)
2466            }
2467
2468            #[cfg(any(feature = "action-pause", test))]
2469            KernelAction::Pause { paused } => Ok(KernelResult::new(
2470                state,
2471                vec![KernelEffect::EmitEvent {
2472                    event: crate::effects::KernelEvent::PauseUpdated { paused },
2473                }],
2474            )),
2475            #[cfg(not(any(feature = "action-pause", test)))]
2476            KernelAction::Pause { .. } => Err(KernelError::NotImplemented),
2477
2478            #[cfg(any(feature = "action-refresh-fees", test))]
2479            KernelAction::RefreshFees { now_ns } => handle_refresh_fees(state, config, now_ns),
2480            #[cfg(not(any(feature = "action-refresh-fees", test)))]
2481            KernelAction::RefreshFees { .. } => Err(KernelError::NotImplemented),
2482
2483            #[cfg(any(feature = "action-recovery", test))]
2484            KernelAction::EmergencyReset => handle_emergency_reset(state, self_id),
2485            #[cfg(not(any(feature = "action-recovery", test)))]
2486            KernelAction::EmergencyReset => Err(KernelError::NotImplemented),
2487        }
2488    }
2489}
2490
2491// Tests
2492
2493#[cfg(test)]
2494mod tests;