Skip to main content

df_hyperliquid_core/deploy/perp/
margin.rs

1//! A margin table a HIP-3 deployer inserts: up to three tiers of position size and the leverage
2//! allowed above each.
3
4use crate::deploy::error::BadDeploy;
5use crate::utils::sign::{Map, Value};
6
7/// The highest max leverage a tier takes.
8pub const MAX_LEVERAGE: u32 = 50;
9/// The most tiers a table takes.
10pub const MAX_TIERS: usize = 3;
11
12/// Above `lower_bound` of position notional, leverage is at most
13/// `max_leverage`.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct MarginTier {
16    /// Position notional from which this tier applies (`lowerBound`).
17    pub lower_bound: u64,
18    /// The highest leverage allowed from the lower bound up (`maxLeverage`), from 1 to 50.
19    pub max_leverage: u32,
20}
21
22/// `{"description","marginTiers"}`: 1 to 3 tiers, lower bounds rising and
23/// max leverage falling, each leverage from 1 to 50.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct MarginTable {
26    description: String,
27    tiers: Vec<MarginTier>,
28}
29
30impl MarginTable {
31    /// Refuses no tiers, more than three, a leverage outside 1 to 50, or
32    /// tiers out of order.
33    pub fn new(description: impl Into<String>, tiers: Vec<MarginTier>) -> Result<Self, BadDeploy> {
34        let in_range = tiers.iter().all(|tier| (1..=MAX_LEVERAGE).contains(&tier.max_leverage));
35        let ordered = tiers
36            .windows(2)
37            .all(|two| two[0].lower_bound < two[1].lower_bound && two[0].max_leverage > two[1].max_leverage);
38        if tiers.is_empty() || tiers.len() > MAX_TIERS || !in_range || !ordered {
39            return Err(BadDeploy::MarginTiers);
40        }
41        Ok(MarginTable { description: description.into(), tiers })
42    }
43
44    /// The table's description.
45    #[must_use]
46    pub fn description(&self) -> &str {
47        &self.description
48    }
49
50    /// The tiers, lower bounds rising.
51    #[must_use]
52    pub fn tiers(&self) -> &[MarginTier] {
53        &self.tiers
54    }
55
56    /// The table as sent.
57    #[must_use]
58    pub fn wire(&self) -> Map {
59        let tiers = self
60            .tiers
61            .iter()
62            .map(|tier| Map::new().put("lowerBound", tier.lower_bound).put("maxLeverage", tier.max_leverage));
63        Map::new().put("description", self.description.clone()).put("marginTiers", Value::array(tiers))
64    }
65}