polymarket 0.1.0

Rust SDK for Polymarket prediction market - CLOB trading, on-chain operations, and WebSocket streaming
Documentation
use ws_reconnect_client::{WebSocketClient, WebSocketClientBuilder};

use super::{SubscribeRequest, Subscription, RtdsMessage};
use crate::Result;

/// RTDS websocket client with automatic reconnection
pub struct RtdsWebSocket {
    client: WebSocketClient<RtdsMessage>,
}

impl RtdsWebSocket {
    /// Create a new RTDS client with default configuration
    pub fn new(rtds_url: impl Into<String>) -> Self {
        let client = WebSocketClientBuilder::new(rtds_url)
            .ping_interval(5)
            .auto_reconnect(true)
            .max_retries(20)
            .build();

        Self { client }
    }

    /// Create a new RTDS client with custom WebSocket client
    pub fn with_client(client: WebSocketClient<RtdsMessage>) -> Self {
        Self { client }
    }

    /// Start listening to RTDS messages with automatic reconnection
    ///
    /// # Arguments
    /// * `subscriptions` - List of RTDS subscriptions to subscribe to
    /// * `handler` - Callback function that processes each received message
    ///
    /// # Example
    /// ```no_run
    /// # use polymarket_sdk::rtds::{RtdsWebSocket, Subscription};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = RtdsWebSocket::new("wss://ws-live-data.polymarket.com");
    /// let subscriptions = vec![
    ///     Subscription {
    ///         topic: "crypto_prices_chainlink".to_string(),
    ///         r#type: "*".to_string(),
    ///         filters: Some("".to_string()),
    ///         clob_auth: None,
    ///         gamma_auth: None,
    ///     }
    /// ];
    ///
    /// client.listen(subscriptions, |msg| {
    ///     println!("Received RTDS message: {:?}", msg);
    ///     Ok(())
    /// }).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn listen<F>(&self, subscriptions: Vec<Subscription>, mut handler: F) -> Result<()>
    where
        F: FnMut(RtdsMessage) -> Result<()>,
    {
        let subscribe_request = SubscribeRequest::new(subscriptions);

        self.client
            .listen(Some(subscribe_request), |msg| {
                handler(msg).map_err(|e| ws_reconnect_client::WebSocketError::HandlerError(e.to_string()))
            })
            .await?;

        Ok(())
    }
}