Skip to main content

polymarket_rs_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    ActivityQuery, ActivitySortBy, ActivityType, ApiCredentials, AssetType,
99    BalanceAllowanceParams, BalanceAllowanceResponse, BiggestWinner, BiggestWinnersQuery, BookLevel,
100    ClosedPosition, ConnectionStats, DataApiActivity, DataApiPosition, DataApiTrade, DataApiTrader,
101    Event, EventMarket, EventTag, LeaderboardEntry, ListParams, Market, MarketOrderArgs, NewOrder,
102    NewOrderData, OrderOptions, OrderType, PaginationParams, PositionSortBy, PositionsQuery,
103    PublicProfile, PublicProfileUser, SearchEvent, SearchProfile, SearchRequest, SearchResponse,
104    SearchTag, Side, SignedOrderRequest, SortDirection, Tag, Token, TraderProfile,
105};
106
107#[cfg(feature = "auth")]
108pub use types::ExtraOrderArgs;
109
110// ============================================================================
111// Auth Re-exports
112// ============================================================================
113
114#[cfg(feature = "auth")]
115pub use auth::{
116    build_clob_auth_typed_data, build_hmac_signature, build_hmac_signature_from_string,
117    create_l1_headers, create_l2_headers, create_l2_headers_with_address,
118    create_l2_headers_with_body_string, get_current_unix_time_secs, sign_clob_auth_message,
119    sign_order_message, BuilderApiKeyCreds, BuilderSigner, ClobAuth, Headers, Order,
120};
121
122// ============================================================================
123// Client Re-exports
124// ============================================================================
125
126#[cfg(feature = "client")]
127pub use client::{
128    ApiKeyResponse, CancelResponse, ClobClient, ClobConfig, DataClient, DataConfig,
129    DeriveApiKeyResponse, GammaClient, GammaConfig, OpenOrder, OrderResponse, PaginatedResponse,
130};
131
132// ============================================================================
133// Order Re-exports
134// ============================================================================
135
136#[cfg(feature = "order")]
137pub use order::{get_contract_config, ContractConfig, OrderArgs, OrderBuilder, SigType};
138
139// ============================================================================
140// Stream Re-exports
141// ============================================================================
142
143#[cfg(feature = "stream")]
144pub use stream::{
145    LastTradeMessage, MarketBook, MarketStream, MockStream, PriceChangeEntry, PriceChangeMessage,
146    RtdsClient, RtdsConfig, RtdsEvent, RtdsMessage, RtdsSubscription, RtdsSubscriptionMessage,
147    StreamManager, StreamMessage, StreamStats, Subscription, TickSizeChangeMessage, TradePayload,
148    WebSocketStream, WssAuth, WssMarketClient, WssMarketEvent, WssStats, WssSubscription,
149    WssUserClient, WssUserEvent, WssUserOrderMessage, WssUserTradeMessage,
150};
151
152// ============================================================================
153// Safe Re-exports
154// ============================================================================
155
156#[cfg(feature = "safe")]
157pub use safe::{
158    build_ctf_approve_typed_data, build_safe_create_typed_data, build_safe_tx_request,
159    build_token_approve_typed_data, build_usdc_transfer_typed_data, compute_safe_tx_digest,
160    derive_safe_address, encode_erc1155_set_approval_for_all, encode_erc20_allowance_query,
161    encode_erc20_approve, encode_erc20_transfer, pack_signature, pack_signature_for_safe_tx,
162    ApprovalStatus, DeploySafeResponse, NonceType, RelayerClient, RelayerConfig,
163    SafeCreateTypedData, SafeTxDomain, SafeTxMessage, SafeTxTypedData, SafeTxTypes,
164    SignatureParams, TransactionReceipt, TransactionRequest, TransactionState, TransactionType,
165    CONDITIONAL_TOKENS_ADDRESS, CTF_EXCHANGE_ADDRESS, EXCHANGE_ADDRESS,
166    NATIVE_USDC_CONTRACT_ADDRESS, NEG_RISK_CTF_EXCHANGE_ADDRESS, SAFE_FACTORY, SAFE_INIT_CODE_HASH,
167    USDC_CONTRACT_ADDRESS,
168};
169
170// ============================================================================
171// Backward-compatible Module Aliases (for ride-service migration)
172// ============================================================================
173
174/// Backward-compatible alias for `client` module
175#[cfg(feature = "client")]
176pub mod clob {
177    //! Backward-compatible module alias for CLOB client.
178    //! Use `polymarket_sdk::client` or top-level re-exports instead.
179    pub use crate::client::{ClobClient, ClobConfig};
180}
181
182/// Backward-compatible alias for Gamma API client
183#[cfg(feature = "client")]
184pub mod gamma {
185    //! Backward-compatible module alias for Gamma API client.
186    //! Use `polymarket_sdk::client` or top-level re-exports instead.
187    pub use crate::client::{GammaClient, GammaConfig};
188}
189
190/// Backward-compatible alias for Data API client
191#[cfg(feature = "client")]
192pub mod data {
193    //! Backward-compatible module alias for Data API client.
194    //! Use `polymarket_sdk::client` or top-level re-exports instead.
195    pub use crate::client::{DataClient, DataConfig};
196}
197
198/// Backward-compatible alias for `order` module
199#[cfg(feature = "order")]
200pub mod orders {
201    //! Backward-compatible module alias for order building.
202    //! Use `polymarket_sdk::order` or top-level re-exports instead.
203    pub use crate::order::{get_contract_config, ContractConfig, OrderArgs, OrderBuilder, SigType};
204}
205
206/// Backward-compatible alias for CLOB WebSocket client
207#[cfg(feature = "stream")]
208pub mod wss {
209    //! Backward-compatible module alias for CLOB WebSocket functionality.
210    //! Use `polymarket_sdk::stream` or top-level re-exports instead.
211    pub use crate::stream::{
212        LastTradeMessage, MarketBook, OrderSummary, PriceChangeEntry, PriceChangeMessage,
213        TickSizeChangeMessage, WssMarketClient, WssMarketEvent, WssStats, WssUserClient,
214        WssUserEvent, WssUserOrderMessage, WssUserTradeMessage,
215    };
216}
217
218/// Backward-compatible alias for `safe` module
219#[cfg(feature = "safe")]
220pub mod relayer {
221    //! Backward-compatible module alias for relayer/safe functionality.
222    //! Use `polymarket_sdk::safe` or top-level re-exports instead.
223
224    pub use crate::safe::{
225        build_ctf_approve_typed_data, build_safe_create_typed_data, build_safe_tx_request,
226        build_token_approve_typed_data, build_usdc_transfer_typed_data, compute_safe_tx_digest,
227        derive_safe_address, encode_erc1155_set_approval_for_all, encode_erc20_allowance_query,
228        encode_erc20_approve, encode_erc20_transfer, pack_signature, pack_signature_for_safe_tx,
229        ApprovalStatus, BuilderApiCredentials, DeploySafeResponse, NonceType, RelayerClient,
230        RelayerConfig, SafeCreateTypedData, SafeTxDomain, SafeTxMessage, SafeTxTypedData,
231        SafeTxTypes, SignatureParams, TransactionReceipt, TransactionRequest, TransactionState,
232        TransactionType, CONDITIONAL_TOKENS_ADDRESS, CTF_EXCHANGE_ADDRESS, EXCHANGE_ADDRESS,
233        NATIVE_USDC_CONTRACT_ADDRESS, NEG_RISK_CTF_EXCHANGE_ADDRESS, SAFE_FACTORY,
234        SAFE_INIT_CODE_HASH, USDC_CONTRACT_ADDRESS,
235    };
236}
237
238/// Backward-compatible alias for `core` error types
239pub mod errors {
240    //! Backward-compatible module alias for error types.
241    //! Use `polymarket_sdk::core` or top-level re-exports instead.
242    pub use crate::core::{
243        AuthErrorKind, Error, MarketDataErrorKind, OrderErrorKind, PolymarketError, Result,
244        StreamErrorKind,
245    };
246}