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