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