df_hyperliquid_core/account/settings/
subaccounts.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub struct AccountRef {
19 pub owner: Address,
21 pub sub: Option<Address>,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
27#[non_exhaustive]
28pub enum SubRefusal {
29 #[error("a subaccount places no spot orders here")]
31 Spot,
32 #[error("a subaccount places no HIP-4 orders and splits or merges nothing here")]
34 Outcome,
35 #[error("a subaccount's order names its market, since its spot and HIP-4 orders are refused")]
37 MarketUnknown,
38 #[error("a subaccount moves nothing between its own ledgers here")]
40 LedgerMove,
41 #[error("a subaccount approves nothing: its master's agent signs for it")]
43 Approval,
44 #[error("a subaccount schedules no cancel here")]
46 ScheduleCancel,
47 #[error("only the master opens subaccounts and moves money in and out of them")]
50 MastersOwn,
51 #[error("a subaccount has no key of its own to sign this")]
53 NoKey,
54}
55
56impl AccountRef {
57 #[must_use]
59 pub const fn own(owner: Address) -> AccountRef {
60 AccountRef { owner, sub: None }
61 }
62
63 #[must_use]
65 pub const fn sub(owner: Address, sub: Address) -> AccountRef {
66 AccountRef { owner, sub: Some(sub) }
67 }
68
69 #[must_use]
71 pub const fn is_sub(&self) -> bool {
72 self.sub.is_some()
73 }
74
75 #[must_use]
78 pub fn read_at(&self) -> Address {
79 self.sub.unwrap_or(self.owner)
80 }
81
82 #[must_use]
84 pub const fn vault_address(&self) -> Option<Address> {
85 self.sub
86 }
87
88 #[must_use]
90 pub const fn signs_for(&self) -> Address {
91 self.owner
92 }
93
94 #[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 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#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct CreateSubAccount {
134 name: String,
135}
136
137impl CreateSubAccount {
138 #[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#[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 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 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 #[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#[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 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#[must_use]
229pub fn sub_accounts_request(master: Address) -> String {
230 user_request("subAccounts", master)
231}
232
233pub 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
242#[serde(rename_all = "camelCase")]
243#[non_exhaustive]
244pub struct SubAccount {
245 #[serde(default)]
247 pub name: String,
248 pub sub_account_user: Address,
250 pub master: Address,
252 #[serde(default)]
254 pub clearinghouse_state: Option<ClearinghouseState>,
255 #[serde(default)]
257 pub spot_state: Option<SpotState>,
258}
259
260impl SubAccount {
261 #[must_use]
263 pub const fn account(&self) -> AccountRef {
264 AccountRef::sub(self.master, self.sub_account_user)
265 }
266
267 #[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 #[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 #[must_use]
281 pub fn withdrawable(&self) -> Dec {
282 self.clearinghouse_state.as_ref().map_or(Dec::ZERO, |state| state.withdrawable)
283 }
284
285 #[must_use]
287 pub fn positions(&self) -> usize {
288 self.clearinghouse_state.as_ref().map_or(0, |state| state.positions().count())
289 }
290
291 #[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;