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)]
80#[non_exhaustive]
81pub enum AssetKind {
82    /// A perp on the main dex: its index in `meta.universe`.
83    Perp,
84    /// A spot pair: `10000 + pair index`.
85    Spot,
86    /// A perp on a HIP-3 dex: `100000 + dex * 10000 + index`.
87    Hip3Perp,
88    /// A HIP-4 outcome side: `100000000 + 10 * outcome + side`.
89    Outcome,
90}
91
92impl AssetKind {
93    /// Every kind, in id order.
94    pub const ALL: [AssetKind; 4] = [AssetKind::Perp, AssetKind::Spot, AssetKind::Hip3Perp, AssetKind::Outcome];
95
96    /// The kind an asset id names, by the range it falls in.
97    #[must_use]
98    pub const fn of(id: u32) -> AssetKind {
99        if id >= OUTCOME_ASSET_BASE {
100            AssetKind::Outcome
101        } else if id >= HIP3_ASSET_BASE {
102            AssetKind::Hip3Perp
103        } else if id >= SPOT_ASSET_BASE {
104            AssetKind::Spot
105        } else {
106            AssetKind::Perp
107        }
108    }
109
110    /// The most a builder may take on an order of this kind: 0.1% on a perp,
111    /// main dex or HIP-3, and 1% on spot. HIP-4 takes builder codes as spot
112    /// does, per Hyperliquid's HIP-4 page.
113    #[must_use]
114    pub const fn builder_cap(self) -> BuilderFee {
115        match self {
116            AssetKind::Perp | AssetKind::Hip3Perp => PERP_BUILDER_CAP,
117            AssetKind::Spot => SPOT_BUILDER_CAP,
118            AssetKind::Outcome => OUTCOME_BUILDER_CAP,
119        }
120    }
121
122    /// The kind that holds an action over these assets to its builder cap:
123    /// the one with the lowest, so one perp leg holds the whole action to the
124    /// perp cap. `None` for no assets.
125    #[must_use]
126    pub fn strictest(assets: impl IntoIterator<Item = Asset>) -> Option<AssetKind> {
127        assets.into_iter().map(Asset::kind).reduce(|kept, next| match next.builder_cap() < kept.builder_cap() {
128            true => next,
129            false => kept,
130        })
131    }
132
133    /// `a perp`, `an outcome`: one order of this kind, in a sentence.
134    #[must_use]
135    pub const fn one(self) -> &'static str {
136        match self {
137            AssetKind::Perp => "a perp",
138            AssetKind::Spot => "a spot",
139            AssetKind::Hip3Perp => "a HIP-3 perp",
140            AssetKind::Outcome => "an outcome",
141        }
142    }
143}
144
145/// An asset id. Made from the index it is counted from, so a pair index is
146/// never sent where an asset id belongs; an index past its range is refused
147/// rather than spilling into the next kind's ids.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
149pub struct Asset(u32);
150
151impl Asset {
152    /// An id as the venue wrote it, in an order status or a fill.
153    #[must_use]
154    pub const fn from_id(id: u32) -> Asset {
155        Asset(id)
156    }
157
158    /// The integer id, as an order's `a` carries it.
159    #[must_use]
160    pub const fn id(self) -> u32 {
161        self.0
162    }
163
164    /// What the id names, by its range.
165    #[must_use]
166    pub const fn kind(self) -> AssetKind {
167        AssetKind::of(self.0)
168    }
169
170    /// A perp on the main dex, by its index in `meta.universe`.
171    #[must_use]
172    pub const fn perp(index: u32) -> Option<Asset> {
173        match index < SPOT_ASSET_BASE {
174            true => Some(Asset(index)),
175            false => None,
176        }
177    }
178
179    /// A spot pair, by the pair's own `index` in `spotMeta.universe`, which
180    /// is not a token's index.
181    #[must_use]
182    pub const fn spot(pair: u32) -> Option<Asset> {
183        match pair < HIP3_ASSET_BASE - SPOT_ASSET_BASE {
184            true => Some(Asset(SPOT_ASSET_BASE + pair)),
185            false => None,
186        }
187    }
188
189    /// A perp on a HIP-3 dex: `dex` its place in `perpDexs` (1 or more; the
190    /// main dex at 0 is [`Asset::perp`]), `index` its place in that dex's
191    /// `meta.universe`.
192    #[must_use]
193    pub const fn hip3(dex: u32, index: u32) -> Option<Asset> {
194        if dex == 0 || index >= HIP3_DEX_SPAN {
195            return None;
196        }
197        let Some(offset) = dex.checked_mul(HIP3_DEX_SPAN) else {
198            return None;
199        };
200        let Some(start) = HIP3_ASSET_BASE.checked_add(offset) else {
201            return None;
202        };
203        match start.checked_add(index) {
204            Some(id) if id < OUTCOME_ASSET_BASE => Some(Asset(id)),
205            _ => None,
206        }
207    }
208
209    /// A HIP-3 perp's dex place in `perpDexs` and its index in that dex's
210    /// `meta`: [`Asset::hip3`] taken apart. `None` for any other kind of id.
211    #[must_use]
212    pub const fn hip3_parts(self) -> Option<(u32, u32)> {
213        if !matches!(self.kind(), AssetKind::Hip3Perp) {
214            return None;
215        }
216        let offset = self.0 - HIP3_ASSET_BASE;
217        match offset / HIP3_DEX_SPAN {
218            0 => None,
219            place => Some((place, offset % HIP3_DEX_SPAN)),
220        }
221    }
222
223    /// A perp by its dex's place in `perpDexs`: the main dex at 0, else HIP-3.
224    #[must_use]
225    pub const fn perp_on(dex: u32, index: u32) -> Option<Asset> {
226        match dex {
227            0 => Asset::perp(index),
228            dex => Asset::hip3(dex, index),
229        }
230    }
231
232    /// A HIP-4 outcome side: `100000000 + 10 * outcome + side`.
233    #[must_use]
234    pub const fn outcome(outcome: u32, side: OutcomeSide) -> Option<Asset> {
235        let Some(tens) = outcome.checked_mul(10) else {
236            return None;
237        };
238        match OUTCOME_ASSET_BASE.checked_add(tens + side.digit()) {
239            Some(id) => Some(Asset(id)),
240            None => None,
241        }
242    }
243
244    /// The outcome and side an outcome id names; `None` for any other kind.
245    #[must_use]
246    pub const fn outcome_side(self) -> Option<(u32, OutcomeSide)> {
247        if self.0 < OUTCOME_ASSET_BASE {
248            return None;
249        }
250        let encoding = self.0 - OUTCOME_ASSET_BASE;
251        let side = match encoding % 10 {
252            0 => OutcomeSide::Yes,
253            1 => OutcomeSide::No,
254            _ => return None,
255        };
256        Some((encoding / 10, side))
257    }
258}
259
260impl fmt::Display for Asset {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        write!(f, "{}", self.0)
263    }
264}
265
266/// An asset goes on the wire as its plain id.
267impl From<Asset> for Value {
268    fn from(asset: Asset) -> Value {
269        Value::Uint(u64::from(asset.0))
270    }
271}
272
273#[cfg(test)]
274#[path = "tests/asset.rs"]
275mod tests;