polymarket_sdk/
lib.rs

1//! # Polymarket SDK
2//!
3//! A comprehensive Rust SDK for [Polymarket](https://polymarket.com) prediction markets.
4//!
5//! ## Attribution
6//!
7//! Parts of this SDK are derived from official Polymarket open-source projects:
8//!
9//! - **Builder API signing**: Derived from [`polymarket-rs-sdk`](https://github.com/polymarket/polymarket-rs-sdk)
10//! - **API patterns**: Inspired by [`py-clob-client`](https://github.com/Polymarket/py-clob-client)
11//!   and [`clob-client`](https://github.com/Polymarket/clob-client)
12//!
13//! ## Features
14//!
15//! - **Market Discovery** - Query markets, events, and metadata
16//! - **Real-time Data** - WebSocket streams for trades and order books
17//! - **Order Management** - Create, sign, and submit orders
18//! - **Authentication** - EIP-712 and HMAC-based auth
19//! - **Safe Wallet** - Gnosis Safe proxy wallet integration
20//!
21//! ## Quick Start
22//!
23//! ```rust,ignore
24//! use polymarket_sdk::prelude::*;
25//!
26//! #[tokio::main]
27//! async fn main() -> Result<()> {
28//!     // Market discovery (no auth required)
29//!     let client = GammaClient::new(Default::default())?;
30//!     let markets = client.get_markets(None).await?;
31//!     println!("Found {} markets", markets.len());
32//!     Ok(())
33//! }
34//! ```
35//!
36//! ## Module Organization
37//!
38//! - [`core`] - Error handling and endpoint configuration
39//! - [`types`] - Common types (Side, Market, Order, etc.)
40//! - [`auth`] - Authentication (EIP-712, HMAC, Builder API)
41//! - [`client`] - REST API clients (Gamma, Data, CLOB, Profiles)
42//! - [`order`] - Order creation and signing
43//! - [`stream`] - WebSocket streaming (RTDS, CLOB WSS)
44//! - [`safe`] - Safe wallet deployment and management
45
46#![cfg_attr(docsrs, feature(doc_cfg))]
47
48// Core infrastructure
49pub mod core;
50
51// Type definitions
52pub mod types;
53
54// Authentication
55#[cfg(feature = "auth")]
56#[cfg_attr(docsrs, doc(cfg(feature = "auth")))]
57pub mod auth;
58
59// API clients
60#[cfg(feature = "client")]
61#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
62pub mod client;
63
64// Order building
65#[cfg(feature = "order")]
66#[cfg_attr(docsrs, doc(cfg(feature = "order")))]
67pub mod order;
68
69// WebSocket streams
70#[cfg(feature = "stream")]
71#[cfg_attr(docsrs, doc(cfg(feature = "stream")))]
72pub mod stream;
73
74// Safe wallet
75#[cfg(feature = "safe")]
76#[cfg_attr(docsrs, doc(cfg(feature = "safe")))]
77pub mod safe;
78
79// Prelude for convenient imports
80pub mod prelude;
81
82// ============================================================================
83// Core Re-exports (always available)
84// ============================================================================
85
86pub use core::{
87    AuthErrorKind, MarketDataErrorKind, OrderErrorKind, StreamErrorKind, CLOB_API_BASE,
88    CLOB_WSS_BASE, DATA_API_BASE, GAMMA_API_BASE, PROFILES_API_BASE, RELAYER_API_BASE,
89    RTDS_WSS_BASE,
90};
91pub use core::{Endpoints, Error, PolymarketError, Result};
92
93// ============================================================================
94// Type Re-exports (always available)
95// ============================================================================
96
97pub use types::{
98    ApiCredentials, BiggestWinner, BiggestWinnersQuery, BookLevel, ClosedPosition, ConnectionStats,
99    DataApiActivity, DataApiPosition, DataApiTrade, DataApiTrader, Event, EventMarket,
100    LeaderboardEntry, ListParams, Market, MarketOrderArgs, NewOrder, NewOrderData, OrderOptions,
101    OrderType, PaginationParams, SearchEvent, SearchProfile, SearchRequest, SearchResponse,
102    SearchTag, Side, SignedOrderRequest, Tag, Token, TraderProfile,
103};
104
105#[cfg(feature = "auth")]
106pub use types::ExtraOrderArgs;
107
108// ============================================================================
109// Auth Re-exports
110// ============================================================================
111
112#[cfg(feature = "auth")]
113pub use auth::{
114    build_clob_auth_typed_data, build_hmac_signature, build_hmac_signature_from_string,
115    create_l1_headers, create_l2_headers, create_l2_headers_with_address,
116    create_l2_headers_with_body_string, get_current_unix_time_secs, sign_clob_auth_message,
117    sign_order_message, BuilderApiKeyCreds, BuilderSigner, ClobAuth, Headers, Order,
118};
119
120// ============================================================================
121// Client Re-exports
122// ============================================================================
123
124#[cfg(feature = "client")]
125pub use client::{
126    ApiKeyResponse, CancelResponse, ClobClient, ClobConfig, DataClient, DataConfig,
127    DeriveApiKeyResponse, GammaClient, GammaConfig, OpenOrder, OrderResponse, PaginatedResponse,
128    ProfilesClient, ProfilesConfig,
129};
130
131// ============================================================================
132// Order Re-exports
133// ============================================================================
134
135#[cfg(feature = "order")]
136pub use order::{get_contract_config, ContractConfig, OrderArgs, OrderBuilder, SigType};
137
138// ============================================================================
139// Stream Re-exports
140// ============================================================================
141
142#[cfg(feature = "stream")]
143pub use stream::{
144    LastTradeMessage, MarketBook, MarketStream, MockStream, PriceChangeEntry, PriceChangeMessage,
145    RtdsClient, RtdsConfig, RtdsEvent, RtdsMessage, RtdsSubscription, RtdsSubscriptionMessage,
146    StreamManager, StreamMessage, StreamStats, Subscription, TickSizeChangeMessage, TradePayload,
147    WebSocketStream, WssAuth, WssMarketClient, WssMarketEvent, WssStats, WssSubscription,
148    WssUserClient, WssUserEvent, WssUserOrderMessage, WssUserTradeMessage,
149};
150
151// ============================================================================
152// Safe Re-exports
153// ============================================================================
154
155#[cfg(feature = "safe")]
156pub use safe::{
157    build_ctf_approve_typed_data, build_safe_create_typed_data, build_safe_tx_request,
158    build_token_approve_typed_data, build_usdc_transfer_typed_data, compute_safe_tx_digest,
159    derive_safe_address, encode_erc1155_set_approval_for_all, encode_erc20_allowance_query,
160    encode_erc20_approve, encode_erc20_transfer, pack_signature, pack_signature_for_safe_tx,
161    ApprovalStatus, DeploySafeResponse, NonceType, RelayerClient, RelayerConfig,
162    SafeCreateTypedData, SafeTxDomain, SafeTxMessage, SafeTxTypedData, SafeTxTypes,
163    SignatureParams, TransactionReceipt, TransactionRequest, TransactionState, TransactionType,
164    CONDITIONAL_TOKENS_ADDRESS, CTF_EXCHANGE_ADDRESS, EXCHANGE_ADDRESS,
165    NATIVE_USDC_CONTRACT_ADDRESS, NEG_RISK_CTF_EXCHANGE_ADDRESS, SAFE_FACTORY, SAFE_INIT_CODE_HASH,
166    USDC_CONTRACT_ADDRESS,
167};
168
169// ============================================================================
170// Backward-compatible Module Aliases (for ride-service migration)
171// ============================================================================
172
173/// Backward-compatible alias for `client` module
174#[cfg(feature = "client")]
175pub mod clob {
176    //! Backward-compatible module alias for CLOB client.
177    //! Use `polymarket_sdk::client` or top-level re-exports instead.
178    pub use crate::client::{ClobClient, ClobConfig};
179}
180
181/// Backward-compatible alias for Gamma API client
182#[cfg(feature = "client")]
183pub mod gamma {
184    //! Backward-compatible module alias for Gamma API client.
185    //! Use `polymarket_sdk::client` or top-level re-exports instead.
186    pub use crate::client::{GammaClient, GammaConfig};
187}
188
189/// Backward-compatible alias for Data API client
190#[cfg(feature = "client")]
191pub mod data {
192    //! Backward-compatible module alias for Data API client.
193    //! Use `polymarket_sdk::client` or top-level re-exports instead.
194    pub use crate::client::{DataClient, DataConfig};
195}
196
197/// Backward-compatible alias for `order` module
198#[cfg(feature = "order")]
199pub mod orders {
200    //! Backward-compatible module alias for order building.
201    //! Use `polymarket_sdk::order` or top-level re-exports instead.
202    pub use crate::order::{get_contract_config, ContractConfig, OrderArgs, OrderBuilder, SigType};
203}
204
205/// Backward-compatible alias for CLOB WebSocket client
206#[cfg(feature = "stream")]
207pub mod wss {
208    //! Backward-compatible module alias for CLOB WebSocket functionality.
209    //! Use `polymarket_sdk::stream` or top-level re-exports instead.
210    pub use crate::stream::{
211        LastTradeMessage, MarketBook, OrderSummary, PriceChangeEntry, PriceChangeMessage,
212        TickSizeChangeMessage, WssMarketClient, WssMarketEvent, WssStats, WssUserClient,
213        WssUserEvent, WssUserOrderMessage, WssUserTradeMessage,
214    };
215}
216
217/// Backward-compatible alias for `safe` module
218#[cfg(feature = "safe")]
219pub mod relayer {
220    //! Backward-compatible module alias for relayer/safe functionality.
221    //! Use `polymarket_sdk::safe` or top-level re-exports instead.
222
223    pub use crate::safe::{
224        build_ctf_approve_typed_data, build_safe_create_typed_data, build_safe_tx_request,
225        build_token_approve_typed_data, build_usdc_transfer_typed_data, compute_safe_tx_digest,
226        derive_safe_address, encode_erc1155_set_approval_for_all, encode_erc20_allowance_query,
227        encode_erc20_approve, encode_erc20_transfer, pack_signature, pack_signature_for_safe_tx,
228        ApprovalStatus, BuilderApiCredentials, DeploySafeResponse, NonceType, RelayerClient,
229        RelayerConfig, SafeCreateTypedData, SafeTxDomain, SafeTxMessage, SafeTxTypedData,
230        SafeTxTypes, SignatureParams, TransactionReceipt, TransactionRequest, TransactionState,
231        TransactionType, CONDITIONAL_TOKENS_ADDRESS, CTF_EXCHANGE_ADDRESS, EXCHANGE_ADDRESS,
232        NATIVE_USDC_CONTRACT_ADDRESS, NEG_RISK_CTF_EXCHANGE_ADDRESS, SAFE_FACTORY,
233        SAFE_INIT_CODE_HASH, USDC_CONTRACT_ADDRESS,
234    };
235}
236
237/// Backward-compatible alias for `core` error types
238pub mod errors {
239    //! Backward-compatible module alias for error types.
240    //! Use `polymarket_sdk::core` or top-level re-exports instead.
241    pub use crate::core::{
242        AuthErrorKind, Error, MarketDataErrorKind, OrderErrorKind, PolymarketError, Result,
243        StreamErrorKind,
244    };
245}