Skip to main content

df_hyperliquid_core/live/subscription/
parse.rs

1//! Reading a subscription object back ([`Subscription::parse`]), in any key order, as the venue
2//! echoes it or as it was sent.
3
4use crate::live::{BadSubscription, Subscription};
5use crate::markets::Interval;
6use crate::utils::{Address, Json};
7
8/// Every `type`: the docs' list as it was, the SDK's, then the docs' newer ones.
9const KINDS: [&str; 30] = [
10    "allMids",
11    "notification",
12    "webData3",
13    "twapStates",
14    "clearinghouseState",
15    "openOrders",
16    "candle",
17    "l2Book",
18    "trades",
19    "orderUpdates",
20    "userEvents",
21    "userFills",
22    "userFundings",
23    "userNonFundingLedgerUpdates",
24    "activeAssetCtx",
25    "activeAssetData",
26    "userTwapSliceFills",
27    "userTwapHistory",
28    "bbo",
29    "spotState",
30    "allDexsClearinghouseState",
31    "allDexsAssetCtxs",
32    "outcomeMetaUpdates",
33    "fastAssetCtxs",
34    "assetCtxs",
35    "spotAssetCtxs",
36    "userHistoricalOrders",
37    "l2",
38    "pac",
39    "sac",
40];
41
42impl Subscription {
43    /// Reads a subscription object, in any key order, as the venue echoes it or as it was sent.
44    /// Keys it does not know are passed over; `null`, `false` and `""` read as left out.
45    pub fn parse(json: &Json) -> Result<Subscription, BadSubscription> {
46        if !matches!(json, Json::Object(_)) {
47            return Err(BadSubscription::NotAnObject);
48        }
49        let named = json.get("type").ok_or(BadSubscription::Missing { kind: "subscription", field: "type" })?;
50        let named = named.as_str().ok_or(BadSubscription::Wrong {
51            kind: "subscription",
52            field: "type",
53            expected: "a string",
54        })?;
55        let kind = KINDS
56            .into_iter()
57            .find(|kind| *kind == named)
58            .ok_or_else(|| BadSubscription::UnknownType(named.to_owned()))?;
59        let fields = Fields { json, kind };
60        Ok(match kind {
61            "allMids" => Subscription::AllMids { dex: fields.dex()? },
62            "notification" => Subscription::Notification { user: fields.user()? },
63            "webData3" => Subscription::WebData3 { user: fields.user()? },
64            "twapStates" => Subscription::TwapStates { user: fields.user()?, dex: fields.dex()? },
65            "clearinghouseState" => Subscription::ClearinghouseState { user: fields.user()?, dex: fields.dex()? },
66            "openOrders" => Subscription::OpenOrders { user: fields.user()?, dex: fields.dex()? },
67            "candle" => Subscription::Candle { coin: fields.coin()?, interval: fields.interval()? },
68            "l2Book" => Subscription::L2Book {
69                coin: fields.coin()?,
70                n_sig_figs: fields.small("nSigFigs")?,
71                mantissa: fields.small("mantissa")?,
72                fast: fields.flag("fast")?,
73            },
74            "trades" => Subscription::Trades { coin: fields.coin()? },
75            "orderUpdates" => Subscription::OrderUpdates { user: fields.user()? },
76            "userEvents" => Subscription::UserEvents { user: fields.user()? },
77            "userFills" => {
78                Subscription::UserFills { user: fields.user()?, aggregate_by_time: fields.flag("aggregateByTime")? }
79            }
80            "userFundings" => Subscription::UserFundings { user: fields.user()? },
81            "userNonFundingLedgerUpdates" => Subscription::UserNonFundingLedgerUpdates { user: fields.user()? },
82            "activeAssetCtx" => Subscription::ActiveAssetCtx { coin: fields.coin()? },
83            "activeAssetData" => Subscription::ActiveAssetData { user: fields.user()?, coin: fields.coin()? },
84            "userTwapSliceFills" => Subscription::UserTwapSliceFills { user: fields.user()? },
85            "userTwapHistory" => Subscription::UserTwapHistory { user: fields.user()? },
86            "bbo" => Subscription::Bbo { coin: fields.coin()? },
87            "spotState" => Subscription::SpotState {
88                user: fields.user()?,
89                ignore_portfolio_margin: fields.flag("ignorePortfolioMargin")?,
90            },
91            "allDexsClearinghouseState" => Subscription::AllDexsClearinghouseState { user: fields.user()? },
92            "allDexsAssetCtxs" => Subscription::AllDexsAssetCtxs,
93            "outcomeMetaUpdates" => Subscription::OutcomeMetaUpdates,
94            "fastAssetCtxs" => Subscription::FastAssetCtxs,
95            "assetCtxs" => Subscription::AssetCtxs { dex: fields.dex()? },
96            "spotAssetCtxs" => Subscription::SpotAssetCtxs,
97            "userHistoricalOrders" => Subscription::UserHistoricalOrders { user: fields.user()? },
98            "l2" => Subscription::L2 {
99                coin: fields.string("c")?.to_owned(),
100                n_sig_figs: fields.small("s")?,
101                mantissa: fields.small("m")?,
102            },
103            "pac" => Subscription::Pac,
104            "sac" => Subscription::Sac,
105            other => return Err(BadSubscription::UnknownType(other.to_owned())),
106        })
107    }
108}
109
110/// The fields of one subscription object, read for the `kind` it names.
111struct Fields<'a> {
112    json: &'a Json,
113    kind: &'static str,
114}
115
116impl Fields<'_> {
117    fn wrong(&self, field: &'static str, expected: &'static str) -> BadSubscription {
118        BadSubscription::Wrong { kind: self.kind, field, expected }
119    }
120
121    /// A field that is there and not `null`.
122    fn present(&self, field: &str) -> Option<&Json> {
123        self.json.get(field).filter(|value| !matches!(value, Json::Null))
124    }
125
126    fn string(&self, field: &'static str) -> Result<&str, BadSubscription> {
127        let value = self.present(field).ok_or(BadSubscription::Missing { kind: self.kind, field })?;
128        value.as_str().ok_or_else(|| self.wrong(field, "a string"))
129    }
130
131    fn user(&self) -> Result<Address, BadSubscription> {
132        self.string("user")?.parse().map_err(|_| self.wrong("user", "an address"))
133    }
134
135    fn coin(&self) -> Result<String, BadSubscription> {
136        self.string("coin").map(ToOwned::to_owned)
137    }
138
139    fn interval(&self) -> Result<Interval, BadSubscription> {
140        Interval::parse(self.string("interval")?).ok_or_else(|| self.wrong("interval", "an interval the docs list"))
141    }
142
143    fn dex(&self) -> Result<String, BadSubscription> {
144        match self.present("dex") {
145            None => Ok(String::new()),
146            Some(value) => value.as_str().map(ToOwned::to_owned).ok_or_else(|| self.wrong("dex", "a string")),
147        }
148    }
149
150    fn flag(&self, field: &'static str) -> Result<bool, BadSubscription> {
151        match self.present(field) {
152            None => Ok(false),
153            Some(value) => value.as_bool().ok_or_else(|| self.wrong(field, "true or false")),
154        }
155    }
156
157    fn small(&self, field: &'static str) -> Result<Option<u8>, BadSubscription> {
158        match self.present(field) {
159            None => Ok(None),
160            Some(value) => value
161                .as_u64()
162                .and_then(|number| u8::try_from(number).ok())
163                .map(Some)
164                .ok_or_else(|| self.wrong(field, "a small whole number")),
165        }
166    }
167}
168
169#[cfg(test)]
170#[path = "tests/parse.rs"]
171mod tests;