Skip to main content

df_hyperliquid_core/deploy/perp/
mod.rs

1//! Deploying and running a HIP-3 perp dex: every `perpDeploy` variant the docs list, all L1 actions.
2//! The deploy auction read is in [`dexes`](crate::deploy::dexes). The testnet-only HIP-3* `star`
3//! operations are not here.
4
5pub mod asset;
6pub mod margin;
7pub mod sub;
8
9pub use asset::{DexSchema, MarginMode, NewAsset};
10pub use margin::{MarginTable, MarginTier};
11pub use sub::{PerpKind, SubDeployer};
12
13use std::collections::{BTreeMap, btree_map::Entry};
14
15use crate::deploy::annotation::Annotation;
16use crate::deploy::error::BadDeploy;
17use crate::deploy::name::DexName;
18use crate::utils::sign::{L1Action, Map, Value};
19use crate::utils::{Address, Dec};
20
21/// Values by coin (`dex:NAME`), kept in the order the venue hashes them:
22/// bytewise by coin, so `xyz:BTC` comes before `xyz:abc`.
23pub type ByCoin<T> = BTreeMap<String, T>;
24
25/// A deployer's fee setting for one asset: the scale applied to user fees
26/// and whether growth mode is on.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct DeployerFee {
29    /// From 0 to 3, or from 0 up to (not including) 10 in growth mode.
30    pub scale: Dec,
31    /// Growth mode (`growthMode`): when on, the scale may go up to (not including) 10.
32    pub growth_mode: bool,
33}
34
35/// `{"type":"perpDeploy",<variant>:..}`. The constructors check what the
36/// docs rule out and take each per-coin list in any order, refusing a coin
37/// given twice; the lists go out sorted by coin, as the venue requires.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum PerpDeploy {
40    /// `registerAsset2`: an asset with a margin mode. With a schema it also
41    /// creates the dex. `max_gas` is in HYPE wei, 8 decimals; `None` (sent as
42    /// null) pays the current auction price, and 0 uses a reserve
43    /// deployment whether or not the auction has ended.
44    RegisterAsset2 {
45        /// The most to pay (`maxGas`), in HYPE wei, 8 decimals (1 HYPE is `100_000_000`); `None`,
46        /// sent as null, pays the current auction price. The gas paid is not refunded.
47        max_gas: Option<u64>,
48        /// The asset to list (`assetRequest`).
49        asset: NewAsset,
50        /// How the asset may be margined (`marginMode`).
51        margin_mode: MarginMode,
52        /// The dex the asset is listed on.
53        dex: DexName,
54        /// The new dex's schema when this asset creates the dex; `None`, sent as null, for an existing dex.
55        schema: Option<DexSchema>,
56    },
57    /// `registerAsset`: as [`RegisterAsset2`](PerpDeploy::RegisterAsset2),
58    /// with `onlyIsolated` for the margin mode.
59    RegisterAsset {
60        /// The most to pay (`maxGas`), in HYPE wei, 8 decimals (1 HYPE is `100_000_000`); `None`,
61        /// sent as null, pays the current auction price. The gas paid is not refunded.
62        max_gas: Option<u64>,
63        /// The asset to list (`assetRequest`).
64        asset: NewAsset,
65        /// Whether the asset is isolated margin only (`onlyIsolated`).
66        only_isolated: bool,
67        /// The dex the asset is listed on.
68        dex: DexName,
69        /// The new dex's schema when this asset creates the dex; `None`, sent as null, for an existing dex.
70        schema: Option<DexSchema>,
71    },
72    /// `setOracle`: oracle prices, 0 to 2 lists of mark prices, and external
73    /// perp prices for every asset. At least 2.5 seconds apart.
74    SetOracle {
75        /// The dex the prices are for.
76        dex: DexName,
77        /// Oracle prices by coin (`oraclePxs`).
78        oracle_pxs: ByCoin<Dec>,
79        /// 0 to 2 lists of mark prices by coin (`markPxs`).
80        mark_pxs: Vec<ByCoin<Dec>>,
81        /// External perp prices by coin (`externalPerpPxs`).
82        external_perp_pxs: ByCoin<Dec>,
83    },
84    /// `setFundingMultipliers`, each from 0 to 10.
85    SetFundingMultipliers(ByCoin<Dec>),
86    /// `setFundingInterestRates`: 8 hour rates, each from -0.01 to 0.01.
87    SetFundingInterestRates(ByCoin<Dec>),
88    /// `setFundingClamps`: 8 hour clamps, each from 0 to 0.01.
89    SetFundingClamps(ByCoin<Dec>),
90    /// `haltTrading`: halts (`true`) or resumes (`false`) one asset.
91    HaltTrading {
92        /// The coin, `dex:NAME`.
93        coin: String,
94        /// `true` halts the asset, `false` resumes it (`isHalted`).
95        is_halted: bool,
96    },
97    /// `insertMarginTable`.
98    InsertMarginTable {
99        /// The dex the table is for.
100        dex: DexName,
101        /// The table to insert (`marginTable`).
102        margin_table: MarginTable,
103    },
104    /// `setMarginTableIds`, none of them 0.
105    SetMarginTableIds(ByCoin<u32>),
106    /// `setFeeRecipient`.
107    SetFeeRecipient {
108        /// The dex whose fees are paid out.
109        dex: DexName,
110        /// The address the deployer's fee share goes to (`feeRecipient`).
111        fee_recipient: Address,
112    },
113    /// `setOpenInterestCaps`: notional caps; `None` (sent as null) removes
114    /// an asset's custom cap. A cap is in millionths of the dex's collateral token whatever its
115    /// `weiDecimals`: `1_000_000` is one token of notional. `perpDexLimits` shows it in whole
116    /// tokens. Confirmed against mainnet caps on USDC, USDE, USDH and USDT0 dexes.
117    SetOpenInterestCaps(ByCoin<Option<u64>>),
118    /// `setSubDeployers`.
119    SetSubDeployers {
120        /// The dex the grants are for.
121        dex: DexName,
122        /// The grants (`subDeployers`), at least one.
123        sub_deployers: Vec<SubDeployer>,
124    },
125    /// `setMarginModes`.
126    SetMarginModes(ByCoin<MarginMode>),
127    /// `setDeployerFees`. On mainnet, one change per 30 days.
128    SetDeployerFees(ByCoin<DeployerFee>),
129    /// `setPerpAnnotation`.
130    SetPerpAnnotation {
131        /// The coin, `dex:NAME`.
132        coin: String,
133        /// The annotation, sent flat next to the coin.
134        annotation: Annotation,
135    },
136    /// `disableDex`.
137    DisableDex(DexName),
138}
139
140/// `pairs` by coin, a coin given twice refused.
141fn by_coin<K: Into<String>, T>(pairs: impl IntoIterator<Item = (K, T)>) -> Result<ByCoin<T>, BadDeploy> {
142    let mut coins = ByCoin::new();
143    for (coin, value) in pairs {
144        match coins.entry(coin.into()) {
145            Entry::Occupied(taken) => return Err(BadDeploy::Twice(taken.key().clone())),
146            Entry::Vacant(slot) => {
147                slot.insert(value);
148            }
149        }
150    }
151    Ok(coins)
152}
153
154/// `value` if it is from `least` to `most`.
155fn within(
156    what: &'static str,
157    value: Dec,
158    (least, least_text): (Dec, &'static str),
159    (most, most_text): (Dec, &'static str),
160) -> Result<Dec, BadDeploy> {
161    if value < least || value > most {
162        return Err(BadDeploy::OutOfRange { what, least: least_text, most: most_text, value: value.to_wire() });
163    }
164    Ok(value)
165}
166
167/// Each value of `coins` checked by `check`.
168fn checked<T: Copy>(coins: &ByCoin<T>, check: impl Fn(T) -> Result<(), BadDeploy>) -> Result<(), BadDeploy> {
169    coins.values().try_for_each(|value| check(*value))
170}
171
172fn not_negative(what: &'static str, value: Dec) -> Result<(), BadDeploy> {
173    if value.is_negative() {
174        return Err(BadDeploy::OutOfRange { what, least: "0", most: "any", value: value.to_wire() });
175    }
176    Ok(())
177}
178
179/// `[[coin, value], ..]` in coin order.
180fn tuples<T>(coins: &ByCoin<T>, value: impl Fn(&T) -> Value) -> Value {
181    Value::array(coins.iter().map(|(coin, one)| Value::Array(vec![coin.clone().into(), value(one)])))
182}
183
184fn decimals(coins: &ByCoin<Dec>) -> Value {
185    tuples(coins, |value| value.to_wire().into())
186}
187
188const ZERO: (Dec, &str) = (Dec::ZERO, "0");
189const TEN: (Dec, &str) = (Dec::lit::<0>(10), "10");
190const RATE: Dec = Dec::lit::<2>(1);
191
192impl PerpDeploy {
193    /// `registerAsset2`, refusing a negative oracle price.
194    pub fn register_asset2(
195        dex: DexName,
196        max_gas: Option<u64>,
197        asset: NewAsset,
198        margin_mode: MarginMode,
199        schema: Option<DexSchema>,
200    ) -> Result<Self, BadDeploy> {
201        not_negative("oraclePx", asset.oracle_px)?;
202        Ok(PerpDeploy::RegisterAsset2 { max_gas, asset, margin_mode, dex, schema })
203    }
204
205    /// `registerAsset`, refusing a negative oracle price.
206    pub fn register_asset(
207        dex: DexName,
208        max_gas: Option<u64>,
209        asset: NewAsset,
210        only_isolated: bool,
211        schema: Option<DexSchema>,
212    ) -> Result<Self, BadDeploy> {
213        not_negative("oraclePx", asset.oracle_px)?;
214        Ok(PerpDeploy::RegisterAsset { max_gas, asset, only_isolated, dex, schema })
215    }
216
217    /// `setOracle`, refusing more than 2 mark price lists or a negative price.
218    pub fn set_oracle<K: Into<String>>(
219        dex: DexName,
220        oracle_pxs: impl IntoIterator<Item = (K, Dec)>,
221        mark_pxs: Vec<Vec<(K, Dec)>>,
222        external_perp_pxs: impl IntoIterator<Item = (K, Dec)>,
223    ) -> Result<Self, BadDeploy> {
224        if mark_pxs.len() > 2 {
225            return Err(BadDeploy::MarkPxs(mark_pxs.len()));
226        }
227        let oracle_pxs = by_coin(oracle_pxs)?;
228        let mark_pxs = mark_pxs.into_iter().map(by_coin).collect::<Result<Vec<_>, _>>()?;
229        let external_perp_pxs = by_coin(external_perp_pxs)?;
230        checked(&oracle_pxs, |px| not_negative("an oracle price", px))?;
231        mark_pxs.iter().try_for_each(|marks| checked(marks, |px| not_negative("a mark price", px)))?;
232        checked(&external_perp_pxs, |px| not_negative("an external perp price", px))?;
233        Ok(PerpDeploy::SetOracle { dex, oracle_pxs, mark_pxs, external_perp_pxs })
234    }
235
236    /// `setFundingMultipliers`, each from 0 to 10.
237    pub fn set_funding_multipliers<K: Into<String>>(
238        multipliers: impl IntoIterator<Item = (K, Dec)>,
239    ) -> Result<Self, BadDeploy> {
240        let multipliers = by_coin(multipliers)?;
241        checked(&multipliers, |value| within("a funding multiplier", value, ZERO, TEN).map(drop))?;
242        Ok(PerpDeploy::SetFundingMultipliers(multipliers))
243    }
244
245    /// `setFundingInterestRates`, each from -0.01 to 0.01.
246    pub fn set_funding_interest_rates<K: Into<String>>(
247        rates: impl IntoIterator<Item = (K, Dec)>,
248    ) -> Result<Self, BadDeploy> {
249        let rates = by_coin(rates)?;
250        checked(&rates, |value| {
251            within("a funding interest rate", value, (RATE.negate(), "-0.01"), (RATE, "0.01")).map(drop)
252        })?;
253        Ok(PerpDeploy::SetFundingInterestRates(rates))
254    }
255
256    /// `setFundingClamps`, each from 0 to 0.01.
257    pub fn set_funding_clamps<K: Into<String>>(clamps: impl IntoIterator<Item = (K, Dec)>) -> Result<Self, BadDeploy> {
258        let clamps = by_coin(clamps)?;
259        checked(&clamps, |value| within("a funding clamp", value, ZERO, (RATE, "0.01")).map(drop))?;
260        Ok(PerpDeploy::SetFundingClamps(clamps))
261    }
262
263    /// `setMarginTableIds`, refusing id 0.
264    pub fn set_margin_table_ids<K: Into<String>>(ids: impl IntoIterator<Item = (K, u32)>) -> Result<Self, BadDeploy> {
265        let ids = by_coin(ids)?;
266        if let Some((coin, _)) = ids.iter().find(|(_, id)| **id == 0) {
267            return Err(BadDeploy::MarginTableZero(coin.clone()));
268        }
269        Ok(PerpDeploy::SetMarginTableIds(ids))
270    }
271
272    /// `setOpenInterestCaps`; `None` removes an asset's custom cap. Caps are in millionths of the
273    /// collateral token, as [`PerpDeploy::SetOpenInterestCaps`] says.
274    pub fn set_open_interest_caps<K: Into<String>>(
275        caps: impl IntoIterator<Item = (K, Option<u64>)>,
276    ) -> Result<Self, BadDeploy> {
277        Ok(PerpDeploy::SetOpenInterestCaps(by_coin(caps)?))
278    }
279
280    /// `setSubDeployers`, refusing an empty list.
281    pub fn set_sub_deployers(dex: DexName, sub_deployers: Vec<SubDeployer>) -> Result<Self, BadDeploy> {
282        if sub_deployers.is_empty() {
283            return Err(BadDeploy::NoGrants);
284        }
285        Ok(PerpDeploy::SetSubDeployers { dex, sub_deployers })
286    }
287
288    /// `setMarginModes`.
289    pub fn set_margin_modes<K: Into<String>>(
290        modes: impl IntoIterator<Item = (K, MarginMode)>,
291    ) -> Result<Self, BadDeploy> {
292        Ok(PerpDeploy::SetMarginModes(by_coin(modes)?))
293    }
294
295    /// `setDeployerFees`: each scale from 0 to 3, or from 0 up to (not
296    /// including) 10 in growth mode.
297    pub fn set_deployer_fees<K: Into<String>>(
298        fees: impl IntoIterator<Item = (K, DeployerFee)>,
299    ) -> Result<Self, BadDeploy> {
300        let fees = by_coin(fees)?;
301        checked(&fees, |fee| {
302            if fee.growth_mode {
303                if fee.scale >= TEN.0 {
304                    return Err(BadDeploy::OutOfRange {
305                        what: "a growth mode fee scale",
306                        least: "0",
307                        most: "just under 10",
308                        value: fee.scale.to_wire(),
309                    });
310                }
311                not_negative("a growth mode fee scale", fee.scale)
312            } else {
313                within("a fee scale", fee.scale, ZERO, (Dec::lit::<0>(3), "3")).map(drop)
314            }
315        })?;
316        Ok(PerpDeploy::SetDeployerFees(fees))
317    }
318
319    /// The variant, by the key it travels under.
320    #[must_use]
321    pub const fn kind(&self) -> PerpKind {
322        match self {
323            PerpDeploy::RegisterAsset2 { .. } => PerpKind::RegisterAsset2,
324            PerpDeploy::RegisterAsset { .. } => PerpKind::RegisterAsset,
325            PerpDeploy::SetOracle { .. } => PerpKind::SetOracle,
326            PerpDeploy::SetFundingMultipliers(_) => PerpKind::SetFundingMultipliers,
327            PerpDeploy::SetFundingInterestRates(_) => PerpKind::SetFundingInterestRates,
328            PerpDeploy::SetFundingClamps(_) => PerpKind::SetFundingClamps,
329            PerpDeploy::HaltTrading { .. } => PerpKind::HaltTrading,
330            PerpDeploy::InsertMarginTable { .. } => PerpKind::InsertMarginTable,
331            PerpDeploy::SetMarginTableIds(_) => PerpKind::SetMarginTableIds,
332            PerpDeploy::SetFeeRecipient { .. } => PerpKind::SetFeeRecipient,
333            PerpDeploy::SetOpenInterestCaps(_) => PerpKind::SetOpenInterestCaps,
334            PerpDeploy::SetSubDeployers { .. } => PerpKind::SetSubDeployers,
335            PerpDeploy::SetMarginModes(_) => PerpKind::SetMarginModes,
336            PerpDeploy::SetDeployerFees(_) => PerpKind::SetDeployerFees,
337            PerpDeploy::SetPerpAnnotation { .. } => PerpKind::SetPerpAnnotation,
338            PerpDeploy::DisableDex(_) => PerpKind::DisableDex,
339        }
340    }
341
342    /// The value under the variant's key, keys in the order the docs and
343    /// the venue's clients write them.
344    #[must_use]
345    pub fn body(&self) -> Value {
346        let gas = |max_gas: &Option<u64>| max_gas.map_or(Value::Nil, Value::from);
347        let schema = |schema: &Option<DexSchema>| schema.as_ref().map_or(Value::Nil, |one| one.wire().into());
348        match self {
349            PerpDeploy::RegisterAsset2 { max_gas, asset, margin_mode, dex, schema: new } => Map::new()
350                .put("maxGas", gas(max_gas))
351                .put("assetRequest", asset.wire().put("marginMode", margin_mode.wire()))
352                .put("dex", dex.as_str().to_owned())
353                .put("schema", schema(new))
354                .into(),
355            PerpDeploy::RegisterAsset { max_gas, asset, only_isolated, dex, schema: new } => Map::new()
356                .put("maxGas", gas(max_gas))
357                .put("assetRequest", asset.wire().put("onlyIsolated", *only_isolated))
358                .put("dex", dex.as_str().to_owned())
359                .put("schema", schema(new))
360                .into(),
361            PerpDeploy::SetOracle { dex, oracle_pxs, mark_pxs, external_perp_pxs } => Map::new()
362                .put("dex", dex.as_str().to_owned())
363                .put("oraclePxs", decimals(oracle_pxs))
364                .put("markPxs", Value::array(mark_pxs.iter().map(decimals)))
365                .put("externalPerpPxs", decimals(external_perp_pxs))
366                .into(),
367            PerpDeploy::SetFundingMultipliers(values)
368            | PerpDeploy::SetFundingInterestRates(values)
369            | PerpDeploy::SetFundingClamps(values) => decimals(values),
370            PerpDeploy::HaltTrading { coin, is_halted } => {
371                Map::new().put("coin", coin.clone()).put("isHalted", *is_halted).into()
372            }
373            PerpDeploy::InsertMarginTable { dex, margin_table } => {
374                Map::new().put("dex", dex.as_str().to_owned()).put("marginTable", margin_table.wire()).into()
375            }
376            PerpDeploy::SetMarginTableIds(ids) => tuples(ids, |id| (*id).into()),
377            PerpDeploy::SetFeeRecipient { dex, fee_recipient } => {
378                Map::new().put("dex", dex.as_str().to_owned()).put("feeRecipient", fee_recipient.to_hex()).into()
379            }
380            PerpDeploy::SetOpenInterestCaps(caps) => tuples(caps, |cap| cap.map_or(Value::Nil, Value::from)),
381            PerpDeploy::SetSubDeployers { dex, sub_deployers } => Map::new()
382                .put("dex", dex.as_str().to_owned())
383                .put("subDeployers", Value::array(sub_deployers.iter().map(SubDeployer::wire)))
384                .into(),
385            PerpDeploy::SetMarginModes(modes) => tuples(modes, |mode| mode.wire().into()),
386            PerpDeploy::SetDeployerFees(fees) => tuples(fees, |fee| {
387                Map::new().put("scale", fee.scale.to_wire()).put("growthMode", fee.growth_mode).into()
388            }),
389            PerpDeploy::SetPerpAnnotation { coin, annotation } => {
390                annotation.wire_after(Map::new().put("coin", coin.clone())).into()
391            }
392            PerpDeploy::DisableDex(dex) => dex.as_str().to_owned().into(),
393        }
394    }
395}
396
397impl L1Action for PerpDeploy {
398    fn action(&self) -> Map {
399        Map::new().put("type", "perpDeploy").put(self.kind().wire(), self.body())
400    }
401}
402
403#[cfg(test)]
404#[path = "tests/perp.rs"]
405mod tests;