Skip to main content

df_hyperliquid_core/transfer/send/
plan.rs

1//! From a move's typed values to exactly what is signed: the action, its nonce, who may sign it,
2//! and the balance that should change once it lands. An agent's signature on a user-signed action
3//! recovers to the agent, which holds nothing, so [`Signers::Main`] refuses it before signing.
4
5use crate::account::{ActionKind, Keeping, Signers};
6use crate::client::{Network, USDC_INDEX};
7use crate::transfer::evm::is_system_address;
8use crate::transfer::send::actions::{
9    AgentSendAsset, PERP_DEX, SPOT_DEX, SendAsset, SpotOut, UsdClassTransfer, UsdSend, Withdraw3,
10};
11use crate::transfer::send::amount::Amount;
12use crate::transfer::send::token::SpotToken;
13use crate::utils::{Address, Dec, USDC_DECIMALS};
14
15/// The transfer actions.
16const KINDS: [ActionKind; 6] = [
17    ActionKind::UsdClassTransfer,
18    ActionKind::UsdSend,
19    ActionKind::SpotSend,
20    ActionKind::SendAsset,
21    ActionKind::Withdraw3,
22    ActionKind::AgentSendAsset,
23];
24
25/// Who may sign a transfer action, by its wire `type`.
26#[must_use]
27pub fn key(kind: &str) -> Option<Signers> {
28    ActionKind::from_wire(kind).filter(|kind| KINDS.contains(kind)).map(ActionKind::signers)
29}
30
31/// A figure a read back checks.
32#[derive(Debug, Clone, PartialEq, Eq, Hash)]
33pub enum Balance {
34    /// What a perp dex lets move out, `clearinghouseState`'s `withdrawable`;
35    /// `""` is the main dex.
36    Perp(String),
37    /// A spot token's `total` in `spotClearinghouseState`, by index. A pooled
38    /// account's USDC is `Spot(0)`.
39    Spot(u32),
40}
41
42/// How the figure moves once the action lands.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Change {
45    /// Up by exactly this much.
46    Up(Dec),
47    /// Down by exactly this much: a withdrawal's fee comes out of the amount.
48    Down(Dec),
49    /// Down by this much and whatever the venue takes on top: a fresh
50    /// recipient's activation fee, or HYPE for a spot send.
51    DownAtLeast(Dec),
52}
53
54/// The balance an action changes, and what reading it back should show.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Effect {
57    /// The figure to read back.
58    pub balance: Balance,
59    /// How it should move.
60    pub change: Change,
61}
62
63impl Effect {
64    /// Whether `after`, read back, shows the action landed against `before`,
65    /// read when it was planned.
66    #[must_use]
67    pub fn landed(&self, before: Dec, after: Dec) -> bool {
68        match self.change {
69            Change::Up(amount) => before.checked_add(amount) == Some(after),
70            Change::Down(amount) => before.checked_sub(amount) == Some(after),
71            Change::DownAtLeast(amount) => before.checked_sub(amount).is_some_and(|most| after <= most),
72        }
73    }
74}
75
76/// Exactly what is signed, and what to check once it lands.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Plan<A> {
79    /// The network the action is signed for.
80    pub network: Network,
81    /// The action to sign.
82    pub action: A,
83    /// What it is signed with; a user-signed action carries it too.
84    pub nonce: u64,
85    /// Who may sign it.
86    pub key: Signers,
87    /// The balance that should change, and by how much.
88    pub effect: Effect,
89}
90
91/// Why a move is not signed.
92#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
93pub enum Refused {
94    /// A pooled account has one balance, so there is nothing to move between the two named.
95    #[error("a pooled account holds USDC in one balance, so there is nothing to move between {0}")]
96    OneBalance(&'static str),
97    /// The source and destination balances are the same.
98    #[error("the two balances are the same one")]
99    SameDex,
100    /// The recipient is the account itself.
101    #[error("that is this account; a send goes somewhere else")]
102    ToSelf,
103    /// The recipient is a system address; a send there crosses to HyperEVM and goes through
104    /// [`Ctx::to_evm`].
105    #[error("{0} is a system address: a send there crosses to HyperEVM, which `to_evm` plans")]
106    SystemAddress(Address),
107    /// The token, by name, has no ERC-20 on HyperEVM.
108    #[error("{0} has no token on HyperEVM to cross to")]
109    NotLinked(String),
110    /// No vector covers USDC crossing to HyperEVM, so it is refused.
111    #[error("USDC does not cross to HyperEVM here")]
112    Usdc,
113    /// The amount has more places than the balance it moves counts.
114    #[error("{amount} has more than {places} decimal places")]
115    TooFine {
116        /// The amount asked for.
117        amount: Dec,
118        /// The most places allowed.
119        places: u32,
120    },
121}
122
123/// Everything outside the amounts that a plan is made from.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct Ctx {
126    /// The network the action is signed for.
127    pub network: Network,
128    /// The account that moves the money.
129    pub account: Address,
130    /// How the account keeps its balances, from its mode.
131    pub keeping: Keeping,
132    /// The nonce the action is signed with.
133    pub nonce: u64,
134}
135
136impl Ctx {
137    /// Where USDC leaving the perp side is read back: spot USDC for a pooled
138    /// account, the main dex's `withdrawable` otherwise.
139    #[must_use]
140    pub fn usdc(&self) -> Balance {
141        match self.keeping.pools() {
142            true => Balance::Spot(USDC_INDEX),
143            false => Balance::Perp(PERP_DEX.to_owned()),
144        }
145    }
146
147    const fn plan<A>(&self, action: A, key: Signers, effect: Effect) -> Plan<A> {
148        Plan { network: self.network, action, nonce: self.nonce, key, effect }
149    }
150
151    /// `usdClassTransfer`: USDC between the account's own perp and spot. A
152    /// pooled account has one balance and nothing to move.
153    pub fn class_transfer(&self, amount: Amount, to_perp: bool) -> Result<Plan<UsdClassTransfer>, Refused> {
154        if self.keeping.pools() {
155            return Err(Refused::OneBalance("perps and spot"));
156        }
157        let value = places(&amount, USDC_DECIMALS)?;
158        let change = match to_perp {
159            true => Change::Up(value),
160            false => Change::Down(value),
161        };
162        let effect = Effect { balance: Balance::Perp(PERP_DEX.to_owned()), change };
163        Ok(self.plan(UsdClassTransfer::new(amount, to_perp, self.nonce), UsdClassTransfer::KEY, effect))
164    }
165
166    /// `usdSend`: USDC to another account.
167    pub fn usd_send(&self, to: Address, amount: Amount) -> Result<Plan<UsdSend>, Refused> {
168        self.recipient(to)?;
169        let value = places(&amount, USDC_DECIMALS)?;
170        let effect = Effect { balance: self.usdc(), change: Change::DownAtLeast(value) };
171        Ok(self.plan(UsdSend::new(to, amount, self.nonce), UsdSend::KEY, effect))
172    }
173
174    /// A spot token to another account, by the action the account takes.
175    pub fn send_token(&self, to: Address, token: &SpotToken, amount: Amount) -> Result<Plan<SpotOut>, Refused> {
176        self.recipient(to)?;
177        let value = places(&amount, token.wei_decimals)?;
178        let effect = Effect { balance: Balance::Spot(token.index), change: Change::DownAtLeast(value) };
179        let action = SpotOut::new(to, &token.wire(), amount, self.keeping, self.nonce);
180        Ok(self.plan(action, SpotOut::KEY, effect))
181    }
182
183    /// Core to HyperEVM: the token to its system address, arriving at the same address on HyperEVM.
184    /// The way back is [`crate::transfer::evm::Linked::to_core`].
185    pub fn to_evm(&self, token: &SpotToken, amount: Amount) -> Result<Plan<SpotOut>, Refused> {
186        if token.index == USDC_INDEX {
187            return Err(Refused::Usdc);
188        }
189        let most = token.crossing_places(self.network).ok_or_else(|| Refused::NotLinked(token.name.clone()))?;
190        let value = places(&amount, most)?;
191        let effect = Effect { balance: Balance::Spot(token.index), change: Change::DownAtLeast(value) };
192        let action = SpotOut::new(token.system_address(self.network), &token.wire(), amount, self.keeping, self.nonce);
193        Ok(self.plan(action, SpotOut::KEY, effect))
194    }
195
196    /// `sendAsset` to the account itself, from one of its balances to another
197    /// (`""` the main dex, `spot`, or a HIP-3 dex by name), signed by its own
198    /// key. A pooled account has one balance and nothing to move.
199    pub fn between(&self, from: &str, to: &str, token: &SpotToken, amount: Amount) -> Result<Plan<SendAsset>, Refused> {
200        let effect = self.between_effect(from, to, token, &amount)?;
201        let action = SendAsset::new(self.account, from, to, &token.wire(), amount, self.nonce);
202        Ok(self.plan(action, SendAsset::KEY, effect))
203    }
204
205    /// [`Ctx::between`] as `agentSendAsset`, which an agent signs.
206    pub fn agent_between(
207        &self,
208        from: &str,
209        to: &str,
210        token: &SpotToken,
211        amount: Amount,
212    ) -> Result<Plan<AgentSendAsset>, Refused> {
213        let effect = self.between_effect(from, to, token, &amount)?;
214        let action = AgentSendAsset::new(self.account, from, to, &token.wire(), amount, self.nonce);
215        Ok(self.plan(action, AgentSendAsset::KEY, effect))
216    }
217
218    /// `withdraw3`: USDC out to `to` on Arbitrum. The venue's fee comes out of
219    /// the amount, so the balance falls by exactly it.
220    pub fn withdraw(&self, to: Address, amount: Amount) -> Result<Plan<Withdraw3>, Refused> {
221        if is_system_address(to) {
222            return Err(Refused::SystemAddress(to));
223        }
224        let value = places(&amount, USDC_DECIMALS)?;
225        let effect = Effect { balance: self.usdc(), change: Change::Down(value) };
226        Ok(self.plan(Withdraw3::new(to, amount, self.nonce), Withdraw3::KEY, effect))
227    }
228
229    fn recipient(&self, to: Address) -> Result<(), Refused> {
230        match (to == self.account, is_system_address(to)) {
231            (true, _) => Err(Refused::ToSelf),
232            (false, true) => Err(Refused::SystemAddress(to)),
233            (false, false) => Ok(()),
234        }
235    }
236
237    /// The balance a move between two of the account's own leaves, by exactly
238    /// the amount. One side is always a perp dex, which counts in millionths.
239    fn between_effect(&self, from: &str, to: &str, token: &SpotToken, amount: &Amount) -> Result<Effect, Refused> {
240        if self.keeping.pools() {
241            return Err(Refused::OneBalance("dexes"));
242        }
243        if from == to {
244            return Err(Refused::SameDex);
245        }
246        let value = places(amount, token.wei_decimals.min(USDC_DECIMALS))?;
247        let balance = match from {
248            SPOT_DEX => Balance::Spot(token.index),
249            dex => Balance::Perp(dex.to_owned()),
250        };
251        Ok(Effect { balance, change: Change::Down(value) })
252    }
253}
254
255/// The amount's value, refused when it has more than `most` places.
256fn places(amount: &Amount, most: u32) -> Result<Dec, Refused> {
257    let value = amount.value();
258    match value.places() > most {
259        true => Err(Refused::TooFine { amount: value, places: most }),
260        false => Ok(value),
261    }
262}
263
264#[cfg(test)]
265#[path = "tests/plan.rs"]
266mod tests;