polyfill_rs/lib.rs
1//! Polyfill-rs: High-performance Rust client for Polymarket
2//!
3//! # Features
4//!
5//! - **High-performance order book management** with optimized data structures
6//! - **Real-time market data streaming** with WebSocket support
7//! - **Trade execution simulation** with slippage protection
8//! - **Comprehensive error handling** with specific error types
9//! - **Rate limiting and retry logic** for robust API interactions
10//! - **Ethereum integration** with EIP-712 signing support
11//! - **Benchmarking tools** for performance analysis
12//!
13//! # Quick Start
14//!
15//! ```rust,no_run
16//! use polyfill_rs::{ClobClient, OrderArgs, Side};
17//! use rust_decimal::Decimal;
18//! use std::str::FromStr;
19//!
20//! #[tokio::main]
21//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
22//! // Create client (compatible with polymarket-rs-client)
23//! let mut client = ClobClient::with_l1_headers(
24//! "https://clob.polymarket.com",
25//! "your_private_key",
26//! 137,
27//! );
28//!
29//! // Get API credentials
30//! let api_creds = client.create_or_derive_api_key(None).await.unwrap();
31//! client.set_api_creds(api_creds);
32//!
33//! // Create and post order
34//! let order_args = OrderArgs::new(
35//! "token_id",
36//! Decimal::from_str("0.75").unwrap(),
37//! Decimal::from_str("100.0").unwrap(),
38//! Side::BUY,
39//! );
40//!
41//! let result = client.create_and_post_order(&order_args).await.unwrap();
42//! println!("Order posted: {:?}", result);
43//!
44//! Ok(())
45//! }
46//! ```
47//!
48//! # Advanced Usage
49//!
50//! ```rust,no_run
51//! use polyfill_rs::{ClobClient, OrderBookImpl};
52//! use rust_decimal::Decimal;
53//!
54//! #[tokio::main]
55//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
56//! // Create a basic client
57//! let client = ClobClient::new("https://clob.polymarket.com");
58//!
59//! // Get market data
60//! let markets = client.get_sampling_markets(None).await.unwrap();
61//! println!("Found {} markets", markets.data.len());
62//!
63//! // Create an order book for high-performance operations
64//! let mut book = OrderBookImpl::new("token_id".to_string(), 100); // 100 levels depth
65//! println!("Order book created for token: {}", book.token_id);
66//!
67//! Ok(())
68//! }
69//! ```
70
71use tracing::info;
72
73
74// Global constants
75pub const DEFAULT_CHAIN_ID: u64 = 137; // Polygon
76pub const DEFAULT_BASE_URL: &str = "https://clob.polymarket.com";
77pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
78pub const DEFAULT_MAX_RETRIES: u32 = 3;
79pub const DEFAULT_RATE_LIMIT_RPS: u32 = 100;
80
81// Initialize logging
82pub fn init() {
83 tracing_subscriber::fmt::init();
84 info!("Polyfill-rs initialized");
85}
86
87// Re-export main types
88pub use crate::types::{
89 ApiCredentials, Balance, BalanceAllowance, BatchMidpointRequest, BatchMidpointResponse,
90 BatchPriceRequest, BatchPriceResponse, ClientConfig, FillEvent, MarketSnapshot,
91 NotificationParams, OpenOrder, OpenOrderParams, Order, OrderBook, OrderDelta,
92 OrderRequest, OrderStatus, OrderType, Side, StreamMessage, TokenPrice, TradeParams,
93 WssAuth, WssSubscription, WssChannelType,
94 // Additional compatibility types
95 ApiKeysResponse, MidpointResponse, PriceResponse, SpreadResponse, TickSizeResponse,
96 NegRiskResponse, BookParams, MarketsResponse, SimplifiedMarketsResponse, Market,
97 SimplifiedMarket, Token, Rewards, ClientResult, OrderBookSummary, OrderSummary,
98 BalanceAllowanceParams, AssetType,
99};
100
101// Re-export client
102pub use crate::client::{ClobClient, PolyfillClient};
103
104// Re-export compatibility types (for easy migration from polymarket-rs-client)
105pub use crate::client::{
106 OrderArgs,
107};
108
109// Re-export error types
110pub use crate::errors::{PolyfillError, Result};
111
112// Re-export advanced components
113pub use crate::book::{OrderBook as OrderBookImpl, OrderBookManager};
114pub use crate::fill::{FillEngine, FillResult};
115pub use crate::stream::{MarketStream, StreamManager, WebSocketStream};
116pub use crate::decode::Decoder;
117
118// Re-export utilities
119pub use crate::utils::{
120 crypto, math, retry, time, url, rate_limit,
121};
122
123// Module declarations
124pub mod auth;
125pub mod book;
126pub mod client;
127pub mod decode;
128pub mod errors;
129pub mod fill;
130pub mod orders;
131pub mod stream;
132pub mod types;
133pub mod utils;
134
135// Benchmarks
136#[cfg(test)]
137mod benches {
138 use criterion::{criterion_group, criterion_main};
139 use crate::{OrderBookManager, OrderDelta, Side};
140 use rust_decimal::Decimal;
141 use chrono::Utc;
142 use std::str::FromStr;
143
144 fn order_book_benchmark(c: &mut criterion::Criterion) {
145 let mut book_manager = OrderBookManager::new(100);
146
147 c.bench_function("apply_order_delta", |b| {
148 b.iter(|| {
149 let delta = OrderDelta {
150 token_id: "test_token".to_string(),
151 timestamp: Utc::now(),
152 side: Side::BUY,
153 price: Decimal::from_str("0.75").unwrap(),
154 size: Decimal::from_str("100.0").unwrap(),
155 sequence: 1,
156 };
157
158 let _ = book_manager.apply_delta(delta);
159 });
160 });
161 }
162
163 criterion_group!(benches, order_book_benchmark);
164 criterion_main!(benches);
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170 use rust_decimal::Decimal;
171 use std::str::FromStr;
172
173 #[test]
174 fn test_client_creation() {
175 let client = ClobClient::new("https://test.example.com");
176 // Test that the client was created successfully
177 // We can't test private fields, but we can verify the client exists
178 assert!(true); // Client creation successful
179 }
180
181 #[test]
182 fn test_order_args_creation() {
183 let args = OrderArgs::new(
184 "test_token",
185 Decimal::from_str("0.75").unwrap(),
186 Decimal::from_str("100.0").unwrap(),
187 Side::BUY,
188 );
189
190 assert_eq!(args.token_id, "test_token");
191 assert_eq!(args.side, Side::BUY);
192 }
193
194 #[test]
195 fn test_order_args_default() {
196 let args = OrderArgs::default();
197 assert_eq!(args.token_id, "");
198 assert_eq!(args.price, Decimal::ZERO);
199 assert_eq!(args.size, Decimal::ZERO);
200 assert_eq!(args.side, Side::BUY);
201 }
202}