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