Skip to main content

df_hyperliquid_core/utils/
asset.rs

1//! Asset ids: the integer an order names its market by. Ids run perps on the
2//! main dex below 10000, spot pairs from 10000, HIP-3 perps from 100000 and
3//! HIP-4 outcomes from 100000000, so an id alone says what it names, and so
4//! which builder cap holds it.
5
6use std::fmt;
7
8use crate::trade::builder::fee::{BuilderFee, OUTCOME_BUILDER_CAP, PERP_BUILDER_CAP, SPOT_BUILDER_CAP};
9use crate::utils::sign::msgpack::Value;
10
11/// Where spot pairs begin: `10000 + pair index`.
12pub const SPOT_ASSET_BASE: u32 = 10_000;
13
14/// Where HIP-3 perps begin: `100000 + dex * 10000 + index`, `dex` the dex's
15/// place in `perpDexs`, where the main dex is 0.
16pub const HIP3_ASSET_BASE: u32 = 100_000;
17
18/// How many ids each HIP-3 dex spans.
19pub const HIP3_DEX_SPAN: u32 = 10_000;
20
21/// Where HIP-4 outcomes begin: `100000000 + 10 * outcome + side`.
22pub const OUTCOME_ASSET_BASE: u32 = 100_000_000;
23
24/// A HIP-4 outcome's side, the last digit of its encoding.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub enum OutcomeSide {
27    /// The first side, `0`: the one a settle fraction pays.
28    Yes,
29    /// The second side, `1`.
30    No,
31}
32
33impl OutcomeSide {
34    /// The side's digit in an outcome asset id: 0 for yes, 1 for no.
35    #[must_use]
36    pub const fn digit(self) -> u32 {
37        match self {
38            OutcomeSide::Yes => 0,
39            OutcomeSide::No => 1,
40        }
41    }
42
43    /// The opposite side.
44    #[must_use]
45    pub const fn other(self) -> OutcomeSide {
46        match self {
47            OutcomeSide::Yes => OutcomeSide::No,
48            OutcomeSide::No => OutcomeSide::Yes,
49        }
50    }
51
52    /// `yes` or `no`, as serde writes it.
53    #[must_use]
54    pub const fn as_str(self) -> &'static str {
55        match self {
56            OutcomeSide::Yes => "yes",
57            OutcomeSide::No => "no",
58        }
59    }
60}
61
62impl serde::Serialize for OutcomeSide {
63    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
64        serializer.serialize_str(self.as_str())
65    }
66}
67
68impl<'de> serde::Deserialize<'de> for OutcomeSide {
69    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
70        match String::deserialize(deserializer)?.as_str() {
71            "yes" => Ok(OutcomeSide::Yes),
72            "no" => Ok(OutcomeSide::No),
73            other => Err(serde::de::Error::custom(format!("`{other}` is not an outcome side; expected yes or no"))),
74        }
75    }
76}
77
78/// What an asset id names.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80pub enum AssetKind {
81    /// A perp on the main dex: its index in `meta.universe`.
82    Perp,
83    /// A spot pair: `10000 + pair index`.
84    Spot,
85    /// A perp on a HIP-3 dex: `100000 + dex * 10000 + index`.
86    Hip3Perp,
87    /// A HIP-4 outcome side: `100000000 + 10 * outcome + side`.
88    Outcome,
89}
90
91impl AssetKind {
92    /// Every kind, in id order.
93    pub const ALL: [AssetKind; 4] = [AssetKind::Perp, AssetKind::Spot, AssetKind::Hip3Perp, AssetKind::Outcome];
94
95    /// The kind an asset id names, by the range it falls in.
96    #[must_use]
97    pub const fn of(id: u32) -> AssetKind {
98        if id >= OUTCOME_ASSET_BASE {
99            AssetKind::Outcome
100        } else if id >= HIP3_ASSET_BASE {
101            AssetKind::Hip3Perp
102        } else if id >= SPOT_ASSET_BASE {
103            AssetKind::Spot
104        } else {
105            AssetKind::Perp
106        }
107    }
108
109    /// The most a builder may take on an order of this kind: 0.1% on a perp,
110    /// main dex or HIP-3, and 1% on spot. HIP-4 takes builder codes as spot
111    /// does, per Hyperliquid's HIP-4 page.
112    #[must_use]
113    pub const fn builder_cap(self) -> BuilderFee {
114        match self {
115            AssetKind::Perp | AssetKind::Hip3Perp => PERP_BUILDER_CAP,
116            AssetKind::Spot => SPOT_BUILDER_CAP,
117            AssetKind::Outcome => OUTCOME_BUILDER_CAP,
118        }
119    }
120
121    /// The kind that holds an action over these assets to its builder cap:
122    /// the one with the lowest, so one perp leg holds the whole action to the
123    /// perp cap. `None` for no assets.
124    #[must_use]
125    pub fn strictest(assets: impl IntoIterator<Item = Asset>) -> Option<AssetKind> {
126        assets.into_iter().map(Asset::kind).reduce(|kept, next| match next.builder_cap() < kept.builder_cap() {
127            true => next,
128            false => kept,
129        })
130    }
131
132    /// `a perp`, `an outcome`: one order of this kind, in a sentence.
133    #[must_use]
134    pub const fn one(self) -> &'static str {
135        match self {
136            AssetKind::Perp => "a perp",
137            AssetKind::Spot => "a spot",
138            AssetKind::Hip3Perp => "a HIP-3 perp",
139            AssetKind::Outcome => "an outcome",
140        }
141    }
142}
143
144/// An asset id. Made from the index it is counted from, so a pair index is
145/// never sent where an asset id belongs; an index past its range is refused
146/// rather than spilling into the next kind's ids.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
148pub struct Asset(u32);
149
150impl Asset {
151    /// An id as the venue wrote it, in an order status or a fill.
152    #[must_use]
153    pub const fn from_id(id: u32) -> Asset {
154        Asset(id)
155    }
156
157    /// The integer id, as an order's `a` carries it.
158    #[must_use]
159    pub const fn id(self) -> u32 {
160        self.0
161    }
162
163    /// What the id names, by its range.
164    #[must_use]
165    pub const fn kind(self) -> AssetKind {
166        AssetKind::of(self.0)
167    }
168
169    /// A perp on the main dex, by its index in `meta.universe`.
170    #[must_use]
171    pub const fn perp(index: u32) -> Option<Asset> {
172        match index < SPOT_ASSET_BASE {
173            true => Some(Asset(index)),
174            false => None,
175        }
176    }
177
178    /// A spot pair, by the pair's own `index` in `spotMeta.universe`, which
179    /// is not a token's index.
180    #[must_use]
181    pub const fn spot(pair: u32) -> Option<Asset> {
182        match pair < HIP3_ASSET_BASE - SPOT_ASSET_BASE {
183            true => Some(Asset(SPOT_ASSET_BASE + pair)),
184            false => None,
185        }
186    }
187
188    /// A perp on a HIP-3 dex: `dex` its place in `perpDexs` (1 or more; the
189    /// main dex at 0 is [`Asset::perp`]), `index` its place in that dex's
190    /// `meta.universe`.
191    #[must_use]
192    pub const fn hip3(dex: u32, index: u32) -> Option<Asset> {
193        if dex == 0 || index >= HIP3_DEX_SPAN {
194            return None;
195        }
196        let Some(offset) = dex.checked_mul(HIP3_DEX_SPAN) else {
197            return None;
198        };
199        let Some(start) = HIP3_ASSET_BASE.checked_add(offset) else {
200            return None;
201        };
202        match start.checked_add(index) {
203            Some(id) if id < OUTCOME_ASSET_BASE => Some(Asset(id)),
204            _ => None,
205        }
206    }
207
208    /// A HIP-3 perp's dex place in `perpDexs` and its index in that dex's
209    /// `meta`: [`Asset::hip3`] taken apart. `None` for any other kind of id.
210    #[must_use]
211    pub const fn hip3_parts(self) -> Option<(u32, u32)> {
212        if !matches!(self.kind(), AssetKind::Hip3Perp) {
213            return None;
214        }
215        let offset = self.0 - HIP3_ASSET_BASE;
216        match offset / HIP3_DEX_SPAN {
217            0 => None,
218            place => Some((place, offset % HIP3_DEX_SPAN)),
219        }
220    }
221
222    /// A perp by its dex's place in `perpDexs`: the main dex at 0, else HIP-3.
223    #[must_use]
224    pub const fn perp_on(dex: u32, index: u32) -> Option<Asset> {
225        match dex {
226            0 => Asset::perp(index),
227            dex => Asset::hip3(dex, index),
228        }
229    }
230
231    /// A HIP-4 outcome side: `100000000 + 10 * outcome + side`.
232    #[must_use]
233    pub const fn outcome(outcome: u32, side: OutcomeSide) -> Option<Asset> {
234        let Some(tens) = outcome.checked_mul(10) else {
235            return None;
236        };
237        match OUTCOME_ASSET_BASE.checked_add(tens + side.digit()) {
238            Some(id) => Some(Asset(id)),
239            None => None,
240        }
241    }
242
243    /// The outcome and side an outcome id names; `None` for any other kind.
244    #[must_use]
245    pub const fn outcome_side(self) -> Option<(u32, OutcomeSide)> {
246        if self.0 < OUTCOME_ASSET_BASE {
247            return None;
248        }
249        let encoding = self.0 - OUTCOME_ASSET_BASE;
250        let side = match encoding % 10 {
251            0 => OutcomeSide::Yes,
252            1 => OutcomeSide::No,
253            _ => return None,
254        };
255        Some((encoding / 10, side))
256    }
257}
258
259impl fmt::Display for Asset {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        write!(f, "{}", self.0)
262    }
263}
264
265/// An asset goes on the wire as its plain id.
266impl From<Asset> for Value {
267    fn from(asset: Asset) -> Value {
268        Value::Uint(u64::from(asset.0))
269    }
270}
271
272#[cfg(test)]
273#[path = "tests/asset.rs"]
274mod tests;