Skip to main content

df_hyperliquid_core/client/
transport.rs

1//! The [`Transport`] and [`Http`] traits, and the `/info` and `/exchange`
2//! calls every read and action goes through.
3
4use std::future::Future;
5
6use serde::de::DeserializeOwned;
7use serde_json::Value;
8
9use crate::utils::address::Address;
10use crate::utils::json::Json;
11
12pub const INFO: &str = "/info";
13pub const EXCHANGE: &str = "/exchange";
14
15/// Posts a JSON body to `path` (`/info` or `/exchange`) on one network and
16/// returns the answer's text. [`crate::client::Api`] implements it with the
17/// rate limit. No `Send` bound, since the browser is single-threaded.
18pub trait Transport {
19    fn post(&self, path: &str, body: String) -> impl Future<Output = Result<String, TransportError>>;
20}
21
22/// One HTTP request out and its answer back, whatever the status. It knows
23/// nothing of networks or limits; an error means no answer at all
24/// ([`TransportError::Unreachable`]).
25pub trait Http {
26    fn send(&self, request: Request) -> impl Future<Output = Result<Response, TransportError>>;
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum Method {
31    Get,
32    Post,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Request {
37    pub method: Method,
38    pub url: String,
39    pub headers: Vec<(String, String)>,
40    pub body: Vec<u8>,
41}
42
43impl Request {
44    #[must_use]
45    pub fn get(url: impl Into<String>) -> Self {
46        Request { method: Method::Get, url: url.into(), headers: Vec::new(), body: Vec::new() }
47    }
48
49    /// A JSON body, posted as `application/json`.
50    #[must_use]
51    pub fn post_json(url: impl Into<String>, body: String) -> Self {
52        Request {
53            method: Method::Post,
54            url: url.into(),
55            headers: vec![("Content-Type".to_owned(), "application/json".to_owned())],
56            body: body.into_bytes(),
57        }
58    }
59
60    /// The same request with one more header.
61    #[must_use]
62    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
63        self.headers.push((name.into(), value.into()));
64        self
65    }
66
67    /// A header's value, its name matched whatever its case.
68    #[must_use]
69    pub fn header(&self, name: &str) -> Option<&str> {
70        find_header(&self.headers, name)
71    }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct Response {
76    pub status: u16,
77    pub headers: Vec<(String, String)>,
78    pub body: Vec<u8>,
79}
80
81impl Response {
82    #[must_use]
83    pub const fn is_success(&self) -> bool {
84        self.status >= 200 && self.status < 300
85    }
86
87    /// A header's value, its name matched whatever its case.
88    #[must_use]
89    pub fn header(&self, name: &str) -> Option<&str> {
90        find_header(&self.headers, name)
91    }
92
93    /// The body as text; bytes that are not UTF-8 read as U+FFFD.
94    #[must_use]
95    pub fn text(&self) -> String {
96        String::from_utf8_lossy(&self.body).into_owned()
97    }
98}
99
100fn find_header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
101    headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value.as_str())
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
105pub enum TransportError {
106    /// No answer came back. For `/exchange` that means unknown, not failed:
107    /// the action may have landed, so it is never sent again.
108    #[error("no answer from the venue: {0}")]
109    Unreachable(String),
110    #[error("the venue answered HTTP {status}: {body}")]
111    Status { status: u16, body: String },
112    /// Refused for the rate limit, by the venue (a 429) or by [`crate::client::Api`]'s
113    /// gate before it went out. Nothing was done; try again after the wait.
114    #[error("rate limited; try again in {} ms", retry_after_ms.unwrap_or(0))]
115    RateLimited { retry_after_ms: Option<u64> },
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
119pub enum ApiError {
120    #[error(transparent)]
121    Transport(#[from] TransportError),
122    #[error("the venue's answer on {path} could not be read: {detail}")]
123    Unreadable { path: &'static str, detail: String },
124    /// `{"status":"err"}`: the venue's own words, shown as they came.
125    #[error("{0}")]
126    Refused(String),
127}
128
129/// `{"type":<kind>, ..fields}`, the body of every `/info` read: `type` first,
130/// then each field in the order given, so a request matches a recorded one
131/// byte for byte.
132#[must_use]
133pub fn info_request(kind: &str, fields: &[(&str, Json)]) -> String {
134    let mut object = Vec::with_capacity(fields.len() + 1);
135    object.push(("type".to_owned(), Json::String(kind.to_owned())));
136    object.extend(fields.iter().map(|(key, value)| ((*key).to_owned(), value.clone())));
137    Json::Object(object).compact()
138}
139
140/// `{"type":<kind>,"user":<user>}`, the shape of most account reads.
141#[must_use]
142pub fn user_request(kind: &str, user: Address) -> String {
143    info_request(kind, &[("user", Json::String(user.to_hex()))])
144}
145
146/// One read from `/info`, not retried; the caller decides.
147pub async fn info<R: DeserializeOwned>(transport: &impl Transport, request: String) -> Result<R, ApiError> {
148    let text = transport.post(INFO, request).await?;
149    serde_json::from_str(&text).map_err(|error| ApiError::Unreadable { path: INFO, detail: unreadable(&error, &text) })
150}
151
152/// Posts a signed body to `/exchange`, once. Never retried, here or by a
153/// caller: a second post of a timed-out action could move the money twice.
154pub async fn exchange(transport: &impl Transport, body: String) -> Result<Accepted, ApiError> {
155    let text = transport.post(EXCHANGE, body).await?;
156    match ExchangeResponse::parse(&text)? {
157        ExchangeResponse::Ok(accepted) => Ok(accepted),
158        ExchangeResponse::Err(reason) => Err(ApiError::Refused(reason)),
159    }
160}
161
162fn unreadable(error: &serde_json::Error, text: &str) -> String {
163    let shown: String = text.chars().take(300).collect();
164    format!("{error} in {shown}")
165}
166
167/// What `/exchange` answers.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub enum ExchangeResponse {
170    /// `{"status":"ok","response":{...}}`.
171    Ok(Accepted),
172    /// `{"status":"err","response":"message"}`.
173    Err(String),
174}
175
176/// An accepted action. `kind` is `response.type`: `"default"` for a transfer,
177/// `"order"` and the like for actions that answer per item.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Accepted {
180    pub kind: String,
181    /// `response.data.statuses`, or `response.data.status` alone, when present.
182    pub statuses: Vec<Status>,
183    /// `response.data` whole, as the venue wrote it; `None` when there is none
184    /// (`"default"`). Some answers carry more than their statuses.
185    pub data: Option<Value>,
186}
187
188/// One item of an accepted answer.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub enum Status {
191    Ok(Value),
192    /// `{"error": "..."}`: that item was refused though the action was taken.
193    Error(String),
194}
195
196impl Accepted {
197    /// The items the venue refused inside an `ok`.
198    pub fn errors(&self) -> impl Iterator<Item = &str> {
199        self.statuses.iter().filter_map(|status| match status {
200            Status::Error(reason) => Some(reason.as_str()),
201            Status::Ok(_) => None,
202        })
203    }
204}
205
206impl ExchangeResponse {
207    pub fn parse(text: &str) -> Result<ExchangeResponse, ApiError> {
208        let bad = |detail: String| ApiError::Unreadable { path: EXCHANGE, detail };
209        let answer: Value = serde_json::from_str(text).map_err(|error| bad(unreadable(&error, text)))?;
210        let response = answer.get("response").cloned().unwrap_or(Value::Null);
211        match answer.get("status").and_then(Value::as_str) {
212            Some("ok") => {
213                let kind = response.get("type").and_then(Value::as_str).unwrap_or_default().to_owned();
214                let data = response.get("data");
215                let statuses = match (
216                    data.and_then(|data| data.get("statuses")).and_then(Value::as_array),
217                    data.and_then(|data| data.get("status")),
218                ) {
219                    (Some(many), _) => many.iter().map(status_of).collect(),
220                    (None, Some(one)) => vec![status_of(one)],
221                    (None, None) => Vec::new(),
222                };
223                Ok(ExchangeResponse::Ok(Accepted { kind, statuses, data: data.cloned() }))
224            }
225            Some(_) => Ok(ExchangeResponse::Err(text_of(&response))),
226            None => Err(bad(format!("no status in {}", text.chars().take(300).collect::<String>()))),
227        }
228    }
229}
230
231fn status_of(status: &Value) -> Status {
232    match status.get("error") {
233        Some(error) => Status::Error(text_of(error)),
234        None => Status::Ok(status.clone()),
235    }
236}
237
238fn text_of(value: &Value) -> String {
239    value.as_str().map_or_else(|| value.to_string(), ToOwned::to_owned)
240}
241
242#[cfg(test)]
243#[path = "tests/transport.rs"]
244mod tests;