df_hyperliquid_core/client/
transport.rs1use 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
15pub trait Transport {
19 fn post(&self, path: &str, body: String) -> impl Future<Output = Result<String, TransportError>>;
20}
21
22pub 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 #[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 #[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 #[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 #[must_use]
89 pub fn header(&self, name: &str) -> Option<&str> {
90 find_header(&self.headers, name)
91 }
92
93 #[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 #[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 #[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 #[error("{0}")]
126 Refused(String),
127}
128
129#[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#[must_use]
142pub fn user_request(kind: &str, user: Address) -> String {
143 info_request(kind, &[("user", Json::String(user.to_hex()))])
144}
145
146pub 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
152pub 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#[derive(Debug, Clone, PartialEq, Eq)]
169pub enum ExchangeResponse {
170 Ok(Accepted),
172 Err(String),
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Accepted {
180 pub kind: String,
181 pub statuses: Vec<Status>,
183 pub data: Option<Value>,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq)]
190pub enum Status {
191 Ok(Value),
192 Error(String),
194}
195
196impl Accepted {
197 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;