Skip to main content

df_hyperliquid_core/earn/lending/
plan.rs

1//! From a lending move's typed values to exactly what is signed: the action,
2//! its nonce, the key it needs, and the position that should change once it
3//! lands. A token is its spot index from the caller's `spotMeta`.
4
5use crate::account::Signers;
6use crate::client::Network;
7use crate::earn::lending::action::{BadLend, BorrowLend};
8use crate::earn::lending::state::{ReserveState, UserState, reserve};
9use crate::utils::Dec;
10
11/// A figure a read back checks: a position's `value` in
12/// `borrowLendUserState`, by token.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum Balance {
16    /// What is supplied of the token.
17    Supplied(u32),
18    /// What is borrowed of the token.
19    Borrowed(u32),
20}
21
22/// How the position moves once the action lands. Interest moves it too, so a
23/// read back shows the direction, by about the amount.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum Change {
27    /// Rises by about this amount, in the token.
28    Rises(Dec),
29    /// Falls by about this amount, in the token.
30    Falls(Dec),
31    /// To nothing: all of it withdrawn or repaid.
32    Empties,
33}
34
35/// The position an action changes, and what reading it back should show.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct Effect {
39    /// The position that changes.
40    pub balance: Balance,
41    /// How it changes.
42    pub change: Change,
43}
44
45impl Effect {
46    /// Whether `after`, read back, shows the action landed against `before`.
47    #[must_use]
48    pub fn landed(&self, before: Dec, after: Dec) -> bool {
49        match self.change {
50            Change::Rises(_) => after > before,
51            Change::Falls(_) => after < before,
52            Change::Empties => after.is_zero(),
53        }
54    }
55}
56
57/// Exactly what is signed, and what to check once it lands.
58#[derive(Debug, Clone, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct Plan<A> {
61    /// The network the action is signed for.
62    pub network: Network,
63    /// The action signed.
64    pub action: A,
65    /// The nonce it is signed with, in milliseconds.
66    pub nonce: u64,
67    /// Which keys may sign it.
68    pub key: Signers,
69    /// The position that should change, to check once it lands.
70    pub effect: Effect,
71}
72
73/// Why a move is not signed.
74#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
75#[non_exhaustive]
76pub enum Refused {
77    /// The token has no lending reserve; holds the token index.
78    #[error("token {0} has no lending reserve")]
79    NoReserve(u32),
80    /// An amount over what the reserve can lend, or over what is supplied or owed.
81    #[error("{amount} is more than the {held} there is")]
82    MoreThan {
83        /// The amount asked for, in the token.
84        amount: Dec,
85        /// What there is, in the token.
86        held: Dec,
87    },
88    /// Nothing of the token is supplied or owed to take back; holds the token index.
89    #[error("nothing of token {0} is there to take back")]
90    Nothing(u32),
91    /// The action itself was refused.
92    #[error(transparent)]
93    Lend(#[from] BadLend),
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}
104
105impl Ctx {
106    const fn plan(&self, action: BorrowLend, effect: Effect) -> Plan<BorrowLend> {
107        Plan { network: self.network, action, nonce: self.nonce, key: BorrowLend::KEY, effect }
108    }
109
110    /// Supplies `amount` of `token`, already cut to its `weiDecimals`.
111    pub fn supply(
112        &self,
113        token: u32,
114        amount: Dec,
115        reserves: &[(u32, ReserveState)],
116    ) -> Result<Plan<BorrowLend>, Refused> {
117        let action = BorrowLend::supply(token, amount)?;
118        reserve(reserves, token).ok_or(Refused::NoReserve(token))?;
119        Ok(self.plan(action, Effect { balance: Balance::Supplied(token), change: Change::Rises(amount) }))
120    }
121
122    /// Takes back `amount` of what is supplied, or with `None` all of it.
123    pub fn withdraw(&self, token: u32, amount: Option<Dec>, state: &UserState) -> Result<Plan<BorrowLend>, Refused> {
124        let held = state.supplied(token);
125        let (action, change) = back(token, amount, held, BorrowLend::withdraw, BorrowLend::withdraw_all)?;
126        Ok(self.plan(action, Effect { balance: Balance::Supplied(token), change }))
127    }
128
129    /// Borrows `amount` of `token`, at most what its reserve can lend.
130    pub fn borrow(
131        &self,
132        token: u32,
133        amount: Dec,
134        reserves: &[(u32, ReserveState)],
135    ) -> Result<Plan<BorrowLend>, Refused> {
136        let action = BorrowLend::borrow(token, amount)?;
137        let lendable = reserve(reserves, token).ok_or(Refused::NoReserve(token))?.lendable();
138        if amount > lendable {
139            return Err(Refused::MoreThan { amount, held: lendable });
140        }
141        Ok(self.plan(action, Effect { balance: Balance::Borrowed(token), change: Change::Rises(amount) }))
142    }
143
144    /// Repays `amount` of what is owed, or with `None` all of it, interest in.
145    pub fn repay(&self, token: u32, amount: Option<Dec>, state: &UserState) -> Result<Plan<BorrowLend>, Refused> {
146        let held = state.borrowed(token);
147        let (action, change) = back(token, amount, held, BorrowLend::repay, BorrowLend::repay_all)?;
148        Ok(self.plan(action, Effect { balance: Balance::Borrowed(token), change }))
149    }
150}
151
152/// A withdraw or repay of `amount` against `held`, or of all of it.
153fn back(
154    token: u32,
155    amount: Option<Dec>,
156    held: Dec,
157    some: fn(u32, Dec) -> Result<BorrowLend, BadLend>,
158    all: fn(u32) -> BorrowLend,
159) -> Result<(BorrowLend, Change), Refused> {
160    if !held.is_positive() {
161        return Err(Refused::Nothing(token));
162    }
163    match amount {
164        None => Ok((all(token), Change::Empties)),
165        Some(amount) => {
166            let action = some(token, amount)?;
167            match amount > held {
168                true => Err(Refused::MoreThan { amount, held }),
169                false => Ok((action, Change::Falls(amount))),
170            }
171        }
172    }
173}
174
175#[cfg(test)]
176#[path = "tests/plan.rs"]
177mod tests;