Skip to main content

df_hyperliquid_core/live/frame/
read.rs

1//! Reading one text frame ([`decode`]): its channel names the type its data reads into. A frame
2//! that does not read is a [`BadFrame`], naming the channel when it got that far.
3
4use std::{borrow::Cow, fmt};
5
6use crate::client::ExchangeResponse;
7use crate::live::{Ack, Answer, Frame, Method, Refusal, Reply};
8use crate::markets::context::{PerpCtx, SpotCtx};
9use crate::utils::Json;
10use serde::Deserialize;
11use serde_json::value::RawValue;
12
13/// A frame that did not read: the channel it named, when it got that far, and why.
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct BadFrame {
17    /// The channel the frame named; `None` when it did not get that far.
18    pub channel: Option<String>,
19    /// Why it did not read.
20    pub detail: String,
21}
22
23impl fmt::Display for BadFrame {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        match &self.channel {
26            Some(channel) => write!(f, "a `{channel}` frame did not read: {}", self.detail),
27            None => write!(f, "not a frame: {}", self.detail),
28        }
29    }
30}
31
32impl std::error::Error for BadFrame {}
33
34#[derive(Deserialize)]
35struct Head<'a> {
36    #[serde(borrow)]
37    channel: Cow<'a, str>,
38    #[serde(default, borrow)]
39    data: Option<&'a RawValue>,
40}
41
42#[derive(Deserialize)]
43struct RawAck<'a> {
44    method: Method,
45    #[serde(borrow)]
46    subscription: &'a RawValue,
47}
48
49#[derive(Deserialize)]
50struct RawReply<'a> {
51    id: u64,
52    #[serde(borrow)]
53    response: RawResponse<'a>,
54}
55
56#[derive(Deserialize)]
57struct RawResponse<'a> {
58    #[serde(rename = "type", borrow)]
59    kind: Cow<'a, str>,
60    #[serde(borrow)]
61    payload: &'a RawValue,
62}
63
64#[derive(Deserialize)]
65struct RawInfo<'a> {
66    #[serde(rename = "type")]
67    kind: String,
68    #[serde(default, borrow)]
69    data: Option<&'a RawValue>,
70}
71
72#[derive(Deserialize)]
73struct Active<C> {
74    coin: String,
75    ctx: C,
76}
77
78#[derive(Deserialize)]
79struct DexCtxs {
80    dex: String,
81    ctxs: Vec<PerpCtx>,
82}
83
84#[derive(Deserialize)]
85struct EveryDexCtxs {
86    ctxs: Vec<(String, Vec<PerpCtx>)>,
87}
88
89#[derive(Deserialize)]
90struct Note {
91    notification: String,
92}
93
94/// Reads one text frame.
95pub fn decode(text: &str) -> Result<Frame, BadFrame> {
96    let head: Head<'_> = serde_json::from_str(text)
97        .map_err(|error| BadFrame { channel: None, detail: format!("{error} in {}", shown(text)) })?;
98    let channel = head.channel.as_ref();
99    let data = head.data.map(RawValue::get);
100    let typed = Typed { channel, data };
101    Ok(match channel {
102        "pong" => Frame::Pong,
103        "subscriptionResponse" => {
104            let ack: RawAck<'_> = typed.read()?;
105            let echo = Json::parse(ack.subscription.get()).map_err(|error| typed.fail(error.to_string()))?;
106            Frame::Ack(Ack { method: ack.method, echo })
107        }
108        "error" => Frame::Error(Refusal { message: typed.read()? }),
109        "post" => Frame::Post(typed.reply()?),
110        "allMids" => Frame::AllMids(typed.read()?),
111        "l2Book" => Frame::Book(typed.read()?),
112        "trades" => Frame::Trades(typed.read()?),
113        "bbo" => Frame::Bbo(typed.read()?),
114        "candle" => Frame::Candle(typed.read()?),
115        "activeAssetCtx" => {
116            let active: Active<PerpCtx> = typed.read()?;
117            Frame::AssetCtx { coin: active.coin, ctx: active.ctx }
118        }
119        "activeSpotAssetCtx" => {
120            let active: Active<SpotCtx> = typed.read()?;
121            Frame::SpotAssetCtx { coin: active.coin, ctx: active.ctx }
122        }
123        "activeAssetData" => Frame::AssetData(typed.read()?),
124        "userFills" => Frame::UserFills(typed.read()?),
125        "orderUpdates" => Frame::OrderUpdates(typed.read()?),
126        "user" => Frame::UserEvent(typed.read()?),
127        "userFundings" => Frame::UserFundings(typed.read()?),
128        "userNonFundingLedgerUpdates" => Frame::Ledger(typed.read()?),
129        "clearinghouseState" => Frame::ClearinghouseState(typed.read()?),
130        "allDexsClearinghouseState" => Frame::AllDexsClearinghouseState(typed.read()?),
131        "openOrders" => Frame::OpenOrders(typed.read()?),
132        "spotState" => Frame::SpotState(typed.read()?),
133        "twapStates" => Frame::TwapStates(typed.read()?),
134        "userTwapSliceFills" => Frame::TwapSliceFills(typed.read()?),
135        "userTwapHistory" => Frame::TwapHistory(typed.read()?),
136        "notification" => Frame::Notification(typed.read::<Note>()?.notification),
137        "webData3" => Frame::WebData3(typed.read()?),
138        "allDexsAssetCtxs" => Frame::AllDexsAssetCtxs(typed.read::<EveryDexCtxs>()?.ctxs),
139        "assetCtxs" => {
140            let dex: DexCtxs = typed.read()?;
141            Frame::AssetCtxs { dex: dex.dex, ctxs: dex.ctxs }
142        }
143        "spotAssetCtxs" => Frame::SpotAssetCtxs(typed.read()?),
144        "outcomeMetaUpdates" => {
145            Frame::OutcomeMetaUpdates(Json::parse(typed.data()?).map_err(|error| typed.fail(error.to_string()))?)
146        }
147        "fastAssetCtxs" => Frame::FastAssetCtxs(typed.read()?),
148        "userHistoricalOrders" => Frame::HistoricalOrders(typed.read()?),
149        "l2" => Frame::L2(typed.read()?),
150        "pac" => Frame::Pac(typed.read()?),
151        "sac" => Frame::Sac(typed.read()?),
152        other => Frame::Other { channel: other.to_owned(), data: data.unwrap_or_default().to_owned() },
153    })
154}
155
156/// A frame's data, read for the channel that named it.
157struct Typed<'a> {
158    channel: &'a str,
159    data: Option<&'a str>,
160}
161
162impl<'a> Typed<'a> {
163    fn fail(&self, detail: String) -> BadFrame {
164        BadFrame { channel: Some(self.channel.to_owned()), detail }
165    }
166
167    fn data(&self) -> Result<&'a str, BadFrame> {
168        self.data.ok_or_else(|| self.fail("no data".to_owned()))
169    }
170
171    fn read<T: Deserialize<'a>>(&self) -> Result<T, BadFrame> {
172        let data = self.data()?;
173        serde_json::from_str(data).map_err(|error| self.fail(format!("{error} in {}", shown(data))))
174    }
175
176    fn reply(&self) -> Result<Reply, BadFrame> {
177        let data = self.data()?;
178        let reply: RawReply<'_> =
179            serde_json::from_str(data).map_err(|error| self.fail(format!("{error} in {}", shown(data))))?;
180        let payload = reply.response.payload.get();
181        let answer = match reply.response.kind.as_ref() {
182            "info" => {
183                let info: RawInfo<'_> = serde_json::from_str(payload).map_err(|error| self.fail(error.to_string()))?;
184                Answer::Info { kind: info.kind, data: info.data.map_or("null", RawValue::get).to_owned() }
185            }
186            "action" => Answer::Action(ExchangeResponse::parse(payload).map_err(|error| self.fail(error.to_string()))?),
187            "error" => Answer::Error(serde_json::from_str(payload).map_err(|error| self.fail(error.to_string()))?),
188            other => return Err(self.fail(format!("a post answered as `{other}`"))),
189        };
190        Ok(Reply { id: reply.id, answer })
191    }
192}
193
194/// The start of a text, for an error message.
195fn shown(text: &str) -> String {
196    let start: String = text.chars().take(160).collect();
197    match start.len() < text.len() {
198        true => format!("{start}..."),
199        false => start,
200    }
201}
202
203#[cfg(test)]
204#[path = "tests/read.rs"]
205mod tests;