//! Polymarket: its market channel (the connection's side of it), Gamma (which //! markets are live), and the hash rule its book threads apply //! (docs/adr/0003-first-one-wins.md). pub mod feed; pub mod gamma; pub mod wire; use crossbeam::channel::{Receiver, Sender}; use serde_json::json; use tungstenite::client::IntoClientRequest; use crate::core::{self, Finding, Request, Undecoded}; pub const MARKET_CHANNEL_URL: &str = "wss://ws-subscriptions-clob.polymarket.com/ws/market"; /// Tokens per subscribe or unsubscribe message: a first message of more than /// 500 gets no opening books (docs/notes.md). const CHUNK: usize = 500; /// A live market: its symbols and the two inputs of their book hash that the /// websocket doesn't carry (docs/notes.md). #[derive(Debug, Clone)] pub struct Market { /// Gamma's `conditionId`, the websocket's `market`. pub condition_id: String, /// Its token ids, one per outcome: each is a symbol. pub tokens: Vec, /// Exactly as the hash expects it, e.g. `"5"`. pub min_order_size: String, pub neg_risk: bool, } impl core::Market for Market { fn id(&self) -> &str { &self.condition_id } fn symbols(&self) -> &[String] { &self.tokens } } /// The exchange, at its market channel's URL (the tests' local one in tests). pub struct Polymarket { pub url: String, } impl core::Exchange for Polymarket { type Market = Market; type Event = wire::Event; type Session = Session; type Rule = feed::Chain; const NAME: &'static str = "polymarket"; fn request(&self) -> anyhow::Result { Ok(self.url.as_str().into_client_request()?) } fn session(&self) -> Session { Session } fn rule(&self) -> feed::Chain { feed::Chain::default() } fn fetch(&self, requests: Receiver, findings: Sender>) { gamma::run(requests, findings) } } /// The market channel keeps no state of its own per connection. pub struct Session; impl Session { /// The messages that subscribe or unsubscribe `tokens` on an open /// connection. fn operations(operation: &str, tokens: &[&String]) -> Vec { tokens .chunks(CHUNK) .map(|chunk| json!({"assets_ids": chunk, "operation": operation}).to_string()) .collect() } } impl core::Session for Session { type Event = wire::Event; /// Opened empty, then subscribed in chunks: one rule for every token. fn opening(&mut self) -> Vec { vec![json!({"type": "market", "assets_ids": []}).to_string()] } fn subscribe(&mut self, tokens: &[&String]) -> Vec { Self::operations("subscribe", tokens) } fn unsubscribe(&mut self, tokens: &[&String]) -> Vec { Self::operations("unsubscribe", tokens) } fn keepalive(&self) -> Option<&'static str> { Some("PING") } fn decode(&mut self, text: &str) -> Result, Undecoded> { wire::decode(text).map_err(|error| Undecoded::Unreadable(error.to_string())) } } #[cfg(test)] pub(crate) fn fixture_markets() -> Vec { gamma::parse_markets(include_str!("../../tests/fixtures/gamma-markets.json")) } #[cfg(test)] mod socket_tests;