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