Skip to main content

bpx_api_client/
lib.rs

1//! Backpack Exchange API Client
2//!
3//! This module provides the `BpxClient` for interacting with the Backpack Exchange API.
4//! It includes functionality for authenticated and public endpoints,
5//! along with utilities for error handling, request signing, and response processing.
6//!
7//! ## Features
8//! - Request signing and authentication using ED25519 signatures.
9//! - Supports both REST and WebSocket endpoints.
10//! - Includes modules for managing capital, orders, trades, and user data.
11//!
12//! ## Example
13//! ```no_run
14//! # // We depend on tokio only when the `ws` feature is enabled.
15//! # #[cfg(feature = "ws")]
16//! # {
17//! use bpx_api_client::{BACKPACK_API_BASE_URL, BpxClient};
18//!
19//! #[tokio::main]
20//! async fn main() {
21//!     let base_url = BACKPACK_API_BASE_URL.to_string();
22//!     let secret = "your_api_secret_here";
23//!     let headers = None;
24//!
25//!     let client = BpxClient::init(base_url, secret, headers)
26//!         .expect("Failed to initialize Backpack API client");
27//!
28//!     match client.get_open_orders(Some("SOL_USDC")).await {
29//!         Ok(orders) => println!("Open Orders: {:?}", orders),
30//!         Err(err) => tracing::error!("Error: {:?}", err),
31//!     }
32//! }
33//! # }
34//! ```
35
36use 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_PENDING_REDEEMS,
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
68/// Re-export of the Backpack Exchange API types.
69pub use bpx_api_types as types;
70
71/// Re-export of the custom `Error` type and `Result` alias for error handling.
72pub 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
87/// The official base URL for the Backpack Exchange REST API.
88pub const BACKPACK_API_BASE_URL: &str = "https://api.backpack.exchange";
89
90/// The official WebSocket URL for real-time data from the Backpack Exchange.
91pub const BACKPACK_WS_URL: &str = "wss://ws.backpack.exchange";
92
93/// Type alias for custom HTTP headers passed to `BpxClient` during initialization.
94pub type BpxHeaders = reqwest::header::HeaderMap;
95
96/// A client for interacting with the Backpack Exchange API.
97#[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
127// Public functions.
128impl BpxClient {
129    pub fn builder() -> BpxClientBuilder {
130        BpxClientBuilder::new()
131    }
132
133    /// Initializes a new client with the given base URL, API secret, and optional headers.
134    ///
135    /// This sets up the signing and verification keys, and creates a `reqwest` client
136    /// with default headers including the API key and content type.
137    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    /// Initializes a new client with WebSocket support.
146    #[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    /// Processes the response to check for HTTP errors and extracts
165    /// the response content.
166    ///
167    /// Returns a custom error if the status code is non-2xx.
168    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    /// Sends a GET request to the specified URL and signs it before execution.
181    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        let res = self.client.execute(req).await?;
185        Self::process_response(res).await
186    }
187
188    /// Sends a POST request with a JSON payload to the specified URL and signs it.
189    pub async fn post<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
190        let req = self.build_and_maybe_sign_request(url, Method::POST, Some(&payload))?;
191        tracing::debug!(?req, "POST request");
192        let res = self.client.execute(req).await?;
193        Self::process_response(res).await
194    }
195
196    /// Sends a DELETE request with a JSON payload to the specified URL and signs it.
197    pub async fn delete<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
198        let req = self.build_and_maybe_sign_request(url, Method::DELETE, Some(&payload))?;
199        tracing::debug!(?req, "DELETE request");
200        let res = self.client.execute(req).await?;
201        Self::process_response(res).await
202    }
203
204    /// Sends a PATCH request with a JSON payload to the specified URL and signs it.
205    pub async fn patch<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
206        let req = self.build_and_maybe_sign_request(url, Method::PATCH, Some(&payload))?;
207        tracing::debug!(?req, "PATCH request");
208        let res = self.client.execute(req).await?;
209        Self::process_response(res).await
210    }
211
212    /// Returns a reference to the [`VerifyingKey`] used for request verification.
213    /// Return will be [`Some`] if the client was initialised with a secret key, otherwise [`None`].
214    pub const fn verifying_key(&self) -> Option<&VerifyingKey> {
215        self.verifying_key.as_ref()
216    }
217
218    /// Returns a reference to the underlying HTTP client.
219    pub const fn client(&self) -> &reqwest::Client {
220        &self.client
221    }
222}
223
224// Private functions.
225impl BpxClient {
226    /// Signs a request by generating a signature from the request details
227    /// and appending necessary headers for authentication.
228    ///
229    /// # Arguments
230    /// * `req` - The mutable reference to the request to be signed.
231    fn build_and_maybe_sign_request<P: Serialize, U: IntoUrl>(
232        &self,
233        url: U,
234        method: Method,
235        payload: Option<&P>,
236    ) -> Result<Request> {
237        let url = url.into_url()?;
238        let instruction = match url.path() {
239            API_CAPITAL if method == Method::GET => "balanceQuery",
240            API_DEPOSITS if method == Method::GET => "depositQueryAll",
241            API_DEPOSIT_ADDRESS if method == Method::GET => "depositAddressQuery",
242            API_WITHDRAWALS if method == Method::GET => "withdrawalQueryAll",
243            API_WITHDRAWALS if method == Method::POST => "withdraw",
244            API_USER_2FA if method == Method::POST => "issueTwoFactorToken",
245            API_ORDER if method == Method::GET => "orderQuery",
246            API_ORDER if method == Method::POST => "orderExecute",
247            API_ORDER if method == Method::DELETE => "orderCancel",
248            API_ORDERS if method == Method::GET => "orderQueryAll",
249            API_ORDERS if method == Method::POST => "orderExecute",
250            API_ORDERS if method == Method::DELETE => "orderCancelAll",
251            API_RFQ if method == Method::POST => "rfqSubmit",
252            API_RFQ_QUOTE if method == Method::POST => "quoteSubmit",
253            API_RFQ_ACCEPT if method == Method::POST => "quoteAccept",
254            API_RFQ_CANCEL if method == Method::POST => "rfqCancel",
255            API_RFQ_REFRESH if method == Method::POST => "rfqRefresh",
256            API_FUTURES_POSITION if method == Method::GET => "positionQuery",
257            API_BORROW_LEND_POSITIONS if method == Method::GET => "borrowLendPositionQuery",
258            API_COLLATERAL if method == Method::GET => "collateralQuery",
259            API_ACCOUNT if method == Method::GET => "accountQuery",
260            API_ACCOUNT_MAX_BORROW if method == Method::GET => "maxBorrowQuantity",
261            API_ACCOUNT_MAX_ORDER if method == Method::GET => "maxOrderQuantity",
262            API_ACCOUNT_MAX_WITHDRAWAL if method == Method::GET => "maxWithdrawalQuantity",
263            API_ACCOUNT if method == Method::PATCH => "accountUpdate",
264            API_ACCOUNT_CONVERT_DUST if method == Method::POST => "convertDust",
265            API_FILLS_HISTORY if method == Method::GET => "fillHistoryQueryAll",
266            API_VAULT_PENDING_REDEEMS if method == Method::GET => "vaultPendingRedeemsQuery",
267            _ => {
268                let req = self.client().request(method, url);
269                if let Some(payload) = payload {
270                    return Ok(req.json(payload).build()?);
271                } else {
272                    return Ok(req.build()?);
273                }
274            }
275        };
276
277        let Some(signing_key) = &self.signing_key else {
278            return Err(Error::NotAuthenticated);
279        };
280
281        let query_params = url
282            .query_pairs()
283            .collect::<BTreeMap<Cow<'_, str>, Cow<'_, str>>>();
284
285        let mut signee = if let Some(payload) = payload {
286            let value = serde_json::to_value(payload)?;
287            build_signee_query_and_payload(instruction, value, &query_params)?
288        } else {
289            build_signee_query(instruction, &query_params)
290        };
291
292        let timestamp = now_millis();
293        signee.push_str(&format!("&timestamp={timestamp}&window={DEFAULT_WINDOW}"));
294        tracing::debug!("signee: {}", signee);
295
296        let signature: Signature = signing_key.sign(signee.as_bytes());
297        let signature = Base64::encode_string(&signature.to_bytes());
298
299        let mut req = self.client().request(method, url);
300        if let Some(payload) = payload {
301            req = req.json(payload);
302        }
303        let mut req = req.build()?;
304        req.headers_mut()
305            .insert(SIGNATURE_HEADER, signature.parse()?);
306        req.headers_mut()
307            .insert(TIMESTAMP_HEADER, timestamp.to_string().parse()?);
308        req.headers_mut()
309            .insert(WINDOW_HEADER, DEFAULT_WINDOW.to_string().parse()?);
310        if matches!(req.method(), &Method::POST | &Method::DELETE) {
311            req.headers_mut()
312                .insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
313        }
314        Ok(req)
315    }
316}
317
318fn build_signee_query_and_payload(
319    instruction: &str,
320    payload: serde_json::Value,
321    query_params: &BTreeMap<Cow<'_, str>, Cow<'_, str>>,
322) -> Result<String> {
323    match payload {
324        Value::Object(map) => {
325            let body_params = map
326                .into_iter()
327                .map(|(k, v)| (k, v.to_string()))
328                .collect::<BTreeMap<_, _>>();
329            let mut signee = build_signee_query(instruction, query_params);
330            for (k, v) in body_params {
331                let v = v.trim_start_matches('"').trim_end_matches('"');
332                signee.push_str(&format!("&{k}={v}"));
333            }
334            Ok(signee)
335        }
336        Value::Array(array) => array
337            .into_iter()
338            .map(|item| build_signee_query_and_payload(instruction, item, query_params))
339            .collect::<Result<Vec<_>>>()
340            .map(|parts| parts.join("&")),
341        _ => Err(Error::InvalidRequest(
342            "payload must be a JSON object".into(),
343        )),
344    }
345}
346
347fn build_signee_query(
348    instruction: &str,
349    query_params: &BTreeMap<Cow<'_, str>, Cow<'_, str>>,
350) -> String {
351    let mut signee = format!("instruction={instruction}");
352    for (k, v) in query_params {
353        signee.push_str(&format!("&{k}={v}"));
354    }
355    signee
356}
357
358#[derive(Debug, Default)]
359pub struct BpxClientBuilder {
360    base_url: Option<String>,
361    ws_url: Option<String>,
362    secret: Option<String>,
363    headers: Option<BpxHeaders>,
364}
365
366impl BpxClientBuilder {
367    pub fn new() -> Self {
368        Default::default()
369    }
370
371    /// Sets the base URL for the Backpack Exchange API.
372    /// If not set, defaults to `BACKPACK_API_BASE_URL`.
373    ///
374    /// # Arguments
375    /// * `base_url` - The base URL
376    ///
377    /// # Returns
378    /// * `Self` - The updated builder instance
379    pub fn base_url(mut self, base_url: impl ToString) -> Self {
380        self.base_url = Some(base_url.to_string());
381        self
382    }
383
384    /// Sets the WebSocket URL for the Backpack Exchange API.
385    /// If not set, defaults to `BACKPACK_WS_URL`.
386    ///
387    /// # Arguments
388    /// * `ws_url` - The WebSocket URL
389    ///
390    /// # Returns
391    /// * `Self` - The updated builder instance
392    #[cfg(feature = "ws")]
393    pub fn ws_url(mut self, ws_url: impl ToString) -> Self {
394        self.ws_url = Some(ws_url.to_string());
395        self
396    }
397
398    /// Sets the API secret for signing requests.
399    /// If not set, the client will be unauthenticated.
400    ///
401    /// # Arguments
402    /// * `secret` - The API secret
403    ///
404    /// # Returns
405    /// * `Self` - The updated builder instance
406    pub fn secret(mut self, secret: impl ToString) -> Self {
407        self.secret = Some(secret.to_string());
408        self
409    }
410
411    /// Sets custom HTTP headers for the client.
412    /// If not set, no additional headers will be included.
413    ///
414    /// # Arguments
415    /// * `headers` - The custom HTTP headers
416    ///
417    /// # Returns
418    /// * `Self` - The updated builder instance
419    pub fn headers(mut self, headers: BpxHeaders) -> Self {
420        self.headers = Some(headers);
421        self
422    }
423
424    /// Builds the `BpxClient` instance with the configured parameters.
425    ///
426    /// # Returns
427    /// * `Result<BpxClient>` - The constructed client or an error if building fails
428    pub fn build(self) -> Result<BpxClient> {
429        let base_url = self.base_url.as_deref().unwrap_or(BACKPACK_API_BASE_URL);
430        let base_url = Url::parse(base_url)?;
431
432        let ws_url = self.ws_url.as_deref().unwrap_or(BACKPACK_WS_URL);
433        let ws_url = Url::parse(ws_url)?;
434
435        let signing_key = if let Some(secret) = self.secret {
436            Some(
437                Base64::decode_vec(&secret)?
438                    .try_into()
439                    .map(|s| SigningKey::from_bytes(&s))
440                    .map_err(|_| Error::SecretKey)?,
441            )
442        } else {
443            None
444        };
445        let verifying_key = signing_key.as_ref().map(|s| s.verifying_key());
446
447        let mut header_map = BpxHeaders::new();
448        if let Some(headers) = self.headers {
449            header_map.extend(headers);
450        }
451
452        header_map.insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
453        if let Some(signing_key) = &signing_key {
454            let verifier = signing_key.verifying_key();
455            header_map.insert(
456                API_KEY_HEADER,
457                Base64::encode_string(&verifier.to_bytes()).parse()?,
458            );
459        }
460
461        let client = BpxClient {
462            signing_key,
463            verifying_key,
464            base_url,
465            ws_url,
466            client: reqwest::Client::builder()
467                .user_agent(API_USER_AGENT)
468                .default_headers(header_map)
469                .build()?,
470        };
471
472        Ok(client)
473    }
474}
475
476/// Returns the current time in milliseconds since UNIX epoch.
477fn now_millis() -> u64 {
478    SystemTime::now()
479        .duration_since(UNIX_EPOCH)
480        .expect("Time went backwards")
481        .as_millis() as u64
482}