Skip to main content

df_hyperliquid_core/account/settings/
mode.rs

1//! An account's mode: how its balances are kept, as `userAbstraction` answers, the read, and
2//! changing it with `userSetAbstraction` (the account's own wallet) or `agentSetAbstraction` (an
3//! agent, for its master). Unified back to standard is refused.
4
5use std::fmt;
6
7use serde::{Deserialize, Deserializer, de};
8
9use crate::client::{ApiError, Transport, info, user_request};
10use crate::utils::Address;
11use crate::utils::sign::{Field, L1Action, Map, NonceKey, UserAction, UserSigned};
12
13/// `{"type":"userAbstraction","user":..}`.
14#[must_use]
15pub fn abstraction_request(user: Address) -> String {
16    user_request("userAbstraction", user)
17}
18
19/// Weighs 20.
20pub async fn abstraction(transport: &impl Transport, user: Address) -> Result<Abstraction, ApiError> {
21    info(transport, abstraction_request(user)).await
22}
23
24/// How an account's balances are kept, as `userAbstraction` answers.
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26#[non_exhaustive]
27pub enum Abstraction {
28    /// What a new account answers, never set. Standard: perp and spot apart.
29    Default,
30    /// Standard, set: each perp dex and spot keep their own.
31    Disabled,
32    /// One balance per asset, in spot.
33    UnifiedAccount,
34    /// Unified, and an order may borrow against HYPE and BTC.
35    PortfolioMargin,
36    /// Discontinued: USDC sits with the main dex's perps, and every USDC dex
37    /// draws on it; everything else as standard.
38    DexAbstraction,
39    /// A mode this build does not know, kept as spelled. Treated as standard.
40    Unknown(String),
41}
42
43impl Abstraction {
44    /// From the venue's spelling: `unifiedAccount`. A mode this build does not know is kept as
45    /// [`Abstraction::Unknown`].
46    #[must_use]
47    pub fn parse(text: &str) -> Abstraction {
48        match text {
49            "default" => Abstraction::Default,
50            "disabled" => Abstraction::Disabled,
51            "unifiedAccount" => Abstraction::UnifiedAccount,
52            "portfolioMargin" => Abstraction::PortfolioMargin,
53            "dexAbstraction" => Abstraction::DexAbstraction,
54            other => Abstraction::Unknown(other.to_owned()),
55        }
56    }
57
58    /// As the venue spells it: `unifiedAccount`.
59    #[must_use]
60    pub fn wire(&self) -> &str {
61        match self {
62            Abstraction::Default => "default",
63            Abstraction::Disabled => "disabled",
64            Abstraction::UnifiedAccount => "unifiedAccount",
65            Abstraction::PortfolioMargin => "portfolioMargin",
66            Abstraction::DexAbstraction => "dexAbstraction",
67            Abstraction::Unknown(other) => other,
68        }
69    }
70
71    /// One balance, in spot: a unified or portfolio-margin account, which also
72    /// refuses `spotSend`.
73    #[must_use]
74    pub const fn is_pooled(&self) -> bool {
75        matches!(self, Abstraction::UnifiedAccount | Abstraction::PortfolioMargin)
76    }
77
78    /// Separate ledgers: each perp dex and spot keep their own.
79    #[must_use]
80    pub const fn is_standard(&self) -> bool {
81        !self.is_pooled()
82    }
83}
84
85impl fmt::Display for Abstraction {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str(self.wire())
88    }
89}
90
91/// From the bare JSON string the venue answers.
92impl<'de> Deserialize<'de> for Abstraction {
93    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
94        struct Visitor;
95
96        impl de::Visitor<'_> for Visitor {
97            type Value = Abstraction;
98
99            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100                f.write_str("an account mode as a string")
101            }
102
103            fn visit_str<E: de::Error>(self, text: &str) -> Result<Abstraction, E> {
104                Ok(Abstraction::parse(text))
105            }
106        }
107
108        deserializer.deserialize_str(Visitor)
109    }
110}
111
112/// A mode an account can be set to.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114#[non_exhaustive]
115pub enum AbstractionMode {
116    /// Standard: perp and spot apart.
117    Disabled,
118    /// One balance, in spot.
119    UnifiedAccount,
120    /// Unified, and an order may borrow against HYPE and BTC.
121    PortfolioMargin,
122}
123
124impl AbstractionMode {
125    /// Every mode, standard first.
126    pub const ALL: [AbstractionMode; 3] =
127        [AbstractionMode::Disabled, AbstractionMode::UnifiedAccount, AbstractionMode::PortfolioMargin];
128
129    /// As `userSetAbstraction` and `userAbstraction` spell it.
130    #[must_use]
131    pub const fn wire(self) -> &'static str {
132        match self {
133            AbstractionMode::Disabled => "disabled",
134            AbstractionMode::UnifiedAccount => "unifiedAccount",
135            AbstractionMode::PortfolioMargin => "portfolioMargin",
136        }
137    }
138
139    /// As `agentSetAbstraction` spells it.
140    #[must_use]
141    pub const fn code(self) -> &'static str {
142        match self {
143            AbstractionMode::Disabled => "i",
144            AbstractionMode::UnifiedAccount => "u",
145            AbstractionMode::PortfolioMargin => "p",
146        }
147    }
148
149    /// From `userSetAbstraction`'s spelling. `default`, a mode never set, is
150    /// none an account can be set to.
151    #[must_use]
152    pub fn from_wire(text: &str) -> Option<AbstractionMode> {
153        AbstractionMode::ALL.into_iter().find(|mode| mode.wire() == text)
154    }
155
156    /// From `agentSetAbstraction`'s one letter.
157    #[must_use]
158    pub fn from_code(text: &str) -> Option<AbstractionMode> {
159        AbstractionMode::ALL.into_iter().find(|mode| mode.code() == text)
160    }
161
162    /// Whether the venue refuses moving an account in `current` to this
163    /// mode: a unified account back to standard.
164    #[must_use]
165    pub const fn is_refused_from(self, current: &Abstraction) -> bool {
166        matches!((current, self), (Abstraction::UnifiedAccount, AbstractionMode::Disabled))
167    }
168}
169
170/// `userSetAbstraction`, signed by the account's own wallet. `user` is the
171/// account whose mode changes. Unified back to standard is refused.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct UserSetAbstraction {
174    user: Address,
175    mode: AbstractionMode,
176    nonce: u64,
177}
178
179impl UserSetAbstraction {
180    /// Sets `user`'s mode to `mode`, signed at `nonce`.
181    #[must_use]
182    pub const fn new(user: Address, mode: AbstractionMode, nonce: u64) -> UserSetAbstraction {
183        UserSetAbstraction { user, mode, nonce }
184    }
185}
186
187impl UserAction for UserSetAbstraction {
188    fn user_signed(&self) -> UserSigned<'_> {
189        UserSigned::new("userSetAbstraction", "HyperliquidTransaction:UserSetAbstraction", NonceKey::Nonce, self.nonce)
190            .field("user", Field::Address(self.user))
191            .field("abstraction", Field::String(self.mode.wire()))
192    }
193}
194
195/// `agentSetAbstraction`: `{type, abstraction}` with the one-letter code, an
196/// L1 action an agent signs for its master. Unified back to standard is
197/// refused.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub struct AgentSetAbstraction {
200    mode: AbstractionMode,
201}
202
203impl AgentSetAbstraction {
204    /// Sets the master's mode to `mode`.
205    #[must_use]
206    pub const fn new(mode: AbstractionMode) -> AgentSetAbstraction {
207        AgentSetAbstraction { mode }
208    }
209}
210
211impl L1Action for AgentSetAbstraction {
212    fn action(&self) -> Map {
213        Map::new().put("type", "agentSetAbstraction").put("abstraction", self.mode.code())
214    }
215}
216
217#[cfg(test)]
218#[path = "tests/mode.rs"]
219mod tests;