Skip to main content

df_hyperliquid_core/account/settings/
subaccounts.rs

1//! Subaccounts: `createSubAccount`, `subAccountTransfer` (perp USDC), `subAccountSpotTransfer` (any
2//! spot token) and the `subAccounts` read. A subaccount is a user of its own with no key: it is read
3//! at its own address, and the master's agent trades its perps with it as `vaultAddress`.
4
5use std::fmt;
6
7use crate::account::holdings::perps::ClearinghouseState;
8use crate::account::holdings::spot::SpotState;
9use crate::account::keys::signers::ActionKind;
10use crate::client::{ApiError, Transport, info, user_request};
11use crate::utils::sign::{L1Action, Map};
12use crate::utils::{Address, AssetKind, BadUnits, Dec, USDC_DECIMALS, exact_units};
13use serde::Deserialize;
14
15/// Whose account an action or a read is about: the master's own, or one of
16/// its subaccounts.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub struct AccountRef {
19    /// The account whose key, or whose agent, signs.
20    pub owner: Address,
21    /// The subaccount acted for, if any.
22    pub sub: Option<Address>,
23}
24
25/// What a subaccount does not do, and why.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
27#[non_exhaustive]
28pub enum SubRefusal {
29    /// A spot order.
30    #[error("a subaccount places no spot orders here")]
31    Spot,
32    /// A HIP-4 order, split or merge.
33    #[error("a subaccount places no HIP-4 orders and splits or merges nothing here")]
34    Outcome,
35    /// An order-like action that names no market cannot be told apart.
36    #[error("a subaccount's order names its market, since its spot and HIP-4 orders are refused")]
37    MarketUnknown,
38    /// A move between the subaccount's own balances: `usdClassTransfer` or `agentSendAsset`.
39    #[error("a subaccount moves nothing between its own ledgers here")]
40    LedgerMove,
41    /// An approval: `approveAgent` or `approveBuilderFee`.
42    #[error("a subaccount approves nothing: its master's agent signs for it")]
43    Approval,
44    /// Setting the dead man's switch (`scheduleCancel`).
45    #[error("a subaccount schedules no cancel here")]
46    ScheduleCancel,
47    /// Opening a subaccount, and moving money in and out of one, is the
48    /// master's own business.
49    #[error("only the master opens subaccounts and moves money in and out of them")]
50    MastersOwn,
51    /// User-signed: it would need the subaccount's own key, which there is not.
52    #[error("a subaccount has no key of its own to sign this")]
53    NoKey,
54}
55
56impl AccountRef {
57    /// The master's own account.
58    #[must_use]
59    pub const fn own(owner: Address) -> AccountRef {
60        AccountRef { owner, sub: None }
61    }
62
63    /// One of `owner`'s subaccounts.
64    #[must_use]
65    pub const fn sub(owner: Address, sub: Address) -> AccountRef {
66        AccountRef { owner, sub: Some(sub) }
67    }
68
69    /// Whether it acts for a subaccount.
70    #[must_use]
71    pub const fn is_sub(&self) -> bool {
72        self.sub.is_some()
73    }
74
75    /// Where its states, mode, fees and limits are read: the subaccount's
76    /// own address for one.
77    #[must_use]
78    pub fn read_at(&self) -> Address {
79        self.sub.unwrap_or(self.owner)
80    }
81
82    /// The `vaultAddress` an L1 action names: the subaccount it acts for.
83    #[must_use]
84    pub const fn vault_address(&self) -> Option<Address> {
85        self.sub
86    }
87
88    /// The account whose key, or whose agent, signs.
89    #[must_use]
90    pub const fn signs_for(&self) -> Address {
91        self.owner
92    }
93
94    /// Why this account does not do `kind`, or `None` when it may. An
95    /// order-like action (`order`, `modify`, `batchModify`, `twapOrder`) names
96    /// its `market`. The master's own account refuses nothing here.
97    #[must_use]
98    pub fn refuses(&self, kind: ActionKind, market: Option<AssetKind>) -> Option<SubRefusal> {
99        self.sub?;
100        match kind {
101            ActionKind::Order | ActionKind::Modify | ActionKind::BatchModify | ActionKind::TwapOrder => match market {
102                Some(AssetKind::Perp | AssetKind::Hip3Perp) => None,
103                Some(AssetKind::Spot) => Some(SubRefusal::Spot),
104                Some(AssetKind::Outcome) => Some(SubRefusal::Outcome),
105                None => Some(SubRefusal::MarketUnknown),
106            },
107            ActionKind::UserOutcome => Some(SubRefusal::Outcome),
108            ActionKind::UsdClassTransfer | ActionKind::AgentSendAsset => Some(SubRefusal::LedgerMove),
109            ActionKind::ApproveAgent | ActionKind::ApproveBuilderFee => Some(SubRefusal::Approval),
110            ActionKind::ScheduleCancel => Some(SubRefusal::ScheduleCancel),
111            ActionKind::CreateSubAccount | ActionKind::SubAccountTransfer | ActionKind::SubAccountSpotTransfer => {
112                Some(SubRefusal::MastersOwn)
113            }
114            // The docs: `userSetAbstraction`'s user "can be a sub-account of the user".
115            ActionKind::UserSetAbstraction => None,
116            user_signed if user_signed.is_user_signed() => Some(SubRefusal::NoKey),
117            _ => None,
118        }
119    }
120}
121
122impl fmt::Display for AccountRef {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        match self.sub {
125            Some(sub) => write!(f, "{sub} (a subaccount of {})", self.owner),
126            None => write!(f, "{}", self.owner),
127        }
128    }
129}
130
131/// `createSubAccount`: `{type, name}`.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct CreateSubAccount {
134    name: String,
135}
136
137impl CreateSubAccount {
138    /// A subaccount named `name`.
139    #[must_use]
140    pub fn new(name: &str) -> CreateSubAccount {
141        CreateSubAccount { name: name.to_owned() }
142    }
143}
144
145impl L1Action for CreateSubAccount {
146    fn action(&self) -> Map {
147        Map::new().put("type", "createSubAccount").put("name", self.name.clone())
148    }
149}
150
151/// `subAccountTransfer`: perp USDC between the master and a subaccount,
152/// `usd` in millionths.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub struct SubAccountTransfer {
155    sub_account: Address,
156    is_deposit: bool,
157    usd: u64,
158}
159
160impl SubAccountTransfer {
161    /// Into the subaccount, at most six places: refused rather than rounded
162    /// when finer.
163    pub fn deposit(sub_account: Address, usdc: Dec) -> Result<SubAccountTransfer, BadUnits> {
164        Ok(SubAccountTransfer { sub_account, is_deposit: true, usd: exact_units(usdc, USDC_DECIMALS)? })
165    }
166
167    /// Back to the master.
168    pub fn withdraw(sub_account: Address, usdc: Dec) -> Result<SubAccountTransfer, BadUnits> {
169        Ok(SubAccountTransfer { sub_account, is_deposit: false, usd: exact_units(usdc, USDC_DECIMALS)? })
170    }
171
172    /// From a count of millionths already made.
173    #[must_use]
174    pub const fn from_micros(sub_account: Address, is_deposit: bool, usd: u64) -> SubAccountTransfer {
175        SubAccountTransfer { sub_account, is_deposit, usd }
176    }
177}
178
179impl L1Action for SubAccountTransfer {
180    fn action(&self) -> Map {
181        Map::new()
182            .put("type", "subAccountTransfer")
183            .put("subAccountUser", self.sub_account.to_hex())
184            .put("isDeposit", self.is_deposit)
185            .put("usd", self.usd)
186    }
187}
188
189/// `subAccountSpotTransfer`: a spot token between the master and a
190/// subaccount. `token` is `NAME:0x<tokenId>`; the amount goes as a decimal
191/// with no trailing zeros.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct SubAccountSpotTransfer {
194    sub_account: Address,
195    is_deposit: bool,
196    token: String,
197    amount: Dec,
198}
199
200impl SubAccountSpotTransfer {
201    /// `amount` of `token` (`NAME:0x<tokenId>`) into the subaccount when `is_deposit`, else back to
202    /// the master; refused unless positive.
203    pub fn new(
204        sub_account: Address,
205        is_deposit: bool,
206        token: &str,
207        amount: Dec,
208    ) -> Result<SubAccountSpotTransfer, BadUnits> {
209        if !amount.is_positive() {
210            return Err(BadUnits::NotPositive(amount));
211        }
212        Ok(SubAccountSpotTransfer { sub_account, is_deposit, token: token.to_owned(), amount })
213    }
214}
215
216impl L1Action for SubAccountSpotTransfer {
217    fn action(&self) -> Map {
218        Map::new()
219            .put("type", "subAccountSpotTransfer")
220            .put("subAccountUser", self.sub_account.to_hex())
221            .put("isDeposit", self.is_deposit)
222            .put("token", self.token.clone())
223            .put("amount", self.amount.to_wire())
224    }
225}
226
227/// `{"type":"subAccounts","user":<master>}`.
228#[must_use]
229pub fn sub_accounts_request(master: Address) -> String {
230    user_request("subAccounts", master)
231}
232
233/// A master's subaccounts. The venue answers `null`, not `[]`, for none.
234pub async fn sub_accounts(transport: &impl Transport, master: Address) -> Result<Vec<SubAccount>, ApiError> {
235    let subs: Option<Vec<SubAccount>> = info(transport, sub_accounts_request(master)).await?;
236    Ok(subs.unwrap_or_default())
237}
238
239/// One subaccount with its states. A subaccount is a user in its own right,
240/// so its figures are never added to its master's.
241#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
242#[serde(rename_all = "camelCase")]
243#[non_exhaustive]
244pub struct SubAccount {
245    /// The subaccount's name; empty when the venue leaves it out.
246    #[serde(default)]
247    pub name: String,
248    /// The subaccount's address (`subAccountUser`).
249    pub sub_account_user: Address,
250    /// The master's address.
251    pub master: Address,
252    /// Its main dex's clearinghouse state (`clearinghouseState`); `None` when not sent.
253    #[serde(default)]
254    pub clearinghouse_state: Option<ClearinghouseState>,
255    /// Its spot balances (`spotState`); `None` when not sent.
256    #[serde(default)]
257    pub spot_state: Option<SpotState>,
258}
259
260impl SubAccount {
261    /// Acting for it, as its master.
262    #[must_use]
263    pub const fn account(&self) -> AccountRef {
264        AccountRef::sub(self.master, self.sub_account_user)
265    }
266
267    /// Its main dex's account value; nothing when it has no state.
268    #[must_use]
269    pub fn equity(&self) -> Dec {
270        self.clearinghouse_state.as_ref().map_or(Dec::ZERO, |state| state.margin_summary.account_value)
271    }
272
273    /// Its main dex's positions' notional (`totalNtlPos`); nothing when it has no state.
274    #[must_use]
275    pub fn notional(&self) -> Dec {
276        self.clearinghouse_state.as_ref().map_or(Dec::ZERO, |state| state.margin_summary.total_ntl_pos)
277    }
278
279    /// What can leave its main dex's balance now (`withdrawable`); nothing when it has no state.
280    #[must_use]
281    pub fn withdrawable(&self) -> Dec {
282        self.clearinghouse_state.as_ref().map_or(Dec::ZERO, |state| state.withdrawable)
283    }
284
285    /// Positions held on its main dex, a flat leg left out.
286    #[must_use]
287    pub fn positions(&self) -> usize {
288        self.clearinghouse_state.as_ref().map_or(0, |state| state.positions().count())
289    }
290
291    /// Spot USDC's total.
292    #[must_use]
293    pub fn spot_usdc(&self) -> Dec {
294        self.spot_state.as_ref().and_then(SpotState::usdc).map_or(Dec::ZERO, |usdc| usdc.total)
295    }
296}
297
298#[cfg(test)]
299#[path = "tests/subaccounts.rs"]
300mod tests;