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},
50 user::API_USER_2FA,
51 vault::{API_VAULT_MINT, API_VAULT_PENDING_REDEEMS, API_VAULT_REDEEM},
52};
53use serde::Serialize;
54use serde_json::Value;
55use std::{
56 borrow::Cow,
57 collections::BTreeMap,
58 time::{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_RFQ if method == Method::POST => "rfqSubmit",
257 API_RFQ_QUOTE if method == Method::POST => "quoteSubmit",
258 API_RFQ_ACCEPT if method == Method::POST => "quoteAccept",
259 API_RFQ_CANCEL if method == Method::POST => "rfqCancel",
260 API_RFQ_REFRESH if method == Method::POST => "rfqRefresh",
261 API_FUTURES_POSITION if method == Method::GET => "positionQuery",
262 API_BORROW_LEND_POSITIONS if method == Method::GET => "borrowLendPositionQuery",
263 API_COLLATERAL if method == Method::GET => "collateralQuery",
264 API_ACCOUNT if method == Method::GET => "accountQuery",
265 API_ACCOUNT_MAX_BORROW if method == Method::GET => "maxBorrowQuantity",
266 API_ACCOUNT_MAX_ORDER if method == Method::GET => "maxOrderQuantity",
267 API_ACCOUNT_MAX_WITHDRAWAL if method == Method::GET => "maxWithdrawalQuantity",
268 API_ACCOUNT if method == Method::PATCH => "accountUpdate",
269 API_ACCOUNT_CONVERT_DUST if method == Method::POST => "convertDust",
270 API_FILLS_HISTORY if method == Method::GET => "fillHistoryQueryAll",
271 API_VAULT_PENDING_REDEEMS if method == Method::GET => "vaultPendingRedeemsQuery",
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 _ => {
276 let req = self.client().request(method, url);
277 if let Some(payload) = payload {
278 return Ok(req.json(payload).build()?);
279 } else {
280 return Ok(req.build()?);
281 }
282 }
283 };
284
285 self.build_signed_request(url, method, instruction, payload)
286 }
287
288 pub fn build_signed_request<P: Serialize, U: IntoUrl>(
293 &self,
294 url: U,
295 method: Method,
296 instruction: &str,
297 payload: Option<&P>,
298 ) -> Result<Request> {
299 let url = url.into_url()?;
300
301 let signing_key = self.signing_key.as_ref().ok_or(Error::NotAuthenticated)?;
302
303 let query_params = url
304 .query_pairs()
305 .collect::<BTreeMap<Cow<'_, str>, Cow<'_, str>>>();
306
307 let mut signee = if let Some(payload) = payload {
308 let value = serde_json::to_value(payload)?;
309 build_signee_query_and_payload(instruction, value, &query_params)?
310 } else {
311 build_signee_query(instruction, &query_params)
312 };
313
314 let timestamp = now_millis();
315 signee.push_str(&format!("×tamp={timestamp}&window={DEFAULT_WINDOW}"));
316 tracing::debug!("signee: {}", signee);
317
318 let signature: Signature = signing_key.sign(signee.as_bytes());
319 let signature = Base64::encode_string(&signature.to_bytes());
320
321 let mut req = self.client().request(method, url);
322 if let Some(payload) = payload {
323 req = req.json(payload);
324 }
325 let mut req = req.build()?;
326 req.headers_mut()
327 .insert(SIGNATURE_HEADER, signature.parse()?);
328 req.headers_mut()
329 .insert(TIMESTAMP_HEADER, timestamp.to_string().parse()?);
330 req.headers_mut()
331 .insert(WINDOW_HEADER, DEFAULT_WINDOW.to_string().parse()?);
332 if matches!(req.method(), &Method::POST | &Method::DELETE) {
333 req.headers_mut()
334 .insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
335 }
336 Ok(req)
337 }
338}
339
340fn build_signee_query_and_payload(
341 instruction: &str,
342 payload: serde_json::Value,
343 query_params: &BTreeMap<Cow<'_, str>, Cow<'_, str>>,
344) -> Result<String> {
345 match payload {
346 Value::Object(map) => {
347 let body_params = map
348 .into_iter()
349 .map(|(k, v)| (k, v.to_string()))
350 .collect::<BTreeMap<_, _>>();
351 let mut signee = build_signee_query(instruction, query_params);
352 for (k, v) in body_params {
353 let v = v.trim_start_matches('"').trim_end_matches('"');
354 signee.push_str(&format!("&{k}={v}"));
355 }
356 Ok(signee)
357 }
358 Value::Array(array) => array
359 .into_iter()
360 .map(|item| build_signee_query_and_payload(instruction, item, query_params))
361 .collect::<Result<Vec<_>>>()
362 .map(|parts| parts.join("&")),
363 _ => Err(Error::InvalidRequest(
364 "payload must be a JSON object".into(),
365 )),
366 }
367}
368
369fn build_signee_query(
370 instruction: &str,
371 query_params: &BTreeMap<Cow<'_, str>, Cow<'_, str>>,
372) -> String {
373 let mut signee = format!("instruction={instruction}");
374 for (k, v) in query_params {
375 signee.push_str(&format!("&{k}={v}"));
376 }
377 signee
378}
379
380#[derive(Debug, Default)]
381pub struct BpxClientBuilder {
382 base_url: Option<String>,
383 ws_url: Option<String>,
384 secret: Option<String>,
385 headers: Option<BpxHeaders>,
386}
387
388impl BpxClientBuilder {
389 pub fn new() -> Self {
390 Default::default()
391 }
392
393 pub fn base_url(mut self, base_url: impl ToString) -> Self {
402 self.base_url = Some(base_url.to_string());
403 self
404 }
405
406 #[cfg(feature = "ws")]
415 pub fn ws_url(mut self, ws_url: impl ToString) -> Self {
416 self.ws_url = Some(ws_url.to_string());
417 self
418 }
419
420 pub fn secret(mut self, secret: impl ToString) -> Self {
429 self.secret = Some(secret.to_string());
430 self
431 }
432
433 pub fn headers(mut self, headers: BpxHeaders) -> Self {
442 self.headers = Some(headers);
443 self
444 }
445
446 pub fn build(self) -> Result<BpxClient> {
451 let base_url = self.base_url.as_deref().unwrap_or(BACKPACK_API_BASE_URL);
452 let base_url = Url::parse(base_url)?;
453
454 let ws_url = self.ws_url.as_deref().unwrap_or(BACKPACK_WS_URL);
455 let ws_url = Url::parse(ws_url)?;
456
457 let signing_key = if let Some(secret) = self.secret {
458 Some(
459 Base64::decode_vec(&secret)?
460 .try_into()
461 .map(|s| SigningKey::from_bytes(&s))
462 .map_err(|_| Error::SecretKey)?,
463 )
464 } else {
465 None
466 };
467 let verifying_key = signing_key.as_ref().map(|s| s.verifying_key());
468
469 let mut header_map = BpxHeaders::new();
470 if let Some(headers) = self.headers {
471 header_map.extend(headers);
472 }
473
474 header_map.insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
475 if let Some(signing_key) = &signing_key {
476 let verifier = signing_key.verifying_key();
477 header_map.insert(
478 API_KEY_HEADER,
479 Base64::encode_string(&verifier.to_bytes()).parse()?,
480 );
481 }
482
483 let client = BpxClient {
484 signing_key,
485 verifying_key,
486 base_url,
487 ws_url,
488 client: reqwest::Client::builder()
489 .user_agent(API_USER_AGENT)
490 .default_headers(header_map)
491 .build()?,
492 };
493
494 Ok(client)
495 }
496}
497
498fn now_millis() -> u64 {
500 SystemTime::now()
501 .duration_since(UNIX_EPOCH)
502 .expect("Time went backwards")
503 .as_millis() as u64
504}