templar_common/vault/
mod.rs

1use std::num::NonZeroU8;
2
3use derive_more::{Display, From, Into};
4
5use crate::vault::wad::Wad;
6use crate::{
7    asset::{BorrowAsset, FungibleAsset},
8    supply::SupplyPosition,
9};
10pub use external::*;
11use near_sdk::{
12    env,
13    json_types::{U128, U64},
14    near, require, AccountId, Gas, Promise, PromiseOrValue,
15};
16pub use templar_curator_primitives::{
17    CapGroupId, CapGroupRecord, CapGroupUpdate, CapGroupUpdateKey,
18};
19pub use templar_vault_kernel::state::op_state::{
20    AllocatingState, IdleState, OpState, PayoutState, RefreshingState, TargetId, WithdrawingState,
21};
22pub use templar_vault_kernel::types::{ActualIdx, ExpectedIdx, TimestampNs};
23
24pub use event::{
25    AllocationPositionIssueKind, Event, PositionReportOutcome, QueueAction, QueueStatus, Reason,
26    UnbrickPhase, WithdrawProgressPhase, WithdrawalAccountingKind,
27};
28pub use params::*;
29
30pub mod errors;
31pub mod event;
32pub mod external;
33pub mod gas;
34pub mod lock;
35pub mod params;
36pub mod restrictions;
37pub mod wad;
38
39pub use errors::Error;
40pub use gas::*;
41pub use lock::Locker;
42pub use restrictions::*;
43
44/// Broad import surface for vault consumers.
45///
46/// Prefer `use templar_common::vault::prelude::*;` at call sites that need
47/// most vault types, constants, and wad/math helpers.
48pub mod prelude {
49    pub use super::event::{
50        AllocationPositionIssueKind, Event, PositionReportOutcome, QueueAction, QueueStatus,
51        Reason, UnbrickPhase, WithdrawProgressPhase, WithdrawalAccountingKind,
52    };
53    pub use super::external::*;
54    pub use super::gas::*;
55    pub use super::params::*;
56    pub use super::restrictions::*;
57    pub use super::wad::{
58        compute_fee_shares, compute_fee_shares_from_assets, mul_div_ceil, mul_div_floor,
59        mul_wad_floor, Wad, MAX_FEE_WAD, MAX_MANAGEMENT_FEE_WAD, MAX_PERFORMANCE_FEE_WAD,
60    };
61    pub use super::wad::{Number, WIDE};
62    pub use super::{
63        require_at_least, storage_bytes_for_account_id, ActualIdx, AllocationDelta, AllocationPlan,
64        AllocationWeights, CapGroupId, CapGroupRecord, CapGroupUpdate, CapGroupUpdateKey, Delta,
65        DepositMsg, Error, EscrowSettlement, ExpectedIdx, Fee, FeeAccrualAnchor, Fees,
66        IdleBalanceDelta, IdleResyncOutcome, Locker, MarketConfiguration, MarketId,
67        PendingWithdrawal, RealAssetsReport, ResyncIdleReport, TimestampNs, VaultConfiguration,
68    };
69}
70
71pub type AllocationWeights = Vec<(MarketId, U128)>;
72pub type AllocationPlan = Vec<(MarketId, u128)>;
73
74/// Report of real (live) total assets broken down by market, used for AUM refresh.
75#[derive(Debug, Clone)]
76#[near(serializers = [borsh, json])]
77pub struct RealAssetsReport {
78    pub total_assets: U128,
79    pub per_market: Vec<(MarketId, U128)>,
80    /// Block timestamp in nanoseconds when this report was generated.
81    pub refreshed_at: U64,
82}
83
84/// Outcome of an idle balance resynchronization attempt.
85#[derive(Debug, Clone, PartialEq, Eq)]
86#[near(serializers = [borsh, json])]
87pub enum IdleResyncOutcome {
88    /// Resync succeeded.
89    Ok,
90    /// `ft_balance_of` call failed.
91    BalanceReadFailed,
92    /// Vault not in expected state.
93    UnexpectedState,
94    /// Resync was a no-op (e.g. cooldown not elapsed).
95    Ignored,
96}
97
98/// Detailed report from an idle balance resync operation.
99#[derive(Debug, Clone, PartialEq, Eq)]
100#[near(serializers = [borsh, json])]
101pub struct ResyncIdleReport {
102    pub outcome: IdleResyncOutcome,
103    /// Balance snapshot before resync.
104    pub before_idle: U128,
105    /// Actual idle balance read from contract.
106    pub actual_idle: U128,
107    /// Balance snapshot after resync.
108    pub after_idle: U128,
109    /// Magnitude of increase adjustment.
110    pub increased_by: U128,
111    /// Magnitude of decrease adjustment.
112    pub decreased_by: U128,
113    /// Amount added to fee anchor to prevent donation fees.
114    pub fee_anchor_bump: U128,
115    /// Completion timestamp in nanoseconds.
116    pub resynced_at_ns: U64,
117}
118
119#[derive(
120    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, From, Into, Display,
121)]
122#[near(serializers = [borsh, json])]
123#[display("{_0}")]
124pub struct MarketId(pub u32);
125
126impl From<MarketId> for u64 {
127    fn from(value: MarketId) -> Self {
128        u64::from(value.0)
129    }
130}
131
132impl TryFrom<u64> for MarketId {
133    type Error = <u32 as TryFrom<u64>>::Error;
134
135    fn try_from(value: u64) -> Result<Self, Self::Error> {
136        u32::try_from(value).map(Self)
137    }
138}
139
140/// Parsed from the string parameter `msg` passed by `*_transfer_call` to
141/// `*_on_transfer` calls.
142#[near(serializers = [json])]
143pub enum DepositMsg {
144    /// Add the attached tokens to the sender's vault position.
145    Supply,
146}
147
148/// Concrete configuration for a market.
149#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
150#[derive(Clone, Default)]
151#[near]
152pub struct MarketConfiguration {
153    /// Supply cap for this market (in underlying asset units)
154    pub cap: U128,
155    /// Whether market is enabled for deposits/withdrawals
156    pub enabled: bool,
157    /// Timestamp after which market can be removed (if pending removal)
158    pub removable_at: TimestampNs,
159    /// Cap group identifier used to throttle correlated exposure
160    pub cap_group_id: Option<CapGroupId>,
161}
162
163/// A fee configuration pairing a fee rate with its recipient.
164#[derive(Clone, Debug, PartialEq, Eq)]
165#[near(serializers = [borsh, json])]
166pub struct Fee<T> {
167    pub fee: T,
168    pub recipient: AccountId,
169}
170
171/// Complete fee configuration for the vault, including performance and management fees.
172#[derive(Clone, Debug, PartialEq, Eq)]
173#[near(serializers = [borsh, json])]
174pub struct Fees<T> {
175    pub performance: Fee<T>,
176    pub management: Fee<T>,
177    /// Optional cap on how fast `total_assets` is allowed to grow for fee accrual.
178    ///
179    /// Interpreted as an annualized WAD rate (1e18 = 100% per year). When set,
180    /// fee accrual uses `min(cur_total_assets, last_total_assets * (1 + max_rate * dt / YEAR))`
181    /// as the effective `cur_total_assets`.
182    pub max_total_assets_growth_rate: Option<T>,
183}
184
185impl From<Fee<Wad>> for Fee<U128> {
186    fn from(value: Fee<Wad>) -> Self {
187        Self {
188            fee: U128(u128::from(value.fee)),
189            recipient: value.recipient,
190        }
191    }
192}
193
194impl From<Fees<Wad>> for Fees<U128> {
195    fn from(value: Fees<Wad>) -> Self {
196        Self {
197            performance: value.performance.into(),
198            management: value.management.into(),
199            max_total_assets_growth_rate: value
200                .max_total_assets_growth_rate
201                .map(|rate| U128(u128::from(rate))),
202        }
203    }
204}
205
206impl From<Fee<U128>> for Fee<Wad> {
207    fn from(value: Fee<U128>) -> Self {
208        Self {
209            fee: Wad::from(value.fee.0),
210            recipient: value.recipient,
211        }
212    }
213}
214
215impl From<Fees<U128>> for Fees<Wad> {
216    fn from(value: Fees<U128>) -> Self {
217        Self {
218            performance: value.performance.into(),
219            management: value.management.into(),
220            max_total_assets_growth_rate: value
221                .max_total_assets_growth_rate
222                .map(|rate| rate.0.into()),
223        }
224    }
225}
226
227/// Configuration for the setup of a metavault.
228#[derive(Clone)]
229#[near(serializers = [json, borsh])]
230pub struct VaultConfiguration {
231    /// The account that owns this vault.
232    pub owner: AccountId,
233    /// The account that can submit allocation plans. See [`AllocationPlan`].
234    pub curator: AccountId,
235    /// The emergency role that can cancel withdrawals and trigger deallocations.
236    pub sentinel: AccountId,
237    /// The underlying asset for this vault.
238    pub underlying_token: FungibleAsset<BorrowAsset>,
239    /// The initial timelock for this vault used for modifying the configuration.
240    pub initial_timelock_ns: U64,
241    /// Fee configuration for performance and management fees as well as their recipients.
242    pub fees: Fees<Wad>,
243    /// The skim account that can unorphan any assets erroneously sent to this vault.
244    pub skim_recipient: AccountId,
245    /// The name of the share token.
246    pub name: String,
247    /// The symbol of the share token.
248    pub symbol: String,
249    /// The number of decimals for the share token, usually would be the same as the underlying asset.
250    pub decimals: NonZeroU8,
251    /// Restrictions for this vault.
252    pub restrictions: Option<Restrictions>,
253    /// Optional cooldown (ns) between `refresh_markets` calls; defaults to 30 seconds when `None`.
254    pub refresh_cooldown_ns: Option<U64>,
255    /// Optional cooldown (ns) between `idle_resync` calls; defaults to 120 seconds when `None`.
256    pub idle_resync_cooldown_ns: Option<U64>,
257    /// Optional cooldown (ns) before a withdrawal can be executed; defaults to 1 hour when `None`.
258    pub withdrawal_cooldown_ns: Option<U64>,
259    /// Optional maximum NAV age (ns) accepted for deposits; Soroban-only, ignored by the NEAR vault.
260    pub max_nav_age_ns: Option<U64>,
261}
262
263/// A single market allocation delta specifying a market and an amount in underlying asset units.
264#[derive(Debug, Clone)]
265#[near(serializers = [borsh, json])]
266pub struct Delta {
267    pub market: MarketId,
268    pub amount: U128,
269}
270
271impl Delta {
272    pub fn new<T: Into<U128>>(market: MarketId, amount: T) -> Self {
273        Delta {
274            market,
275            amount: amount.into(),
276        }
277    }
278    pub fn validate(&self) {
279        require!(self.amount.0 > 0, "Delta amount must be greater than zero");
280    }
281}
282
283/// Allocation instruction for a single market. `Supply` forwards idle assets to the market. `Withdraw` creates a supply-withdrawal request in the market (does not execute it).
284#[derive(Debug, Clone)]
285#[near(serializers = [borsh, json])]
286pub enum AllocationDelta {
287    Supply(Delta),
288    Withdraw(Delta),
289}
290
291impl AsRef<Delta> for AllocationDelta {
292    fn as_ref(&self) -> &Delta {
293        match self {
294            AllocationDelta::Supply(d) | AllocationDelta::Withdraw(d) => d,
295        }
296    }
297}
298
299/// Settlement breakdown for escrowed withdrawal shares. Invariant: `to_burn + refund == original escrow_shares`.
300#[derive(Debug, Clone, Copy)]
301pub struct EscrowSettlement {
302    pub to_burn: u128,
303    pub refund: u128,
304}
305
306impl EscrowSettlement {
307    pub fn new(escrow_shares: u128, burn_shares: u128) -> Self {
308        let settlement = templar_vault_kernel::types::EscrowSettlement::from_escrow_and_burn(
309            escrow_shares,
310            burn_shares,
311        );
312        Self {
313            to_burn: settlement.to_burn,
314            refund: settlement.refund,
315        }
316    }
317}
318
319impl From<EscrowSettlement> for (u128, u128) {
320    fn from(tuple: EscrowSettlement) -> Self {
321        (tuple.to_burn, tuple.refund)
322    }
323}
324
325/// A queued withdrawal request with shares held in escrow. Fields use underlying asset units for `expected_assets` and nanosecond timestamps for `requested_at`.
326#[derive(Clone, Debug)]
327#[near(serializers = [borsh])]
328pub struct PendingWithdrawal {
329    pub owner: AccountId,
330    pub receiver: AccountId,
331    pub escrow_shares: u128,
332    pub expected_assets: u128,
333    pub requested_at: u64,
334}
335
336impl PendingWithdrawal {
337    #[must_use]
338    pub fn encoded_size() -> u64 {
339        storage_bytes_for_account_id()
340            + storage_bytes_for_account_id()
341            + 16  // escrow_shares: u128
342            + 16  // expected_assets: u128
343            + 8 // requested_at: u64
344    }
345}
346
347// Worst case size encoded for AccountId
348#[must_use]
349pub const fn storage_bytes_for_account_id() -> u64 {
350    // 4 bytes for length prefix + worst case size encoded for AccountId
351    4 + AccountId::MAX_LEN as u64
352}
353
354/// Direction and magnitude of an idle balance change. Emits an `IdleBalanceUpdated` event when applied.
355#[derive(Clone, Debug)]
356#[near(serializers = [borsh, json])]
357pub enum IdleBalanceDelta {
358    Increase(U128),
359    Decrease(U128),
360}
361
362impl IdleBalanceDelta {
363    pub fn apply(&self, balance: u128) -> u128 {
364        let new = match self {
365            IdleBalanceDelta::Increase(amount) => balance.saturating_add(amount.0),
366            IdleBalanceDelta::Decrease(amount) => balance.saturating_sub(amount.0),
367        };
368        Event::IdleBalanceUpdated {
369            prev: U128::from(balance),
370            delta: self.clone(),
371        }
372        .emit();
373        new
374    }
375}
376
377/// Anchor point for fee accrual: stores the total assets and nanosecond timestamp at which fees were last accrued.
378#[near(serializers = [borsh, json])]
379#[derive(Debug, Clone, Default)]
380pub struct FeeAccrualAnchor {
381    pub total_assets: U128,
382    pub timestamp_ns: U64,
383}
384
385#[cfg(test)]
386mod tests {
387    use super::{Fee, Fees, MarketId};
388    use crate::vault::wad::Wad;
389    use near_sdk::json_types::U128;
390    use near_sdk::AccountId;
391
392    #[test]
393    fn market_id_try_from_u64_accepts_u32_range() {
394        assert_eq!(
395            MarketId::try_from(u64::from(u32::MAX)),
396            Ok(MarketId(u32::MAX))
397        );
398    }
399
400    #[test]
401    fn market_id_try_from_u64_rejects_out_of_range() {
402        assert!(MarketId::try_from(u64::from(u32::MAX) + 1).is_err());
403    }
404
405    #[test]
406    fn fees_roundtrip_between_u128_and_wad_preserves_values() {
407        let fees_u128 = Fees {
408            performance: Fee {
409                fee: U128(10),
410                recipient: "perf.testnet"
411                    .parse::<AccountId>()
412                    .expect("valid account id"),
413            },
414            management: Fee {
415                fee: U128(20),
416                recipient: "mgmt.testnet"
417                    .parse::<AccountId>()
418                    .expect("valid account id"),
419            },
420            max_total_assets_growth_rate: Some(U128(30)),
421        };
422
423        let fees_wad: Fees<Wad> = fees_u128.clone().into();
424        assert_eq!(u128::from(fees_wad.performance.fee), 10);
425        assert_eq!(u128::from(fees_wad.management.fee), 20);
426        assert_eq!(
427            fees_wad
428                .max_total_assets_growth_rate
429                .map(u128::from)
430                .expect("max rate must be present"),
431            30
432        );
433
434        let roundtrip: Fees<U128> = fees_wad.into();
435        assert_eq!(roundtrip.performance.fee.0, 10);
436        assert_eq!(roundtrip.management.fee.0, 20);
437        assert_eq!(
438            roundtrip.max_total_assets_growth_rate.map(|v| v.0),
439            Some(30)
440        );
441        assert_eq!(roundtrip.performance.recipient.as_str(), "perf.testnet");
442        assert_eq!(roundtrip.management.recipient.as_str(), "mgmt.testnet");
443    }
444}