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 base64::{Engine, engine::general_purpose::STANDARD};
37use ed25519_dalek::{Signature, Signer, SigningKey};
38use reqwest::{IntoUrl, Method, Request, Response, StatusCode, Url, header::CONTENT_TYPE};
39use routes::{
40    account::{API_ACCOUNT, API_ACCOUNT_CONVERT_DUST, API_ACCOUNT_MAX_BORROW, API_ACCOUNT_MAX_WITHDRAWAL},
41    borrow_lend::API_BORROW_LEND_POSITIONS,
42    capital::{API_CAPITAL, API_COLLATERAL, API_DEPOSIT_ADDRESS, API_DEPOSITS, API_WITHDRAWALS},
43    futures::API_FUTURES_POSITION,
44    history::API_FILLS_HISTORY,
45    order::{API_ORDER, API_ORDERS},
46    rfq::{API_RFQ, API_RFQ_QUOTE},
47    user::API_USER_2FA,
48};
49use serde::Serialize;
50use serde_json::Value;
51use std::{
52    borrow::Cow,
53    collections::BTreeMap,
54    time::{SystemTime, UNIX_EPOCH},
55};
56
57pub mod error;
58
59mod routes;
60
61#[cfg(feature = "ws")]
62mod ws;
63
64/// Re-export of the Backpack Exchange API types.
65pub use bpx_api_types as types;
66
67/// Re-export of the custom `Error` type and `Result` alias for error handling.
68pub use error::{Error, Result};
69
70const API_USER_AGENT: &str = "bpx-rust-client";
71const API_KEY_HEADER: &str = "X-API-Key";
72
73const DEFAULT_WINDOW: u32 = 5000;
74
75const SIGNATURE_HEADER: &str = "X-Signature";
76const TIMESTAMP_HEADER: &str = "X-Timestamp";
77const WINDOW_HEADER: &str = "X-Window";
78
79const JSON_CONTENT: &str = "application/json; charset=utf-8";
80
81/// The official base URL for the Backpack Exchange REST API.
82pub const BACKPACK_API_BASE_URL: &str = "https://api.backpack.exchange";
83
84/// The official WebSocket URL for real-time data from the Backpack Exchange.
85pub const BACKPACK_WS_URL: &str = "wss://ws.backpack.exchange";
86
87/// Type alias for custom HTTP headers passed to `BpxClient` during initialization.
88pub type BpxHeaders = reqwest::header::HeaderMap;
89
90/// A client for interacting with the Backpack Exchange API.
91#[derive(Debug, Clone)]
92pub struct BpxClient {
93    signing_key: Option<SigningKey>,
94    base_url: Url,
95    ws_url: Url,
96    client: reqwest::Client,
97}
98
99impl std::ops::Deref for BpxClient {
100    type Target = reqwest::Client;
101
102    fn deref(&self) -> &Self::Target {
103        &self.client
104    }
105}
106
107impl std::ops::DerefMut for BpxClient {
108    fn deref_mut(&mut self) -> &mut Self::Target {
109        &mut self.client
110    }
111}
112
113impl AsRef<reqwest::Client> for BpxClient {
114    fn as_ref(&self) -> &reqwest::Client {
115        &self.client
116    }
117}
118
119// Public functions.
120impl BpxClient {
121    pub fn builder() -> BpxClientBuilder {
122        BpxClientBuilder::new()
123    }
124
125    /// Initializes a new client with the given base URL, API secret, and optional headers.
126    ///
127    /// This sets up the signing and verification keys, and creates a `reqwest` client
128    /// with default headers including the API key and content type.
129    pub fn init(base_url: String, secret: &str, headers: Option<BpxHeaders>) -> Result<Self> {
130        BpxClientBuilder::new()
131            .base_url(base_url)
132            .secret(secret)
133            .headers(headers.unwrap_or_default())
134            .build()
135    }
136
137    /// Initializes a new client with WebSocket support.
138    #[cfg(feature = "ws")]
139    #[deprecated(note = "Use BpxClient::builder() instead to configure the client with a custom websocket URL.")]
140    pub fn init_with_ws(base_url: String, ws_url: String, secret: &str, headers: Option<BpxHeaders>) -> Result<Self> {
141        BpxClientBuilder::new()
142            .base_url(base_url)
143            .ws_url(ws_url)
144            .secret(secret)
145            .headers(headers.unwrap_or_default())
146            .build()
147    }
148
149    /// Processes the response to check for HTTP errors and extracts
150    /// the response content.
151    ///
152    /// Returns a custom error if the status code is non-2xx.
153    async fn process_response(res: Response) -> Result<Response> {
154        if let Err(e) = res.error_for_status_ref() {
155            let err_text = res.text().await?;
156            let err = Error::BpxApiError {
157                status_code: e.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
158                message: err_text.into(),
159            };
160            return Err(err);
161        }
162        Ok(res)
163    }
164
165    /// Sends a GET request to the specified URL and signs it before execution.
166    pub async fn get<U: IntoUrl>(&self, url: U) -> Result<Response> {
167        let req = self.build_and_maybe_sign_request::<(), _>(url, Method::GET, None)?;
168        tracing::debug!(?req, "GET request");
169        let res = self.client.execute(req).await?;
170        Self::process_response(res).await
171    }
172
173    /// Sends a POST request with a JSON payload to the specified URL and signs it.
174    pub async fn post<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
175        let req = self.build_and_maybe_sign_request(url, Method::POST, Some(&payload))?;
176        tracing::debug!(?req, "POST request");
177        let res = self.client.execute(req).await?;
178        Self::process_response(res).await
179    }
180
181    /// Sends a DELETE request with a JSON payload to the specified URL and signs it.
182    pub async fn delete<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
183        let req = self.build_and_maybe_sign_request(url, Method::DELETE, Some(&payload))?;
184        tracing::debug!(?req, "DELETE request");
185        let res = self.client.execute(req).await?;
186        Self::process_response(res).await
187    }
188
189    /// Sends a PATCH request with a JSON payload to the specified URL and signs it.
190    pub async fn patch<P: Serialize, U: IntoUrl>(&self, url: U, payload: P) -> Result<Response> {
191        let req = self.build_and_maybe_sign_request(url, Method::PATCH, Some(&payload))?;
192        tracing::debug!(?req, "PATCH request");
193        let res = self.client.execute(req).await?;
194        Self::process_response(res).await
195    }
196
197    /// Returns a reference to the underlying HTTP client.
198    pub const fn client(&self) -> &reqwest::Client {
199        &self.client
200    }
201}
202
203// Private functions.
204impl BpxClient {
205    /// Signs a request by generating a signature from the request details
206    /// and appending necessary headers for authentication.
207    ///
208    /// # Arguments
209    /// * `req` - The mutable reference to the request to be signed.
210    fn build_and_maybe_sign_request<P: Serialize, U: IntoUrl>(
211        &self,
212        url: U,
213        method: Method,
214        payload: Option<&P>,
215    ) -> Result<Request> {
216        let url = url.into_url()?;
217        let instruction = match url.path() {
218            API_CAPITAL if method == Method::GET => "balanceQuery",
219            API_DEPOSITS if method == Method::GET => "depositQueryAll",
220            API_DEPOSIT_ADDRESS if method == Method::GET => "depositAddressQuery",
221            API_WITHDRAWALS if method == Method::GET => "withdrawalQueryAll",
222            API_WITHDRAWALS if method == Method::POST => "withdraw",
223            API_USER_2FA if method == Method::POST => "issueTwoFactorToken",
224            API_ORDER if method == Method::GET => "orderQuery",
225            API_ORDER if method == Method::POST => "orderExecute",
226            API_ORDER if method == Method::DELETE => "orderCancel",
227            API_ORDERS if method == Method::GET => "orderQueryAll",
228            API_ORDERS if method == Method::DELETE => "orderCancelAll",
229            API_RFQ if method == Method::POST => "rfqSubmit",
230            API_RFQ_QUOTE if method == Method::POST => "quoteSubmit",
231            API_FUTURES_POSITION if method == Method::GET => "positionQuery",
232            API_BORROW_LEND_POSITIONS if method == Method::GET => "borrowLendPositionQuery",
233            API_COLLATERAL if method == Method::GET => "collateralQuery",
234            API_ACCOUNT if method == Method::GET => "accountQuery",
235            API_ACCOUNT_MAX_BORROW if method == Method::GET => "maxBorrowQuantity",
236            API_ACCOUNT_MAX_WITHDRAWAL if method == Method::GET => "maxWithdrawalQuantity",
237            API_ACCOUNT if method == Method::PATCH => "accountUpdate",
238            API_ACCOUNT_CONVERT_DUST if method == Method::POST => "convertDust",
239            API_FILLS_HISTORY if method == Method::GET => "fillHistoryQueryAll",
240            _ => {
241                let req = self.client().request(method, url);
242                if let Some(payload) = payload {
243                    return Ok(req.json(payload).build()?);
244                } else {
245                    return Ok(req.build()?);
246                }
247            }
248        };
249
250        let Some(signing_key) = &self.signing_key else {
251            return Err(Error::NotAuthenticated);
252        };
253
254        let query_params = url.query_pairs().collect::<BTreeMap<Cow<'_, str>, Cow<'_, str>>>();
255        let body_params = if let Some(payload) = payload {
256            let s = serde_json::to_value(payload)?;
257            match s {
258                Value::Object(map) => map
259                    .into_iter()
260                    .map(|(k, v)| (k, v.to_string()))
261                    .collect::<BTreeMap<_, _>>(),
262                _ => return Err(Error::InvalidRequest("payload must be a JSON object".into())),
263            }
264        } else {
265            BTreeMap::new()
266        };
267
268        let timestamp = now_millis();
269        let mut signee = format!("instruction={instruction}");
270        for (k, v) in query_params {
271            signee.push_str(&format!("&{k}={v}"));
272        }
273        for (k, v) in body_params {
274            let v = v.trim_start_matches('"').trim_end_matches('"');
275            signee.push_str(&format!("&{k}={v}"));
276        }
277        signee.push_str(&format!("&timestamp={timestamp}&window={DEFAULT_WINDOW}"));
278        tracing::debug!("signee: {}", signee);
279
280        let signature: Signature = signing_key.sign(signee.as_bytes());
281        let signature = STANDARD.encode(signature.to_bytes());
282
283        let mut req = self.client().request(method, url);
284        if let Some(payload) = payload {
285            req = req.json(payload);
286        }
287        let mut req = req.build()?;
288        req.headers_mut().insert(SIGNATURE_HEADER, signature.parse()?);
289        req.headers_mut()
290            .insert(TIMESTAMP_HEADER, timestamp.to_string().parse()?);
291        req.headers_mut()
292            .insert(WINDOW_HEADER, DEFAULT_WINDOW.to_string().parse()?);
293        if matches!(req.method(), &Method::POST | &Method::DELETE) {
294            req.headers_mut().insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
295        }
296        Ok(req)
297    }
298}
299
300#[derive(Debug, Default)]
301pub struct BpxClientBuilder {
302    base_url: Option<String>,
303    ws_url: Option<String>,
304    secret: Option<String>,
305    headers: Option<BpxHeaders>,
306}
307
308impl BpxClientBuilder {
309    pub fn new() -> Self {
310        Default::default()
311    }
312
313    /// Sets the base URL for the Backpack Exchange API.
314    /// If not set, defaults to `BACKPACK_API_BASE_URL`.
315    ///
316    /// # Arguments
317    /// * `base_url` - The base URL
318    ///
319    /// # Returns
320    /// * `Self` - The updated builder instance
321    pub fn base_url(mut self, base_url: impl ToString) -> Self {
322        self.base_url = Some(base_url.to_string());
323        self
324    }
325
326    /// Sets the WebSocket URL for the Backpack Exchange API.
327    /// If not set, defaults to `BACKPACK_WS_URL`.
328    ///
329    /// # Arguments
330    /// * `ws_url` - The WebSocket URL
331    ///
332    /// # Returns
333    /// * `Self` - The updated builder instance
334    pub fn ws_url(mut self, ws_url: impl ToString) -> Self {
335        self.ws_url = Some(ws_url.to_string());
336        self
337    }
338
339    /// Sets the API secret for signing requests.
340    /// If not set, the client will be unauthenticated.
341    ///
342    /// # Arguments
343    /// * `secret` - The API secret
344    ///
345    /// # Returns
346    /// * `Self` - The updated builder instance
347    pub fn secret(mut self, secret: impl ToString) -> Self {
348        self.secret = Some(secret.to_string());
349        self
350    }
351
352    /// Sets custom HTTP headers for the client.
353    /// If not set, no additional headers will be included.
354    ///
355    /// # Arguments
356    /// * `headers` - The custom HTTP headers
357    ///
358    /// # Returns
359    /// * `Self` - The updated builder instance
360    pub fn headers(mut self, headers: BpxHeaders) -> Self {
361        self.headers = Some(headers);
362        self
363    }
364
365    /// Builds the `BpxClient` instance with the configured parameters.
366    ///
367    /// # Returns
368    /// * `Result<BpxClient>` - The constructed client or an error if building fails
369    pub fn build(self) -> Result<BpxClient> {
370        let base_url = self
371            .base_url
372            .map(Cow::from)
373            .unwrap_or_else(|| Cow::Borrowed(BACKPACK_API_BASE_URL));
374
375        let base_url = Url::parse(&base_url).map_err(|e| Error::UrlParseError(e.to_string().into()))?;
376
377        let ws_url = self
378            .ws_url
379            .map(Cow::from)
380            .unwrap_or_else(|| Cow::Borrowed(BACKPACK_WS_URL));
381
382        let ws_url = Url::parse(&ws_url).map_err(|e| Error::UrlParseError(e.to_string().into()))?;
383
384        let signing_key = if let Some(secret) = self.secret {
385            Some(
386                STANDARD
387                    .decode(secret)?
388                    .try_into()
389                    .map(|s| SigningKey::from_bytes(&s))
390                    .map_err(|_| Error::SecretKey)?,
391            )
392        } else {
393            None
394        };
395
396        let mut header_map = BpxHeaders::new();
397        if let Some(headers) = self.headers {
398            header_map.extend(headers);
399        }
400
401        header_map.insert(CONTENT_TYPE, JSON_CONTENT.parse()?);
402        if let Some(signing_key) = &signing_key {
403            let verifier = signing_key.verifying_key();
404            header_map.insert(API_KEY_HEADER, STANDARD.encode(verifier).parse()?);
405        }
406
407        let client = BpxClient {
408            signing_key,
409            base_url,
410            ws_url,
411            client: reqwest::Client::builder()
412                .user_agent(API_USER_AGENT)
413                .default_headers(header_map)
414                .build()?,
415        };
416
417        Ok(client)
418    }
419}
420
421/// Returns the current time in milliseconds since UNIX epoch.
422fn now_millis() -> u64 {
423    SystemTime::now()
424        .duration_since(UNIX_EPOCH)
425        .expect("Time went backwards")
426        .as_millis() as u64
427}