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