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