Skip to main content

df_hyperliquid_core/earn/vaults/
plan.rs

1//! From a vault move's typed values to exactly what is signed: the action,
2//! its nonce, the key it needs, the equity that should change once it lands,
3//! and when a deposit unlocks.
4
5use crate::account::Signers;
6use crate::client::Network;
7use crate::earn::vaults::reads::{VaultDetails, VaultEquity};
8use crate::earn::vaults::transfer::{VaultTransfer, lockup_ms};
9use crate::utils::{Address, BadUnits, Dec, USDC_DECIMALS, cut_units};
10
11/// A figure a read back checks.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum Balance {
15    /// The account's equity in a vault: its `userVaultEquities` row. The perp
16    /// USDC on the other side moves by exactly the amount.
17    Vault(Address),
18}
19
20/// How the equity moves once the action lands. The vault's profit and loss
21/// moves it too, so a read back shows the direction, by about the amount.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum Change {
25    /// Rises by about this much USDC.
26    Rises(Dec),
27    /// Falls by about this much USDC.
28    Falls(Dec),
29}
30
31/// The equity an action changes, and what reading it back should show.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct Effect {
35    /// The equity that changes.
36    pub balance: Balance,
37    /// How it changes.
38    pub change: Change,
39}
40
41impl Effect {
42    /// Whether `after`, read back, shows the action landed against `before`.
43    #[must_use]
44    pub fn landed(&self, before: Dec, after: Dec) -> bool {
45        match self.change {
46            Change::Rises(_) => after > before,
47            Change::Falls(_) => after < before,
48        }
49    }
50}
51
52/// Exactly what is signed, and what to check once it lands.
53#[derive(Debug, Clone, PartialEq, Eq)]
54#[non_exhaustive]
55pub struct Plan<A> {
56    /// The network the action is signed for.
57    pub network: Network,
58    /// The action signed.
59    pub action: A,
60    /// The nonce it is signed with, in milliseconds.
61    pub nonce: u64,
62    /// Which keys may sign it.
63    pub key: Signers,
64    /// The equity that should change, to check once it lands.
65    pub effect: Effect,
66    /// When a deposit may first be withdrawn, milliseconds.
67    pub free_at: Option<u64>,
68}
69
70/// Why a move is not signed.
71#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
72#[non_exhaustive]
73pub enum Refused {
74    /// The vault is closed or takes no deposits; holds its address.
75    #[error("{0} takes no deposits")]
76    NoDeposits(Address),
77    /// The deposit is still in its lockup.
78    #[error("locked until {until} ms")]
79    Locked {
80        /// When the lockup ends, milliseconds.
81        until: u64,
82    },
83    /// An amount over the equity held.
84    #[error("{amount} USDC is more than the {held} there is")]
85    MoreThan {
86        /// The USDC asked for.
87        amount: Dec,
88        /// The USDC equity there is.
89        held: Dec,
90    },
91    /// The amount has more than six decimal places.
92    #[error(transparent)]
93    Units(#[from] BadUnits),
94}
95
96/// Everything outside the amounts that a plan is made from.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct Ctx {
99    /// The network the action is signed for.
100    pub network: Network,
101    /// The nonce to sign with, in milliseconds.
102    pub nonce: u64,
103    /// Now, milliseconds: a lockup is measured from it.
104    pub now_ms: u64,
105}
106
107impl Ctx {
108    const fn plan(&self, action: VaultTransfer, change: Change, free_at: Option<u64>) -> Plan<VaultTransfer> {
109        let effect = Effect { balance: Balance::Vault(action.vault()), change };
110        Plan { network: self.network, action, nonce: self.nonce, key: VaultTransfer::KEY, effect, free_at }
111    }
112
113    /// USDC from the perp balance into `vault`, locked for its lockup.
114    pub fn deposit(&self, vault: &VaultDetails, usdc: Dec) -> Result<Plan<VaultTransfer>, Refused> {
115        let action = VaultTransfer::deposit(vault.vault_address, usdc)?;
116        if !vault.takes_deposits() {
117            return Err(Refused::NoDeposits(vault.vault_address));
118        }
119        let free_at = self.now_ms.saturating_add(lockup_ms(self.network, vault.vault_address));
120        Ok(self.plan(action, Change::Rises(usdc), Some(free_at)))
121    }
122
123    /// `usdc` out of the vault `equity` is in, once its lockup has passed.
124    pub fn withdraw(&self, equity: &VaultEquity, usdc: Dec) -> Result<Plan<VaultTransfer>, Refused> {
125        let action = VaultTransfer::withdraw(equity.vault_address, usdc)?;
126        unlocked(equity, self.now_ms)?;
127        if usdc > equity.equity {
128            return Err(Refused::MoreThan { amount: usdc, held: equity.equity });
129        }
130        Ok(self.plan(action, Change::Falls(usdc), None))
131    }
132
133    /// The whole equity, cut to millionths so it never asks for more.
134    pub fn withdraw_all(&self, equity: &VaultEquity) -> Result<Plan<VaultTransfer>, Refused> {
135        unlocked(equity, self.now_ms)?;
136        let usd = cut_units(equity.equity, USDC_DECIMALS)?;
137        let action = VaultTransfer::from_micros(equity.vault_address, false, usd);
138        let amount = equity.withdrawable(self.now_ms);
139        Ok(self.plan(action, Change::Falls(amount), None))
140    }
141}
142
143fn unlocked(equity: &VaultEquity, now_ms: u64) -> Result<(), Refused> {
144    match equity.is_locked(now_ms) {
145        true => Err(Refused::Locked { until: equity.locked_until_timestamp }),
146        false => Ok(()),
147    }
148}
149
150#[cfg(test)]
151#[path = "tests/plan.rs"]
152mod tests;