Skip to main content

df_hyperliquid_core/markets/
dex.rs

1//! Which perp dex a read or a coin is about: a request without `dex` is the main dex's, one with
2//! `"dex":"xyz"` that HIP-3 dex's ([`Dex::field`]). A HIP-3 coin is `dex:SYMBOL`; its asset id is
3//! [`Asset::hip3`](crate::utils::asset::Asset::hip3).
4
5use crate::utils::Json;
6
7/// A perp dex: the main one, or a HIP-3 dex by name.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
9pub enum Dex<'a> {
10    /// The main dex, the first in `perpDexs`.
11    #[default]
12    Main,
13    /// A HIP-3 dex by its name: `xyz`, the `xyz:` of its coins.
14    Hip3(&'a str),
15}
16
17impl<'a> Dex<'a> {
18    /// The dex a coin trades on: `xyz:TSLA` on `xyz`, `BTC` on the main dex.
19    #[must_use]
20    pub fn of_coin(coin: &'a str) -> Dex<'a> {
21        match coin.split_once(':') {
22            Some((dex, _)) => Dex::Hip3(dex),
23            None => Dex::Main,
24        }
25    }
26
27    /// The `dex` a request names; `None` for the main dex.
28    #[must_use]
29    pub const fn name(self) -> Option<&'a str> {
30        match self {
31            Dex::Main => None,
32            Dex::Hip3(name) => Some(name),
33        }
34    }
35
36    /// The `dex` field of a request body; `None` for the main dex, which a request leaves unnamed.
37    #[must_use]
38    pub fn field(self) -> Option<(&'static str, Json)> {
39        self.name().map(|name| ("dex", Json::String(name.to_owned())))
40    }
41}
42
43/// `xyz:TSLA` as `("xyz", "TSLA")`. `None` for a main-dex coin or an empty part.
44#[must_use]
45pub fn split_coin(coin: &str) -> Option<(&str, &str)> {
46    let (dex, symbol) = coin.split_once(':')?;
47    (!dex.is_empty() && !symbol.is_empty()).then_some((dex, symbol))
48}
49
50/// `xyz` and `TSLA` as `xyz:TSLA`.
51#[must_use]
52pub fn coin(dex: &str, symbol: &str) -> String {
53    format!("{dex}:{symbol}")
54}
55
56#[cfg(test)]
57#[path = "tests/dex.rs"]
58mod tests;