Skip to main content

bpx_api_client/ws/
mod.rs

1use crate::error::Result;
2use base64ct::{Base64, Encoding};
3use ed25519_dalek::Signer;
4use futures_util::{SinkExt, StreamExt};
5use serde::de::DeserializeOwned;
6use serde_json::{Value, json};
7use tokio::sync::mpsc::Sender;
8use tokio_tungstenite::tungstenite::protocol::Message;
9#[cfg(not(feature = "permessage-deflate"))]
10use tokio_tungstenite::{connect_async, tungstenite::Utf8Bytes};
11#[cfg(feature = "permessage-deflate")]
12use tokio_tungstenite::{
13    connect_async_with_config,
14    tungstenite::{
15        Utf8Bytes, extensions::compression::deflate::DeflateConfig, protocol::WebSocketConfig,
16    },
17};
18
19use crate::{BpxClient, DEFAULT_WINDOW, Error, now_millis};
20
21impl BpxClient {
22    /// Subscribes to a private WebSocket stream and sends messages of type `T` through a transmitter channel.
23    pub async fn subscribe<T>(&self, stream: &str, tx: Sender<T>) -> Result<()>
24    where
25        T: DeserializeOwned + Send + 'static,
26    {
27        self.internal_subscribe(&[stream], tx).await
28    }
29
30    /// Subscribes to multiple private WebSocket streams and sends messages of type `T` through a transmitter channel.
31    pub async fn subscribe_multiple<T>(&self, streams: &[&str], tx: Sender<T>) -> Result<()>
32    where
33        T: DeserializeOwned + Send + 'static,
34    {
35        self.internal_subscribe(streams, tx).await
36    }
37
38    async fn internal_subscribe<T>(&self, streams: &[&str], tx: Sender<T>) -> Result<()>
39    where
40        T: DeserializeOwned + Send + 'static,
41    {
42        let timestamp = now_millis();
43        let window = DEFAULT_WINDOW;
44
45        let is_private = streams.iter().any(|s| is_private_stream(s));
46        let subscribe_message = if is_private {
47            let signing_key = self.signing_key.as_ref().ok_or(Error::NotAuthenticated)?;
48
49            let message = format!("instruction=subscribe&timestamp={timestamp}&window={window}");
50
51            let verifying_key = Base64::encode_string(&signing_key.verifying_key().to_bytes());
52            let signature = Base64::encode_string(&signing_key.sign(message.as_bytes()).to_bytes());
53
54            json!({
55                "method": "SUBSCRIBE",
56                "params": streams,
57                "signature": [verifying_key, signature, timestamp.to_string(), window.to_string()],
58            })
59        } else {
60            json!({
61                "method": "SUBSCRIBE",
62                "params": streams
63            })
64        };
65
66        let ws_url = self.ws_url.as_str();
67        #[cfg(not(feature = "permessage-deflate"))]
68        let connect = connect_async(ws_url);
69        // Offer permessage-deflate on the handshake. The server selects the
70        // extension when it supports it and falls back to an uncompressed
71        // connection when it does not, so the offer is always safe.
72        #[cfg(feature = "permessage-deflate")]
73        let connect = {
74            let mut config = WebSocketConfig::default();
75            config.extensions.permessage_deflate = Some(DeflateConfig::default());
76            connect_async_with_config(ws_url, Some(config), false)
77        };
78        let (mut ws_stream, _) = connect.await.expect("Error connecting to WebSocket");
79        ws_stream
80            .send(Message::Text(Utf8Bytes::from(
81                subscribe_message.to_string(),
82            )))
83            .await
84            .expect("Error subscribing to WebSocket");
85
86        tracing::debug!("Subscribed to {streams:#?} streams...");
87
88        while let Some(message) = ws_stream.next().await {
89            match message {
90                Ok(msg) => match msg {
91                    Message::Text(text) => {
92                        if let Ok(value) = serde_json::from_str::<Value>(&text) {
93                            if let Some(payload) = value.get("data") {
94                                match T::deserialize(payload) {
95                                    Ok(data) => {
96                                        if tx.send(data).await.is_err() {
97                                            tracing::warn!("Channel is closed");
98                                            break;
99                                        }
100                                    }
101                                    Err(err) => {
102                                        tracing::error!("Could not deserialize ws payload: {err}");
103                                    }
104                                }
105                            } else if let Some(payload) = value.get("error") {
106                                tracing::error!(?payload, "Websocket Error Response");
107                            }
108                        }
109                    }
110                    Message::Close(_) => break,
111                    _ => {}
112                },
113                Err(error) => tracing::error!(%error, "WebSocket error"),
114            }
115        }
116        Ok(())
117    }
118}
119
120fn is_private_stream(stream: &str) -> bool {
121    stream.starts_with("account.")
122}