Skip to main content

df_hyperliquid_core/trade/margin/
tables.rs

1//! Margin tables and the leverage a perp allows, checked before anything is signed. A perp names
2//! its table by `marginTableId`; an id under [`FLAT_TABLES_BELOW`] is a single tier at that
3//! leverage, never listed. The main dex and every HIP-3 dex read them the same way.
4
5use crate::trade::error::TradeError;
6use crate::trade::margin::{MarginMode, UpdateLeverage};
7use crate::utils::{Asset, Dec};
8use serde::Deserialize;
9
10/// A table id under this is a flat table at that leverage.
11pub const FLAT_TABLES_BELOW: u32 = 50;
12
13/// A margin table, as a meta's `marginTables` lists it: the most leverage by position notional.
14#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
15#[serde(rename_all = "camelCase")]
16pub struct MarginTable {
17    /// `tiered 40x`; empty on some.
18    pub description: String,
19    /// Lowest first.
20    pub margin_tiers: Vec<MarginTier>,
21}
22
23/// From `lower_bound` of notional on, at most `max_leverage`.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct MarginTier {
27    /// In the dex's collateral.
28    pub lower_bound: Dec,
29    /// `maxLeverage`: the most leverage from `lower_bound` on.
30    pub max_leverage: u32,
31}
32
33impl MarginTable {
34    /// One tier, from nothing on: what an id under [`FLAT_TABLES_BELOW`] is.
35    #[must_use]
36    pub fn flat(max_leverage: u32) -> MarginTable {
37        MarginTable {
38            description: String::new(),
39            margin_tiers: vec![MarginTier { lower_bound: Dec::ZERO, max_leverage }],
40        }
41    }
42
43    /// A table by its id: flat under [`FLAT_TABLES_BELOW`], else one of
44    /// `listed`, a meta's `marginTables`. No perp is on table 0.
45    #[must_use]
46    pub fn by_id(id: u32, listed: &[(u32, MarginTable)]) -> Option<MarginTable> {
47        match id {
48            0 => None,
49            id if id < FLAT_TABLES_BELOW => Some(MarginTable::flat(id)),
50            id => listed.iter().find(|(at, _)| *at == id).map(|(_, table)| table.clone()),
51        }
52    }
53
54    /// The most leverage a position of `notional` may take: the tier with the
55    /// highest lower bound at or under it. A short's notional counts as its
56    /// size. The docs do not say which tier a notional exactly on a bound
57    /// falls in; here it is the higher one, the bound being its lower.
58    #[must_use]
59    pub fn max_leverage_at(&self, notional: Dec) -> Option<u32> {
60        let notional = notional.abs();
61        self.margin_tiers
62            .iter()
63            .filter(|tier| tier.lower_bound <= notional)
64            .max_by_key(|tier| tier.lower_bound)
65            .map(|tier| tier.max_leverage)
66    }
67
68    /// `leverage` on the perp `name`, refused over what the tier a position
69    /// of `notional` reaches allows.
70    pub fn check(&self, name: &str, leverage: u32, notional: Dec) -> Result<(), LeverageError> {
71        match self.max_leverage_at(notional) {
72            Some(max) if leverage > max => {
73                Err(LeverageError::OverTier { name: name.to_owned(), notional: notional.abs(), max, asked: leverage })
74            }
75            _ => Ok(()),
76        }
77    }
78}
79
80/// Why a leverage is not one the perp allows.
81#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
82pub enum LeverageError {
83    /// Over the perp's `maxLeverage`.
84    #[error("{name} allows at most {max}x, not {asked}x")]
85    TooHigh {
86        /// The perp's name.
87        name: String,
88        /// Its `maxLeverage`.
89        max: u32,
90        /// The leverage asked for.
91        asked: u32,
92    },
93    /// Over what the margin tier a position of this notional reaches allows.
94    #[error("{name} allows at most {max}x at a notional of {notional}, not {asked}x")]
95    OverTier {
96        /// The perp's name.
97        name: String,
98        /// The position's notional, unsigned, in the dex's collateral.
99        notional: Dec,
100        /// The most leverage the tier allows.
101        max: u32,
102        /// The leverage asked for.
103        asked: u32,
104    },
105    /// The perp is isolated only, and cross was asked for; the perp's name.
106    #[error("{0} is isolated only")]
107    NoCross(String),
108    /// A check on the action itself failed: a leverage of 0.
109    #[error(transparent)]
110    Trade(#[from] TradeError),
111}
112
113/// `updateLeverage` at `asset` for the perp `name`: refused over `max`, its `maxLeverage`, and
114/// refused as cross where `cross` is false, the perp being isolated only. Both come from the
115/// perp's meta.
116pub fn checked_leverage(
117    asset: Asset,
118    name: &str,
119    max: u32,
120    cross: bool,
121    mode: MarginMode,
122    leverage: u32,
123) -> Result<UpdateLeverage, LeverageError> {
124    if leverage > max {
125        return Err(LeverageError::TooHigh { name: name.to_owned(), max, asked: leverage });
126    }
127    if mode == MarginMode::Cross && !cross {
128        return Err(LeverageError::NoCross(name.to_owned()));
129    }
130    Ok(UpdateLeverage::new(asset, mode, leverage)?)
131}
132
133#[cfg(test)]
134#[path = "tests/tables.rs"]
135mod tests;