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