Skip to main content

df_hyperliquid_core/earn/staking/
plan.rs

1//! From a staking move's typed values to exactly what is signed: the action,
2//! its nonce, the key it needs, the balance that should change once it lands,
3//! and when what it moved is free again.
4
5use crate::account::Signers;
6use crate::client::Network;
7use crate::earn::staking::actions::{CDeposit, CWithdraw, TokenDelegate};
8use crate::earn::staking::reads::{Delegation, DelegatorSummary, MAX_PENDING_WITHDRAWALS, locked_until, unstaking_ms};
9use crate::utils::{Address, BadUnits, Dec};
10
11/// A figure a read back checks.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub enum Balance {
14    /// The staking balance free to delegate or withdraw:
15    /// `delegatorSummary`'s `undelegated`.
16    Undelegated,
17    /// What is delegated to one validator: its `delegations` row.
18    Delegated(Address),
19    /// On its way to spot: `delegatorSummary`'s `totalPendingWithdrawal`.
20    Pending,
21}
22
23/// How the figure moves once the action lands: by exactly the amount.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Change {
26    /// Rises by exactly this much HYPE.
27    Up(Dec),
28    /// Falls by exactly this much HYPE.
29    Down(Dec),
30}
31
32/// The balance an action changes, and what reading it back should show.
33///
34/// Every move here is read back on the staking balance: each one passes
35/// through it, and rewards do not (they are added to the delegations), so it
36/// moves by exactly the amount. The other side moves too: spot HYPE for a
37/// deposit, the delegation for a delegate, the queue for a withdrawal.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct Effect {
40    /// The balance that changes.
41    pub balance: Balance,
42    /// How it changes.
43    pub change: Change,
44}
45
46impl Effect {
47    /// Whether `after`, read back, shows the action landed against `before`.
48    #[must_use]
49    pub fn landed(&self, before: Dec, after: Dec) -> bool {
50        match self.change {
51            Change::Up(amount) => before.checked_add(amount) == Some(after),
52            Change::Down(amount) => before.checked_sub(amount) == Some(after),
53        }
54    }
55}
56
57/// Exactly what is signed, and what to check once it lands.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Plan<A> {
60    /// The network the action is signed for.
61    pub network: Network,
62    /// The action signed.
63    pub action: A,
64    /// What it is signed with; the action carries it too.
65    pub nonce: u64,
66    /// Which keys may sign it.
67    pub key: Signers,
68    /// The balance that should change, to check once it lands.
69    pub effect: Effect,
70    /// When what it moved is free again, milliseconds: a delegation's lock
71    /// ends, or a withdrawal reaches spot.
72    pub free_at: Option<u64>,
73}
74
75/// Why a move is not signed.
76#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
77pub enum Refused {
78    /// An amount over what the staking balance or the delegation holds.
79    #[error("{amount} HYPE is more than the {held} there is")]
80    MoreThan {
81        /// The HYPE asked for.
82        amount: Dec,
83        /// The HYPE there is.
84        held: Dec,
85    },
86    /// Nothing is delegated to the validator; holds its address.
87    #[error("nothing is delegated to {0}")]
88    NoDelegation(Address),
89    /// The delegation is still locked.
90    #[error("that delegation is locked until {until} ms")]
91    Locked {
92        /// When the lock ends, milliseconds.
93        until: u64,
94    },
95    /// The unstaking queue already holds [`MAX_PENDING_WITHDRAWALS`] withdrawals.
96    #[error("{MAX_PENDING_WITHDRAWALS} withdrawals already wait in the queue, the most there may be")]
97    QueueFull,
98    /// The amount has more than eight decimal places.
99    #[error(transparent)]
100    Units(#[from] BadUnits),
101}
102
103/// Everything outside the amounts that a plan is made from.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct Ctx {
106    /// The network the action is signed for.
107    pub network: Network,
108    /// The nonce to sign with, in milliseconds.
109    pub nonce: u64,
110    /// Now, milliseconds: a lock or a queue is measured from it.
111    pub now_ms: u64,
112}
113
114impl Ctx {
115    const fn plan<A>(&self, action: A, key: Signers, effect: Effect, free_at: Option<u64>) -> Plan<A> {
116        Plan { network: self.network, action, nonce: self.nonce, key, effect, free_at }
117    }
118
119    /// `cDeposit`: HYPE from spot into the staking balance.
120    pub fn stake(&self, hype: Dec) -> Result<Plan<CDeposit>, Refused> {
121        let action = CDeposit::new(hype, self.nonce)?;
122        let effect = Effect { balance: Balance::Undelegated, change: Change::Up(hype) };
123        Ok(self.plan(action, CDeposit::KEY, effect, None))
124    }
125
126    /// `cWithdraw`: HYPE from the staking balance toward spot, through the
127    /// network's queue, which holds at most five at once.
128    pub fn unstake(&self, hype: Dec, summary: &DelegatorSummary) -> Result<Plan<CWithdraw>, Refused> {
129        let action = CWithdraw::new(hype, self.nonce)?;
130        at_most(hype, summary.undelegated)?;
131        if summary.n_pending_withdrawals >= MAX_PENDING_WITHDRAWALS {
132            return Err(Refused::QueueFull);
133        }
134        let effect = Effect { balance: Balance::Undelegated, change: Change::Down(hype) };
135        let ready = self.now_ms.saturating_add(unstaking_ms(self.network));
136        Ok(self.plan(action, CWithdraw::KEY, effect, Some(ready)))
137    }
138
139    /// `tokenDelegate`: the staking balance to `validator`, locked for the
140    /// network's delegation lock.
141    pub fn delegate(
142        &self,
143        validator: Address,
144        hype: Dec,
145        summary: &DelegatorSummary,
146    ) -> Result<Plan<TokenDelegate>, Refused> {
147        let action = TokenDelegate::delegate(validator, hype, self.nonce)?;
148        at_most(hype, summary.undelegated)?;
149        let effect = Effect { balance: Balance::Undelegated, change: Change::Down(hype) };
150        Ok(self.plan(action, TokenDelegate::KEY, effect, Some(locked_until(self.network, self.now_ms))))
151    }
152
153    /// `tokenDelegate` back: from `validator` to the staking balance, once
154    /// its lock has passed.
155    pub fn undelegate(
156        &self,
157        validator: Address,
158        hype: Dec,
159        delegations: &[Delegation],
160    ) -> Result<Plan<TokenDelegate>, Refused> {
161        let action = TokenDelegate::undelegate(validator, hype, self.nonce)?;
162        let held = delegations
163            .iter()
164            .find(|delegation| delegation.validator == validator)
165            .ok_or(Refused::NoDelegation(validator))?;
166        if held.is_locked(self.now_ms) {
167            return Err(Refused::Locked { until: held.locked_until_timestamp });
168        }
169        at_most(hype, held.amount)?;
170        let effect = Effect { balance: Balance::Undelegated, change: Change::Up(hype) };
171        Ok(self.plan(action, TokenDelegate::KEY, effect, None))
172    }
173}
174
175fn at_most(amount: Dec, held: Dec) -> Result<(), Refused> {
176    match amount > held {
177        true => Err(Refused::MoreThan { amount, held }),
178        false => Ok(()),
179    }
180}
181
182#[cfg(test)]
183#[path = "tests/plan.rs"]
184mod tests;