1use base64ct::{Base64, Encoding};
37use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
38use reqwest::{IntoUrl, Method, Request, Response, StatusCode, Url, header::CONTENT_TYPE};
39use routes::{
40 account::{
41 API_ACCOUNT, API_ACCOUNT_CONVERT_DUST, API_ACCOUNT_MAX_BORROW, API_ACCOUNT_MAX_ORDER,
42 API_ACCOUNT_MAX_WITHDRAWAL,
43 },
44 borrow_lend::API_BORROW_LEND_POSITIONS,
45 capital::{API_CAPITAL, API_COLLATERAL, API_DEPOSIT_ADDRESS, API_DEPOSITS, API_WITHDRAWALS},
46 futures::API_FUTURES_POSITION,
47 history::API_FILLS_HISTORY,
48 order::{API_ORDER, API_ORDERS},
49 rfq::{API_RFQ, API_RFQ_QUOTE, API_RFQS},
50 user::API_USER_2FA,
51 vault::{API_VAULT_MINT, API_VAULT_MINTS_HISTORY, API_VAULT_REDEEM, API_VAULT_REDEEMS_HISTORY},
52};
53use serde::Serialize;
54use serde_json::Value;
55use std::{
56 borrow::Cow,
57 collections::BTreeMap,
58 time::{Duration, SystemTime, UNIX_EPOCH},
59};
60
61pub mod error;
62
63mod routes;
64
65#[cfg(feature = "ws")]
66mod ws;
67
68pub use bpx_api_types as types;
70
71pub use error::{Error, Result};
73
74use crate::routes::rfq::{API_RFQ_ACCEPT, API_RFQ_CANCEL, API_RFQ_REFRESH};
75
76const API_USER_AGENT: &str = "bpx-rust-client";
77const API_KEY_HEADER: &str = "X-API-Key";
78
79const DEFAULT_WINDOW: u32 = 5000;
80
81const SIGNATURE_HEADER: &str = "X-Signature";
82const TIMESTAMP_HEADER: &str = "X-Timestamp";
83const WINDOW_HEADER: &str = "X-Window";
84
85const JSON_CONTENT: &str = "application/json; charset=utf-8";
86
87pub const BACKPACK_API_BASE_URL: &str = "https://api.backpack.exchange";
89
90pub const BACKPACK_WS_URL: &str = "wss://ws.backpack.exchange";
92
93pub type BpxHeaders = reqwest::header::HeaderMap;
95
96#[derive(Debug, Clone)]
98pub struct BpxClient {
99 signing_key: Option<SigningKey>,
100 verifying_key: Option<VerifyingKey>,
101 base_url: Url,
102 #[cfg_attr(not(feature = "ws"), allow(dead_code))]
103 ws_url: Url,
104 client: reqwest::Client,
105}
106
107impl std::ops::Deref for BpxClient {
108 type Target = reqwest::Client;
109
110 fn deref(&self) -> &Self::Target {
111 &self.client
112 }
113}
114
115impl std::ops::DerefMut for BpxClient {
116 fn deref_mut(&mut self) -> &mut Self::Target {
117 &mut self.client
118 }
119}
120
121impl AsRef<reqwest::Client> for BpxClient {
122 fn as_ref(&self) -> &reqwest::Client {
123 &self.client
124 }
125}
126
127impl BpxClient {
129 pub fn builder() -> BpxClientBuilder {
130 BpxClientBuilder::new()
131 }
132
133 pub fn init(base_url: String, secret: &str, headers: Option<BpxHeaders>) -> Result<Self> {
138 BpxClientBuilder::new()
139 .base_url(base_url)
140 .secret(secret)
141 .headers(headers.unwrap_or_default())
142 .build()
143 }
144
145 #[cfg(feature = "ws")]
147 #[deprecated(
148 note = "Use BpxClient::builder() instead to configure the client with a custom websocket URL."
149 )]
150 pub fn init_with_ws(
151 base_url: String,
152 ws_url: String,
153 secret: &str,
154 headers: Option<BpxHeaders>,
155 ) -> Result<Self> {
156 BpxClientBuilder::new()
157 .base_url(base_url)
158 .ws_url(ws_url)
159 .secret(secret)
160 .headers(headers.unwrap_or_default())
161 .build()
162 }
163
164 async fn process_response(res: Response) -> Result<Response> {
169 if let Err(e) = res.error_for_status_ref() {
170 let err_text = res.text().await?;
171 let err = Error::BpxApiError {
172 status_code: e.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
173 message: err_text.into(),
174 };
175 return Err(err);
176 }
177 Ok(res)
178 }
179
180 pub async fn get<U: IntoUrl>(&self, url: U) -> Result<Response> {
182 let req = self.build_and_maybe_sign_request::<(), _>(url, Method::GET, None)?;
183 tracing::debug!(?req, "GET request");
184 self.execute(req).await
185 }
186
187 pub async fn post<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
189 let req = self.build_and_maybe_sign_request(url, Method::POST, Some(&payload))?;
190 tracing::debug!(?req, "POST request");
191 self.execute(req).await
192 }
193
194 pub async fn delete<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
196 let req = self.build_and_maybe_sign_request(url, Method::DELETE, Some(&payload))?;
197 tracing::debug!(?req, "DELETE request");
198 self.execute(req).await
199 }
200
201 pub async fn patch<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
203 let req = self.build_and_maybe_sign_request(url, Method::PATCH, Some(&payload))?;
204 tracing::debug!(?req, "PATCH request");
205 self.execute(req).await
206 }
207
208 pub async fn execute(&self, request: Request) -> Result<Response> {
209 let res = self.client.execute(request).await?;
210 Self::process_response(res).await
211 }
212
213 pub const fn verifying_key(&self) -> Option<&VerifyingKey> {
216 self.verifying_key.as_ref()
217 }
218
219 pub const fn client(&self) -> &reqwest::Client {
221 &self.client
222 }
223
224 pub fn base_url(&self) -> &Url {
225 &self.base_url
226 }
227}
228
229impl BpxClient {
231 fn build_and_maybe_sign_request<P: Serialize, U: IntoUrl>(
237 &self,
238 url: U,
239 method: Method,
240 payload: Option<&P>,
241 ) -> Result<Request> {
242 let url = url.into_url()?;
243 let instruction = match url.path() {
244 API_CAPITAL if method == Method::GET => "balanceQuery",
245 API_DEPOSITS if method == Method::GET => "depositQueryAll",
246 API_DEPOSIT_ADDRESS if method == Method::GET => "depositAddressQuery",
247 API_WITHDRAWALS if method == Method::GET => "withdrawalQueryAll",
248 API_WITHDRAWALS if method == Method::POST => "withdraw",
249 API_USER_2FA if method == Method::POST => "issueTwoFactorToken",
250 API_ORDER if method == Method::GET => "orderQuery",
251 API_ORDER if method == Method::POST => "orderExecute",
252 API_ORDER if method == Method::DELETE => "orderCancel",
253 API_ORDERS if method == Method::GET => "orderQueryAll",
254 API_ORDERS if method == Method::POST => "orderExecute",
255 API_ORDERS if method == Method::DELETE => "orderCancelAll",
256 API_RFQS if method == Method::GET => "rfqQuery",
257 API_RFQ if method == Method::POST => "rfqSubmit",
258 API_RFQ_QUOTE if method == Method::POST => "quoteSubmit",
259 API_RFQ_ACCEPT if method == Method::POST => "quoteAccept",
260 API_RFQ_CANCEL if method == Method::POST => "rfqCancel",
261 API_RFQ_REFRESH if method == Method::POST => "rfqRefresh",
262 API_FUTURES_POSITION if method == Method::GET => "positionQuery",
263 API_BORROW_LEND_POSITIONS if method == Method::GET => "borrowLendPositionQuery",
264 API_COLLATERAL if method == Method::GET => "collateralQuery",
265 API_ACCOUNT if method == Method::GET => "accountQuery",
266 API_ACCOUNT_MAX_BORROW if method == Method::GET => "maxBorrowQuantity",
267 API_ACCOUNT_MAX_ORDER if method == Method::GET => "maxOrderQuantity",
268 API_ACCOUNT_MAX_WITHDRAWAL if method == Method::GET => "maxWithdrawalQuantity",
269 API_ACCOUNT if method == Method::PATCH => "accountUpdate",
270 API_ACCOUNT_CONVERT_DUST if method == Method::POST => "convertDust",
271 API_FILLS_HISTORY if method == Method::GET => "fillHistoryQueryAll",
272 API_VAULT_MINT if method == Method::POST => "vaultMint",
273 API_VAULT_REDEEM if method == Method::POST => "vaultRedeemRequest",
274 API_VAULT_REDEEM if method == Method::DELETE => "vaultRedeemCancel",
275 API_VAULT_MINTS_HISTORY if method == Method::GET => "vaultMintHistoryQueryAll",
276 API_VAULT_REDEEMS_HISTORY if method == Method::GET => "vaultRedeemHistoryQueryAll",
277 _ => {
278 let req = self.client().request(method, url);
279 if let Some(payload) = payload {
280 return Ok(req.json(payload).build()?);
281 } else {
282 return Ok(req.build()?);
283 }
284 }
285 };
286
287 self.build_signed_request(url, method, instruction, payload)
288 }
289
290 pub fn build_signed_request<P: Serialize, U: IntoUrl>(
295 &self,
296 url: U,
297 method: Method,
298 instruction: &str,
299 payload: Option<&P>,
300 ) -> Result<Request> {
301 let url = url.into_url()?;
302
303 let signing_key = self.signing_key.as_ref().ok_or(Error::NotAuthenticated)?;
304
305 let query_params = url
306 .query_pairs()
307 .collect::<BTreeMap<Cow<'_, str>, Cow<'_, str>>>();
308
309 let mut signee = if let Some(payload) = payload {
310 let value = serde_json::to_value(payload)?;
311 build_signee_query_and_payload(instruction, value, &query_params)?
312 } else {
313 build_signee_query(instruction, &query_params)
314 };
315
316 let timestamp = now_millis();
317 signee.push_str(&format!("×tamp={timestamp}&window={DEFAULT_WINDOW}"));
318 tracing::debug!("signee: {}", signee);
319
320 let signature: Signature = signing_key.sign(signee.as_bytes());
321 let signature = Base64::encode_string(&signature.to_bytes());
322
323 let mut req = self.client().request(method, url);
324 if let Some(payload) = payload {
325 req = req.json(payload);
326 }
327 let mut req = req.build()?;
328 req.headers_mut()
329 .insert(SIGNATURE_HEADER, signature.parse()?);
330 req.headers_mut()
331 .insert(TIMESTAMP_HEADER, timestamp.to_string().parse()?);
332 req.headers_mut()
333 .insert(WINDOW_HEADER, DEFAULT_WINDOW.to_string().parse()?);
334 if matches!(req.method(), &Method::POST | &Method::DELETE) {
335 req.headers_mut()
336 .insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
337 }
338 Ok(req)
339 }
340}
341
342fn build_signee_query_and_payload(
343 instruction: &str,
344 payload: serde_json::Value,
345 query_params: &BTreeMap<Cow<'_, str>, Cow<'_, str>>,
346) -> Result<String> {
347 match payload {
348 Value::Object(map) => {
349 let body_params = map
350 .into_iter()
351 .map(|(k, v)| (k, v.to_string()))
352 .collect::<BTreeMap<_, _>>();
353 let mut signee = build_signee_query(instruction, query_params);
354 for (k, v) in body_params {
355 let v = v.trim_start_matches('"').trim_end_matches('"');
356 signee.push_str(&format!("&{k}={v}"));
357 }
358 Ok(signee)
359 }
360 Value::Array(array) => array
361 .into_iter()
362 .map(|item| build_signee_query_and_payload(instruction, item, query_params))
363 .collect::<Result<Vec<_>>>()
364 .map(|parts| parts.join("&")),
365 _ => Err(Error::InvalidRequest(
366 "payload must be a JSON object".into(),
367 )),
368 }
369}
370
371fn build_signee_query(
372 instruction: &str,
373 query_params: &BTreeMap<Cow<'_, str>, Cow<'_, str>>,
374) -> String {
375 let mut signee = format!("instruction={instruction}");
376 for (k, v) in query_params {
377 signee.push_str(&format!("&{k}={v}"));
378 }
379 signee
380}
381
382#[derive(Debug, Default)]
383pub struct BpxClientBuilder {
384 base_url: Option<String>,
385 ws_url: Option<String>,
386 secret: Option<String>,
387 headers: Option<BpxHeaders>,
388 timeout: Option<u64>,
389}
390
391impl BpxClientBuilder {
392 pub fn new() -> Self {
393 Default::default()
394 }
395
396 pub fn base_url(mut self, base_url: impl ToString) -> Self {
405 self.base_url = Some(base_url.to_string());
406 self
407 }
408
409 #[cfg(feature = "ws")]
418 pub fn ws_url(mut self, ws_url: impl ToString) -> Self {
419 self.ws_url = Some(ws_url.to_string());
420 self
421 }
422
423 pub fn secret(mut self, secret: impl ToString) -> Self {
432 self.secret = Some(secret.to_string());
433 self
434 }
435
436 pub fn headers(mut self, headers: BpxHeaders) -> Self {
445 self.headers = Some(headers);
446 self
447 }
448
449 pub fn timeout(mut self, timeout: u64) -> Self {
458 self.timeout = Some(timeout);
459 self
460 }
461
462 pub fn build(self) -> Result<BpxClient> {
467 let base_url = self.base_url.as_deref().unwrap_or(BACKPACK_API_BASE_URL);
468 let base_url = Url::parse(base_url)?;
469
470 let ws_url = self.ws_url.as_deref().unwrap_or(BACKPACK_WS_URL);
471 let ws_url = Url::parse(ws_url)?;
472
473 let signing_key = if let Some(secret) = self.secret {
474 Some(
475 Base64::decode_vec(&secret)?
476 .try_into()
477 .map(|s| SigningKey::from_bytes(&s))
478 .map_err(|_| Error::SecretKey)?,
479 )
480 } else {
481 None
482 };
483 let verifying_key = signing_key.as_ref().map(|s| s.verifying_key());
484
485 let mut header_map = BpxHeaders::new();
486 if let Some(headers) = self.headers {
487 header_map.extend(headers);
488 }
489
490 header_map.insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
491 if let Some(signing_key) = &signing_key {
492 let verifier = signing_key.verifying_key();
493 header_map.insert(
494 API_KEY_HEADER,
495 Base64::encode_string(&verifier.to_bytes()).parse()?,
496 );
497 }
498
499 let client = BpxClient {
500 signing_key,
501 verifying_key,
502 base_url,
503 ws_url,
504 client: reqwest::Client::builder()
505 .user_agent(API_USER_AGENT)
506 .default_headers(header_map)
507 .timeout(Duration::from_secs(self.timeout.unwrap_or(30)))
508 .build()?,
509 };
510
511 Ok(client)
512 }
513}
514
515fn now_millis() -> u64 {
517 SystemTime::now()
518 .duration_since(UNIX_EPOCH)
519 .expect("Time went backwards")
520 .as_millis() as u64
521}