Skip to main content

df_hyperliquid_core/deploy/spot/
mod.rs

1//! Deploying a HIP-1 spot token and its HIP-2 hyperliquidity: every `spotDeploy` variant, all L1
2//! actions, and `finalizeEvmContract`, which completes a token's link to a HyperEVM contract. The
3//! reads that go with them are in [`tokens`](crate::deploy::tokens).
4
5pub mod evm;
6pub mod share;
7
8pub use evm::{EvmFinalizer, FinalizeEvmContract};
9pub use share::FeeShare;
10
11use crate::deploy::annotation::Annotation;
12use crate::deploy::error::BadDeploy;
13use crate::deploy::name::DexName;
14use crate::deploy::tokens::TokenSpec;
15use crate::utils::sign::{L1Action, Map, Value};
16use crate::utils::{Address, Dec};
17
18/// `{"type":"spotDeploy",<variant>:{..}}`. A token is deployed in five steps
19/// sent in this order: [`RegisterToken2`](SpotDeploy::RegisterToken2),
20/// [`UserGenesis`](SpotDeploy::UserGenesis) (as many times as needed),
21/// [`Genesis`](SpotDeploy::Genesis), [`RegisterSpot`](SpotDeploy::RegisterSpot)
22/// and [`RegisterHyperliquidity`](SpotDeploy::RegisterHyperliquidity). The
23/// rest are optional. Wei amounts are integers in the token's wei decimals.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum SpotDeploy {
26    /// `registerToken2`: claims a token index, paying the token auction up
27    /// to `max_gas`. `fullName` is left out when `None`.
28    RegisterToken2 {
29        /// The name, size decimals and wei decimals to register.
30        spec: TokenSpec,
31        /// The most to pay for the token auction (`maxGas`), in native token wei.
32        max_gas: u64,
33        /// The full name (`fullName`); `None` leaves it out.
34        full_name: Option<String>,
35    },
36    /// `userGenesis`: wei for addresses, wei shared among the holders of
37    /// existing tokens, and addresses to blacklist (`true`) or take off the
38    /// blacklist (`false`). `blacklistUsers` is left out when empty.
39    UserGenesis {
40        /// The token index.
41        token: u32,
42        /// Wei given to each address (`userAndWei`).
43        user_and_wei: Vec<(Address, u128)>,
44        /// Wei shared among the holders of each existing token, by token index (`existingTokenAndWei`).
45        existing_token_and_wei: Vec<(u32, u128)>,
46        /// Addresses to blacklist (`true`) or take off the blacklist (`false`) (`blacklistUsers`).
47        blacklist_users: Vec<(Address, bool)>,
48    },
49    /// `genesis`: the maximum supply in wei, which must equal what the
50    /// user genesis steps gave out. `noHyperliquidity` is sent, as `true`,
51    /// only when set.
52    Genesis {
53        /// The token index.
54        token: u32,
55        /// The maximum supply in wei (`maxSupply`), sent as a string.
56        max_supply: u128,
57        /// `true` deploys without hyperliquidity (`noHyperliquidity`).
58        no_hyperliquidity: bool,
59    },
60    /// `registerSpot`: the pair of a base and a quote token. Between two
61    /// existing tokens it pays the spot pair auction.
62    RegisterSpot {
63        /// The base token index, sent first in `tokens`.
64        base: u32,
65        /// The quote token index, sent second in `tokens`.
66        quote: u32,
67    },
68    /// `registerHyperliquidity`: the pair index (not the token's), the
69    /// starting price, each order's size in tokens (not wei), the number of
70    /// orders (0 after a genesis with no hyperliquidity) and the number of
71    /// levels seeded with USDC. `nSeededLevels` is left out when `None`.
72    RegisterHyperliquidity {
73        /// The spot pair index.
74        spot: u32,
75        /// The starting price (`startPx`).
76        start_px: Dec,
77        /// Each order's size in tokens, not wei (`orderSz`).
78        order_sz: Dec,
79        /// The number of orders (`nOrders`).
80        n_orders: u32,
81        /// The number of levels seeded with USDC (`nSeededLevels`); `None` leaves it out.
82        n_seeded_levels: Option<u32>,
83    },
84    /// `setDeployerTradingFeeShare`, at any time after `registerToken2`, and
85    /// again only to lower it.
86    SetDeployerTradingFeeShare {
87        /// The token index.
88        token: u32,
89        /// The share the deployer keeps.
90        share: FeeShare,
91    },
92    /// `enableQuoteToken`: lets the token quote spot pairs.
93    EnableQuoteToken(u32),
94    /// `enableAlignedQuoteToken`: makes the token an aligned quote asset.
95    EnableAlignedQuoteToken(u32),
96    /// `disableQuoteToken`.
97    DisableQuoteToken(u32),
98    /// `disableAlignedQuoteToken`, sent after `disableQuoteToken`.
99    DisableAlignedQuoteToken(u32),
100    /// `setTokenAnnotation`, at any time after `registerToken2`, at most
101    /// once a day.
102    SetTokenAnnotation {
103        /// The token index.
104        token: u32,
105        /// The annotation.
106        annotation: Annotation,
107    },
108    /// `setDeployerLabel`: the label shown for the deployer's tokens, set
109    /// once per deployer.
110    SetDeployerLabel(DexName),
111    /// `enableFreezePrivilege`: lets the deployer freeze holders of the
112    /// token. In Hyperliquid's Python SDK; not in the API docs.
113    EnableFreezePrivilege(u32),
114    /// `freezeUser`: freezes (`true`) or unfreezes (`false`) one holder. In
115    /// Hyperliquid's Python SDK; not in the API docs.
116    FreezeUser {
117        /// The token index.
118        token: u32,
119        /// The holder to freeze or unfreeze.
120        user: Address,
121        /// `true` freezes, `false` unfreezes.
122        freeze: bool,
123    },
124    /// `revokeFreezePrivilege`: gives the freeze privilege up. In
125    /// Hyperliquid's Python SDK; not in the API docs.
126    RevokeFreezePrivilege(u32),
127    /// `requestEvmContract`: asks to link the token to an ERC-20 on the
128    /// HyperEVM; the contract's deployer then sends
129    /// [`FinalizeEvmContract`]. `evm_extra_wei_decimals` is the EVM
130    /// contract's decimals less the token's wei decimals, from -2 to 18.
131    /// Linking cannot be undone.
132    RequestEvmContract {
133        /// The token index.
134        token: u32,
135        /// The ERC-20 contract's address on the HyperEVM.
136        address: Address,
137        /// The EVM contract's decimals less the token's wei decimals (`evmExtraWeiDecimals`), from -2 to 18.
138        evm_extra_wei_decimals: i8,
139    },
140}
141
142/// `[key, value]`, the tuple form the venue's lists take.
143fn pair(key: impl Into<Value>, value: impl Into<Value>) -> Value {
144    Value::Array(vec![key.into(), value.into()])
145}
146
147impl SpotDeploy {
148    /// `registerHyperliquidity`, refusing a negative price or size.
149    pub fn register_hyperliquidity(
150        spot: u32,
151        start_px: Dec,
152        order_sz: Dec,
153        n_orders: u32,
154        n_seeded_levels: Option<u32>,
155    ) -> Result<Self, BadDeploy> {
156        for (what, value) in [("startPx", start_px), ("orderSz", order_sz)] {
157            if value.is_negative() {
158                return Err(BadDeploy::OutOfRange { what, least: "0", most: "any", value: value.to_wire() });
159            }
160        }
161        Ok(SpotDeploy::RegisterHyperliquidity { spot, start_px, order_sz, n_orders, n_seeded_levels })
162    }
163
164    /// `requestEvmContract`, refusing extra wei decimals outside -2 to 18.
165    pub fn request_evm_contract(token: u32, address: Address, evm_extra_wei_decimals: i8) -> Result<Self, BadDeploy> {
166        if !(-2..=18).contains(&evm_extra_wei_decimals) {
167            return Err(BadDeploy::EvmExtraWeiDecimals(evm_extra_wei_decimals));
168        }
169        Ok(SpotDeploy::RequestEvmContract { token, address, evm_extra_wei_decimals })
170    }
171
172    /// The key the variant travels under.
173    #[must_use]
174    pub const fn wire_name(&self) -> &'static str {
175        match self {
176            SpotDeploy::RegisterToken2 { .. } => "registerToken2",
177            SpotDeploy::UserGenesis { .. } => "userGenesis",
178            SpotDeploy::Genesis { .. } => "genesis",
179            SpotDeploy::RegisterSpot { .. } => "registerSpot",
180            SpotDeploy::RegisterHyperliquidity { .. } => "registerHyperliquidity",
181            SpotDeploy::SetDeployerTradingFeeShare { .. } => "setDeployerTradingFeeShare",
182            SpotDeploy::EnableQuoteToken(_) => "enableQuoteToken",
183            SpotDeploy::EnableAlignedQuoteToken(_) => "enableAlignedQuoteToken",
184            SpotDeploy::DisableQuoteToken(_) => "disableQuoteToken",
185            SpotDeploy::DisableAlignedQuoteToken(_) => "disableAlignedQuoteToken",
186            SpotDeploy::SetTokenAnnotation { .. } => "setTokenAnnotation",
187            SpotDeploy::SetDeployerLabel(_) => "setDeployerLabel",
188            SpotDeploy::EnableFreezePrivilege(_) => "enableFreezePrivilege",
189            SpotDeploy::FreezeUser { .. } => "freezeUser",
190            SpotDeploy::RevokeFreezePrivilege(_) => "revokeFreezePrivilege",
191            SpotDeploy::RequestEvmContract { .. } => "requestEvmContract",
192        }
193    }
194
195    /// The body under [`wire_name`](Self::wire_name), keys in the order the
196    /// docs and the venue's clients write them.
197    #[must_use]
198    pub fn body(&self) -> Map {
199        let token = |token: u32| Map::new().put("token", token);
200        match self {
201            SpotDeploy::RegisterToken2 { spec, max_gas, full_name } => {
202                let spec = Map::new()
203                    .put("name", spec.name.clone())
204                    .put("szDecimals", spec.sz_decimals)
205                    .put("weiDecimals", spec.wei_decimals);
206                Map::new().put("spec", spec).put("maxGas", *max_gas).put_some("fullName", full_name.clone())
207            }
208            SpotDeploy::UserGenesis { token, user_and_wei, existing_token_and_wei, blacklist_users } => {
209                let users = user_and_wei.iter().map(|(user, wei)| pair(user.to_hex(), wei.to_string()));
210                let existing = existing_token_and_wei.iter().map(|(token, wei)| pair(*token, wei.to_string()));
211                let blacklist = (!blacklist_users.is_empty())
212                    .then(|| Value::array(blacklist_users.iter().map(|(user, listed)| pair(user.to_hex(), *listed))));
213                Map::new()
214                    .put("token", *token)
215                    .put("userAndWei", Value::array(users))
216                    .put("existingTokenAndWei", Value::array(existing))
217                    .put_some("blacklistUsers", blacklist)
218            }
219            SpotDeploy::Genesis { token, max_supply, no_hyperliquidity } => Map::new()
220                .put("token", *token)
221                .put("maxSupply", max_supply.to_string())
222                .put_some("noHyperliquidity", no_hyperliquidity.then_some(true)),
223            SpotDeploy::RegisterSpot { base, quote } => Map::new().put("tokens", Value::array([*base, *quote])),
224            SpotDeploy::RegisterHyperliquidity { spot, start_px, order_sz, n_orders, n_seeded_levels } => Map::new()
225                .put("spot", *spot)
226                .put("startPx", start_px.to_wire())
227                .put("orderSz", order_sz.to_wire())
228                .put("nOrders", *n_orders)
229                .put_some("nSeededLevels", *n_seeded_levels),
230            SpotDeploy::SetDeployerTradingFeeShare { token, share } => {
231                Map::new().put("token", *token).put("share", share.to_wire())
232            }
233            SpotDeploy::EnableQuoteToken(id)
234            | SpotDeploy::EnableAlignedQuoteToken(id)
235            | SpotDeploy::DisableQuoteToken(id)
236            | SpotDeploy::DisableAlignedQuoteToken(id)
237            | SpotDeploy::EnableFreezePrivilege(id)
238            | SpotDeploy::RevokeFreezePrivilege(id) => token(*id),
239            SpotDeploy::SetTokenAnnotation { token, annotation } => {
240                Map::new().put("token", *token).put("annotation", annotation.wire_after(Map::new()))
241            }
242            SpotDeploy::SetDeployerLabel(label) => Map::new().put("label", label.as_str().to_owned()),
243            SpotDeploy::FreezeUser { token, user, freeze } => {
244                Map::new().put("token", *token).put("user", user.to_hex()).put("freeze", *freeze)
245            }
246            SpotDeploy::RequestEvmContract { token, address, evm_extra_wei_decimals } => Map::new()
247                .put("token", *token)
248                .put("address", address.to_hex())
249                .put("evmExtraWeiDecimals", i64::from(*evm_extra_wei_decimals)),
250        }
251    }
252}
253
254impl L1Action for SpotDeploy {
255    fn action(&self) -> Map {
256        Map::new().put("type", "spotDeploy").put(self.wire_name(), self.body())
257    }
258}
259
260#[cfg(test)]
261#[path = "tests/spot.rs"]
262mod tests;