feat: migrate CLOB client to V2-only trading

This commit is contained in:
floor-licker
2026-04-24 12:48:30 -03:00
parent 0ad1915d2a
commit e78ae17286
24 changed files with 1281 additions and 463 deletions
+38 -8
View File
@@ -5,7 +5,7 @@
use crate::errors::{PolyfillError, Result};
use crate::types::ApiCredentials;
use alloy_primitives::{hex::encode_prefixed, Address, U256};
use alloy_primitives::{hex::encode_prefixed, Address, B256, U256};
use alloy_signer::SignerSync;
use alloy_signer_local::PrivateKeySigner;
use alloy_sol_types::{eip712_domain, sol};
@@ -42,18 +42,34 @@ sol! {
uint256 salt;
address maker;
address signer;
address taker;
uint256 tokenId;
uint256 makerAmount;
uint256 takerAmount;
uint256 expiration;
uint256 nonce;
uint256 feeRateBps;
uint8 side;
uint8 signatureType;
uint256 timestamp;
bytes32 metadata;
bytes32 builder;
}
}
/// V2 order signing payload. The REST body still carries `expiration`, but the EIP-712 payload
/// follows the V2 exchange struct.
#[derive(Clone)]
pub struct SignedOrderMessage {
pub salt: U256,
pub maker: Address,
pub signer: Address,
pub token_id: U256,
pub maker_amount: U256,
pub taker_amount: U256,
pub side: u8,
pub signature_type: u8,
pub timestamp: U256,
pub metadata: B256,
pub builder: B256,
}
/// Get current Unix timestamp in seconds
pub fn get_current_unix_time_secs() -> u64 {
SystemTime::now()
@@ -94,13 +110,27 @@ pub fn sign_clob_auth_message(
/// Sign order message using EIP-712
pub fn sign_order_message(
signer: &PrivateKeySigner,
order: Order,
order: SignedOrderMessage,
chain_id: u64,
verifying_contract: Address,
) -> Result<String> {
let order = Order {
salt: order.salt,
maker: order.maker,
signer: order.signer,
tokenId: order.token_id,
makerAmount: order.maker_amount,
takerAmount: order.taker_amount,
side: order.side,
signatureType: order.signature_type,
timestamp: order.timestamp,
metadata: order.metadata,
builder: order.builder,
};
let domain = eip712_domain!(
name: "Polymarket CTF Exchange",
version: "1",
version: "2",
chain_id: chain_id,
verifying_contract: verifying_contract,
);
@@ -335,7 +365,7 @@ mod tests {
passphrase: "test_passphrase".to_string(),
};
let result = create_l2_headers::<String>(&signer, &api_creds, "/test", "GET", None);
let result = create_l2_headers::<String>(&signer, &api_creds, "GET", "/test", None);
assert!(result.is_ok());
let headers = result.unwrap();
+505 -251
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -101,14 +101,14 @@ mod tests {
#[tokio::test]
async fn test_connection_manager_creation() {
let client = reqwest::ClientBuilder::new().no_proxy().build().unwrap();
let manager = ConnectionManager::new(client, "https://clob.polymarket.com".to_string());
let manager = ConnectionManager::new(client, "https://clob-v2.polymarket.com".to_string());
assert!(!manager.is_running());
}
#[tokio::test]
async fn test_keepalive_start_stop() {
let client = reqwest::ClientBuilder::new().no_proxy().build().unwrap();
let manager = ConnectionManager::new(client, "https://clob.polymarket.com".to_string());
let manager = ConnectionManager::new(client, "https://clob-v2.polymarket.com".to_string());
manager.start_keepalive(Duration::from_secs(30)).await;
tokio::time::sleep(Duration::from_millis(100)).await;
+3 -3
View File
@@ -105,7 +105,7 @@ mod tests {
#[ignore = "requires external DNS/network access"]
async fn test_dns_cache_resolve() {
let cache = DnsCache::new().await.unwrap();
let ips = cache.resolve("clob.polymarket.com").await.unwrap();
let ips = cache.resolve("clob-v2.polymarket.com").await.unwrap();
assert!(!ips.is_empty());
}
@@ -113,7 +113,7 @@ mod tests {
#[ignore = "requires external DNS/network access"]
async fn test_dns_cache_prewarm() {
let cache = DnsCache::new().await.unwrap();
cache.prewarm("clob.polymarket.com").await.unwrap();
cache.prewarm("clob-v2.polymarket.com").await.unwrap();
assert_eq!(cache.cache_size().await, 1);
}
@@ -121,7 +121,7 @@ mod tests {
#[ignore = "requires external DNS/network access"]
async fn test_dns_cache_clear() {
let cache = DnsCache::new().await.unwrap();
cache.prewarm("clob.polymarket.com").await.unwrap();
cache.prewarm("clob-v2.polymarket.com").await.unwrap();
cache.clear().await;
assert_eq!(cache.cache_size().await, 0);
}
+19 -14
View File
@@ -13,22 +13,27 @@
//! # Quick Start
//!
//! ```rust,no_run
//! use polyfill_rs::{ClobClient, OrderArgs, Side};
//! use polyfill_rs::{ClientConfig, ClobClient, OrderArgs, Side};
//! use rust_decimal::Decimal;
//! use std::str::FromStr;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create client (compatible with polymarket-rs-client)
//! let mut client = ClobClient::with_l1_headers(
//! "https://clob.polymarket.com",
//! "your_private_key",
//! 137,
//! );
//! let bootstrap = ClobClient::from_config(ClientConfig {
//! base_url: "https://clob-v2.polymarket.com".to_string(),
//! chain: 137,
//! private_key: Some("your_private_key".to_string()),
//! ..ClientConfig::default()
//! })?;
//!
//! // Get API credentials
//! let api_creds = client.create_or_derive_api_key(None).await.unwrap();
//! client.set_api_creds(api_creds);
//! let api_creds = bootstrap.create_or_derive_api_key(None).await?;
//! let client = ClobClient::from_config(ClientConfig {
//! base_url: "https://clob-v2.polymarket.com".to_string(),
//! chain: 137,
//! private_key: Some("your_private_key".to_string()),
//! api_credentials: Some(api_creds),
//! ..ClientConfig::default()
//! })?;
//!
//! // Create and post order
//! let order_args = OrderArgs::new(
@@ -38,7 +43,7 @@
//! Side::BUY,
//! );
//!
//! let result = client.create_and_post_order(&order_args).await.unwrap();
//! let result = client.create_and_post_order(&order_args, None, None).await?;
//! println!("Order posted: {:?}", result);
//!
//! Ok(())
@@ -54,7 +59,7 @@
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a basic client
//! let client = ClobClient::new("https://clob.polymarket.com");
//! let client = ClobClient::new("https://clob-v2.polymarket.com");
//!
//! // Get market data
//! let markets = client.get_sampling_markets(None).await.unwrap();
@@ -72,7 +77,7 @@ use tracing::info;
// Global constants
pub const DEFAULT_CHAIN_ID: u64 = 137; // Polygon
pub const DEFAULT_BASE_URL: &str = "https://clob.polymarket.com";
pub const DEFAULT_BASE_URL: &str = "https://clob-v2.polymarket.com";
pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
pub const DEFAULT_MAX_RETRIES: u32 = 3;
pub const DEFAULT_RATE_LIMIT_RPS: u32 = 100;
@@ -152,7 +157,7 @@ pub use crate::types::{
pub use crate::client::{ClobClient, PolyfillClient};
// Re-export compatibility types (for easy migration from polymarket-rs-client)
pub use crate::client::OrderArgs;
pub use crate::types::OrderArgs;
// Re-export error types
pub use crate::errors::{PolyfillError, Result};
+361 -59
View File
@@ -3,20 +3,23 @@
//! This module handles the complex process of creating and signing orders
//! for the Polymarket CLOB, including EIP-712 signature generation.
use crate::auth::sign_order_message;
use crate::client::OrderArgs;
use crate::auth::{sign_order_message, SignedOrderMessage};
use crate::errors::{PolyfillError, Result};
use crate::types::{ExtraOrderArgs, MarketOrderArgs, OrderOptions, Side, SignedOrderRequest};
use alloy_primitives::{Address, U256};
use crate::types::{CreateOrderOptions, MarketOrderArgs, OrderArgs, OrderType, Side, SignedOrderRequest};
use alloy_primitives::{Address, B256, U256};
use alloy_signer_local::PrivateKeySigner;
use rand::Rng;
use rust_decimal::Decimal;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
use rust_decimal::RoundingStrategy::{AwayFromZero, MidpointTowardZero, ToZero};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};
pub const BYTES32_ZERO: &str =
"0x0000000000000000000000000000000000000000000000000000000000000000";
/// Signature types for orders
#[derive(Copy, Clone)]
pub enum SigType {
@@ -91,13 +94,13 @@ static ROUNDING_CONFIG: LazyLock<HashMap<Decimal, RoundConfig>> = LazyLock::new(
pub fn get_contract_config(chain_id: u64, neg_risk: bool) -> Option<ContractConfig> {
match (chain_id, neg_risk) {
(137, false) => Some(ContractConfig {
exchange: "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E".to_string(),
collateral: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174".to_string(),
exchange: "0xE111180000d2663C0091e4f400237545B87B996B".to_string(),
collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".to_string(),
conditional_tokens: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045".to_string(),
}),
(137, true) => Some(ContractConfig {
exchange: "0xC5d563A36AE78145C45a50134d48A1215220f80a".to_string(),
collateral: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174".to_string(),
exchange: "0xe2222d279d744050d28e00520010520000310F59".to_string(),
collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".to_string(),
conditional_tokens: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045".to_string(),
}),
_ => None,
@@ -124,6 +127,90 @@ fn decimal_to_token_u32(amt: Decimal) -> u32 {
amt.try_into().expect("Couldn't round decimal to integer")
}
fn parse_round_config(tick_size: Decimal) -> Result<&'static RoundConfig> {
ROUNDING_CONFIG
.get(&tick_size)
.ok_or_else(|| PolyfillError::validation(format!("Unsupported tick size {tick_size}")))
}
fn validate_bytes32_hex(field: &str, value: &str) -> Result<()> {
if value == BYTES32_ZERO {
return Ok(());
}
if !value.starts_with("0x") {
return Err(PolyfillError::validation(format!(
"{field} must be a 0x-prefixed 32-byte hex string"
)));
}
if value.len() != 66 {
return Err(PolyfillError::validation(format!(
"{field} must be exactly 32 bytes (64 hex chars)"
)));
}
if !value
.as_bytes()
.iter()
.skip(2)
.all(|byte| byte.is_ascii_hexdigit())
{
return Err(PolyfillError::validation(format!(
"{field} must contain only hexadecimal characters"
)));
}
Ok(())
}
fn normalize_optional_bytes32(field: &str, value: Option<&str>) -> Result<String> {
let value = value.unwrap_or(BYTES32_ZERO);
validate_bytes32_hex(field, value)?;
Ok(value.to_string())
}
pub fn adjust_buy_amount_for_fees(
amount: Decimal,
price: Decimal,
user_usdc_balance: Decimal,
fee_rate: Decimal,
fee_exponent: u32,
builder_taker_fee_rate_bps: Decimal,
) -> Result<Decimal> {
let price_f64 = price
.to_f64()
.ok_or_else(|| PolyfillError::validation(format!("Invalid price {price}")))?;
let amount_f64 = amount
.to_f64()
.ok_or_else(|| PolyfillError::validation(format!("Invalid amount {amount}")))?;
let user_balance_f64 = user_usdc_balance.to_f64().ok_or_else(|| {
PolyfillError::validation(format!("Invalid user_usdc_balance {user_usdc_balance}"))
})?;
let fee_rate_f64 = fee_rate
.to_f64()
.ok_or_else(|| PolyfillError::validation(format!("Invalid fee rate {fee_rate}")))?;
let builder_rate_f64 = builder_taker_fee_rate_bps
.to_f64()
.ok_or_else(|| PolyfillError::validation(format!(
"Invalid builder taker fee rate {builder_taker_fee_rate_bps}"
)))?
/ 10_000.0;
let platform_fee_rate = fee_rate_f64 * (price_f64 * (1.0 - price_f64)).powi(fee_exponent as i32);
let platform_fee = (amount_f64 / price_f64) * platform_fee_rate;
let total_cost = amount_f64 + platform_fee + amount_f64 * builder_rate_f64;
let adjusted = if user_balance_f64 <= total_cost {
user_balance_f64 / (1.0 + platform_fee_rate / price_f64 + builder_rate_f64)
} else {
amount_f64
};
Decimal::from_f64(adjusted)
.ok_or_else(|| PolyfillError::validation("Adjusted market buy amount is out of range"))
}
impl OrderBuilder {
/// Create a new order builder
pub fn new(
@@ -193,20 +280,33 @@ impl OrderBuilder {
/// Get order amounts for a market order
fn get_market_order_amounts(
&self,
side: Side,
amount: Decimal,
price: Decimal,
round_config: &RoundConfig,
) -> (u32, u32) {
let raw_maker_amt = amount.round_dp_with_strategy(round_config.size, ToZero);
let raw_price = price.round_dp_with_strategy(round_config.price, MidpointTowardZero);
let raw_taker_amt = raw_maker_amt / raw_price;
let raw_taker_amt = self.fix_amount_rounding(raw_taker_amt, round_config);
match side {
Side::BUY => {
let raw_maker_amt = amount.round_dp_with_strategy(round_config.size, ToZero);
let raw_taker_amt = self.fix_amount_rounding(raw_maker_amt / raw_price, round_config);
(
decimal_to_token_u32(raw_maker_amt),
decimal_to_token_u32(raw_taker_amt),
)
(
decimal_to_token_u32(raw_maker_amt),
decimal_to_token_u32(raw_taker_amt),
)
},
Side::SELL => {
let raw_maker_amt = amount.round_dp_with_strategy(round_config.size, ToZero);
let raw_taker_amt = self.fix_amount_rounding(raw_maker_amt * raw_price, round_config);
(
decimal_to_token_u32(raw_maker_amt),
decimal_to_token_u32(raw_taker_amt),
)
},
}
}
/// Calculate market price from order book levels
@@ -214,23 +314,33 @@ impl OrderBuilder {
&self,
positions: &[crate::types::BookLevel],
amount_to_match: Decimal,
side: Side,
order_type: OrderType,
) -> Result<Decimal> {
let mut sum = Decimal::ZERO;
let mut last_price = None;
for level in positions {
sum += level.size * level.price;
sum += match side {
Side::BUY => level.size * level.price,
Side::SELL => level.size,
};
last_price = Some(level.price);
if sum >= amount_to_match {
return Ok(level.price);
}
}
Err(PolyfillError::order(
format!(
"Not enough liquidity to create market order with amount {}",
amount_to_match
),
crate::errors::OrderErrorKind::InsufficientBalance,
))
match (order_type, last_price) {
(OrderType::FAK, Some(price)) => Ok(price),
_ => Err(PolyfillError::order(
format!(
"Not enough liquidity to create market order with amount {}",
amount_to_match
),
crate::errors::OrderErrorKind::InsufficientBalance,
)),
}
}
/// Create a market order
@@ -239,15 +349,21 @@ impl OrderBuilder {
chain_id: u64,
order_args: &MarketOrderArgs,
price: Decimal,
extras: &ExtraOrderArgs,
options: &OrderOptions,
options: &CreateOrderOptions,
) -> Result<SignedOrderRequest> {
let tick_size = options
.tick_size
.ok_or_else(|| PolyfillError::validation("Cannot create order without tick size"))?;
if !matches!(order_args.order_type, OrderType::FOK | OrderType::FAK) {
return Err(PolyfillError::validation(
"Market orders only support FOK and FAK order types",
));
}
let tick_size = options.tick_size.ok_or_else(|| {
PolyfillError::validation("Cannot create order without tick size")
})?;
let round_config = parse_round_config(tick_size)?;
let (maker_amount, taker_amount) =
self.get_market_order_amounts(order_args.amount, price, &ROUNDING_CONFIG[&tick_size]);
self.get_market_order_amounts(order_args.side, order_args.amount, price, round_config);
let neg_risk = options
.neg_risk
@@ -262,13 +378,14 @@ impl OrderBuilder {
self.build_signed_order(
order_args.token_id.clone(),
Side::BUY,
order_args.side,
chain_id,
exchange_address,
maker_amount,
taker_amount,
0,
extras,
order_args.builder_code.as_deref(),
order_args.metadata.as_deref(),
)
}
@@ -277,19 +394,18 @@ impl OrderBuilder {
&self,
chain_id: u64,
order_args: &OrderArgs,
expiration: u64,
extras: &ExtraOrderArgs,
options: &OrderOptions,
options: &CreateOrderOptions,
) -> Result<SignedOrderRequest> {
let tick_size = options
.tick_size
.ok_or_else(|| PolyfillError::validation("Cannot create order without tick size"))?;
let tick_size = options.tick_size.ok_or_else(|| {
PolyfillError::validation("Cannot create order without tick size")
})?;
let round_config = parse_round_config(tick_size)?;
let (maker_amount, taker_amount) = self.get_order_amounts(
order_args.side,
order_args.size,
order_args.price,
&ROUNDING_CONFIG[&tick_size],
round_config,
);
let neg_risk = options
@@ -310,8 +426,9 @@ impl OrderBuilder {
exchange_address,
maker_amount,
taker_amount,
expiration,
extras,
order_args.expiration.unwrap_or(0),
order_args.builder_code.as_deref(),
order_args.metadata.as_deref(),
)
}
@@ -326,28 +443,36 @@ impl OrderBuilder {
maker_amount: u32,
taker_amount: u32,
expiration: u64,
extras: &ExtraOrderArgs,
builder_code: Option<&str>,
metadata: Option<&str>,
) -> Result<SignedOrderRequest> {
let seed = generate_seed();
let taker_address = Address::from_str(&extras.taker)
.map_err(|e| PolyfillError::validation(format!("Invalid taker address: {}", e)))?;
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
.as_millis();
let u256_token_id = U256::from_str_radix(&token_id, 10)
.map_err(|e| PolyfillError::validation(format!("Incorrect tokenId format: {}", e)))?;
let builder = normalize_optional_bytes32("builder_code", builder_code)?;
let metadata = normalize_optional_bytes32("metadata", metadata)?;
let order = crate::auth::Order {
let order = SignedOrderMessage {
salt: U256::from(seed),
maker: self.funder,
signer: self.signer.address(),
taker: taker_address,
tokenId: u256_token_id,
makerAmount: U256::from(maker_amount),
takerAmount: U256::from(taker_amount),
expiration: U256::from(expiration),
nonce: extras.nonce,
feeRateBps: U256::from(extras.fee_rate_bps),
token_id: u256_token_id,
maker_amount: U256::from(maker_amount),
taker_amount: U256::from(taker_amount),
side: side as u8,
signatureType: self.sig_type as u8,
signature_type: self.sig_type as u8,
timestamp: U256::from(timestamp),
metadata: B256::from_str(&metadata).map_err(|e| {
PolyfillError::validation(format!("Invalid metadata bytes32 value: {e}"))
})?,
builder: B256::from_str(&builder).map_err(|e| {
PolyfillError::validation(format!("Invalid builder_code bytes32 value: {e}"))
})?,
};
let signature = sign_order_message(&self.signer, order, chain_id, exchange)?;
@@ -356,15 +481,15 @@ impl OrderBuilder {
salt: seed,
maker: self.funder.to_checksum(None),
signer: self.signer.address().to_checksum(None),
taker: taker_address.to_checksum(None),
token_id,
maker_amount: maker_amount.to_string(),
taker_amount: taker_amount.to_string(),
expiration: expiration.to_string(),
nonce: extras.nonce.to_string(),
fee_rate_bps: extras.fee_rate_bps.to_string(),
side: side.as_str().to_string(),
signature_type: self.sig_type as u8,
timestamp: timestamp.to_string(),
metadata,
builder,
signature,
})
}
@@ -373,6 +498,16 @@ impl OrderBuilder {
#[cfg(test)]
mod tests {
use super::*;
use alloy_signer_local::PrivateKeySigner;
use serde_json::Value;
fn test_builder() -> OrderBuilder {
let signer: PrivateKeySigner =
"0x1234567890123456789012345678901234567890123456789012345678901234"
.parse()
.expect("valid private key");
OrderBuilder::new(signer, None, None)
}
#[test]
fn test_decimal_to_token_u32() {
@@ -405,18 +540,185 @@ mod tests {
#[test]
fn test_get_contract_config() {
// Test Polygon mainnet
let config = get_contract_config(137, false);
assert!(config.is_some());
let config = get_contract_config(137, false).expect("polygon config");
assert_eq!(config.exchange, "0xE111180000d2663C0091e4f400237545B87B996B");
assert_eq!(config.collateral, "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB");
assert_eq!(
config.conditional_tokens,
"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"
);
// Test with neg risk
let config_neg = get_contract_config(137, true);
assert!(config_neg.is_some());
let config_neg = get_contract_config(137, true).expect("neg risk polygon config");
assert_eq!(
config_neg.exchange,
"0xe2222d279d744050d28e00520010520000310F59"
);
assert_eq!(
config_neg.collateral,
"0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"
);
// Test unsupported chain
let config_unsupported = get_contract_config(999, false);
assert!(config_unsupported.is_none());
}
#[test]
fn test_normalize_optional_bytes32_defaults_to_zero() {
assert_eq!(
normalize_optional_bytes32("builder_code", None).unwrap(),
BYTES32_ZERO
);
}
#[test]
fn test_normalize_optional_bytes32_rejects_invalid_hex() {
let err = normalize_optional_bytes32("metadata", Some("deadbeef")).unwrap_err();
assert!(matches!(err, PolyfillError::Validation { .. }));
}
#[test]
fn test_create_order_serializes_v2_fields_without_legacy_fields() {
let builder = test_builder();
let order = builder
.create_order(
137,
&OrderArgs {
token_id: "123456".to_string(),
price: Decimal::from_str("0.45").unwrap(),
size: Decimal::from_str("12.34").unwrap(),
side: Side::BUY,
expiration: Some(1_900_000_000),
builder_code: Some(BYTES32_ZERO.to_string()),
metadata: None,
},
&CreateOrderOptions {
tick_size: Some(Decimal::from_str("0.01").unwrap()),
neg_risk: Some(false),
},
)
.unwrap();
let serialized = serde_json::to_value(&order).unwrap();
let object = serialized.as_object().unwrap();
assert!(object.contains_key("timestamp"));
assert!(object.contains_key("metadata"));
assert!(object.contains_key("builder"));
assert!(object.contains_key("expiration"));
assert!(!object.contains_key("taker"));
assert!(!object.contains_key("nonce"));
assert!(!object.contains_key("feeRateBps"));
assert_eq!(order.builder, BYTES32_ZERO);
assert_eq!(order.metadata, BYTES32_ZERO);
}
#[test]
fn test_create_market_order_supports_fak() {
let builder = test_builder();
let order = builder
.create_market_order(
137,
&MarketOrderArgs {
token_id: "123456".to_string(),
amount: Decimal::from_str("10.0").unwrap(),
side: Side::BUY,
order_type: OrderType::FAK,
price_limit: None,
user_usdc_balance: None,
builder_code: None,
metadata: None,
},
Decimal::from_str("0.25").unwrap(),
&CreateOrderOptions {
tick_size: Some(Decimal::from_str("0.01").unwrap()),
neg_risk: Some(false),
},
)
.unwrap();
assert_eq!(order.side, "BUY");
assert!(!order.timestamp.is_empty());
}
#[test]
fn test_market_order_amounts_differ_for_buy_and_sell() {
let builder = test_builder();
let round_config = parse_round_config(Decimal::from_str("0.01").unwrap()).unwrap();
let (buy_maker, buy_taker) = builder.get_market_order_amounts(
Side::BUY,
Decimal::from_str("10").unwrap(),
Decimal::from_str("0.25").unwrap(),
round_config,
);
let (sell_maker, sell_taker) = builder.get_market_order_amounts(
Side::SELL,
Decimal::from_str("10").unwrap(),
Decimal::from_str("0.25").unwrap(),
round_config,
);
assert_eq!(buy_maker, 10_000_000);
assert_eq!(buy_taker, 40_000_000);
assert_eq!(sell_maker, 10_000_000);
assert_eq!(sell_taker, 2_500_000);
}
#[test]
fn test_calculate_market_price_returns_last_level_for_fak() {
let builder = test_builder();
let levels = vec![
crate::types::BookLevel {
price: Decimal::from_str("0.40").unwrap(),
size: Decimal::from_str("2.0").unwrap(),
},
crate::types::BookLevel {
price: Decimal::from_str("0.45").unwrap(),
size: Decimal::from_str("1.0").unwrap(),
},
];
let price = builder
.calculate_market_price(
&levels,
Decimal::from_str("10.0").unwrap(),
Side::SELL,
OrderType::FAK,
)
.unwrap();
assert_eq!(price, Decimal::from_str("0.45").unwrap());
}
#[test]
fn test_signed_order_json_uses_camel_case_wire_shape() {
let builder = test_builder();
let order = builder
.create_order(
137,
&OrderArgs {
token_id: "123456".to_string(),
price: Decimal::from_str("0.55").unwrap(),
size: Decimal::from_str("5.0").unwrap(),
side: Side::SELL,
expiration: Some(1_900_000_000),
builder_code: None,
metadata: Some(BYTES32_ZERO.to_string()),
},
&CreateOrderOptions {
tick_size: Some(Decimal::from_str("0.01").unwrap()),
neg_risk: Some(true),
},
)
.unwrap();
let json = serde_json::to_value(order).unwrap();
assert!(matches!(json.get("tokenId"), Some(Value::String(_))));
assert!(matches!(json.get("makerAmount"), Some(Value::String(_))));
assert!(matches!(json.get("takerAmount"), Some(Value::String(_))));
assert!(matches!(json.get("signatureType"), Some(Value::Number(_))));
}
#[test]
fn test_seed_generation_uniqueness() {
let mut seeds = std::collections::HashSet::new();
+174 -39
View File
@@ -3,7 +3,7 @@
//! This module defines all the stable public types used throughout the client.
//! These types are optimized for latency-sensitive trading environments.
use alloy_primitives::{Address, U256};
use alloy_primitives::Address;
use chrono::{DateTime, Utc};
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
@@ -215,6 +215,7 @@ pub enum OrderType {
GTC,
FOK,
GTD,
FAK,
}
impl OrderType {
@@ -223,6 +224,7 @@ impl OrderType {
OrderType::GTC => "GTC",
OrderType::FOK => "FOK",
OrderType::GTD => "GTD",
OrderType::FAK => "FAK",
}
}
}
@@ -494,37 +496,97 @@ pub struct ApiCredentials {
pub passphrase: String,
}
/// Configuration for order creation
#[derive(Debug, Clone)]
pub struct OrderOptions {
pub tick_size: Option<Decimal>,
pub neg_risk: Option<bool>,
pub fee_rate_bps: Option<u32>,
/// Limit order arguments for V2 order creation.
#[derive(Debug, Clone, PartialEq)]
pub struct OrderArgs {
pub token_id: String,
pub price: Decimal,
pub size: Decimal,
pub side: Side,
pub expiration: Option<u64>,
pub builder_code: Option<String>,
pub metadata: Option<String>,
}
/// Extra arguments for order creation
#[derive(Debug, Clone)]
pub struct ExtraOrderArgs {
pub fee_rate_bps: u32,
pub nonce: U256,
pub taker: String,
}
impl Default for ExtraOrderArgs {
fn default() -> Self {
impl OrderArgs {
pub fn new(token_id: &str, price: Decimal, size: Decimal, side: Side) -> Self {
Self {
fee_rate_bps: 0,
nonce: U256::ZERO,
taker: "0x0000000000000000000000000000000000000000".to_string(),
token_id: token_id.to_string(),
price,
size,
side,
expiration: None,
builder_code: None,
metadata: None,
}
}
}
/// Market order arguments
#[derive(Debug, Clone)]
impl Default for OrderArgs {
fn default() -> Self {
Self {
token_id: String::new(),
price: Decimal::ZERO,
size: Decimal::ZERO,
side: Side::BUY,
expiration: None,
builder_code: None,
metadata: None,
}
}
}
/// Market order arguments for V2 order creation.
#[derive(Debug, Clone, PartialEq)]
pub struct MarketOrderArgs {
pub token_id: String,
pub amount: Decimal,
pub side: Side,
pub order_type: OrderType,
pub price_limit: Option<Decimal>,
pub user_usdc_balance: Option<Decimal>,
pub builder_code: Option<String>,
pub metadata: Option<String>,
}
impl MarketOrderArgs {
pub fn new(token_id: &str, amount: Decimal, side: Side, order_type: OrderType) -> Self {
Self {
token_id: token_id.to_string(),
amount,
side,
order_type,
price_limit: None,
user_usdc_balance: None,
builder_code: None,
metadata: None,
}
}
}
/// Options used while constructing an order.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct CreateOrderOptions {
pub tick_size: Option<Decimal>,
pub neg_risk: Option<bool>,
}
/// Options used while posting a signed order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PostOrderOptions {
pub order_type: OrderType,
pub post_only: bool,
pub defer_exec: bool,
}
impl Default for PostOrderOptions {
fn default() -> Self {
Self {
order_type: OrderType::GTC,
post_only: false,
defer_exec: false,
}
}
}
/// Signed order request ready for submission
@@ -534,15 +596,15 @@ pub struct SignedOrderRequest {
pub salt: u64,
pub maker: String,
pub signer: String,
pub taker: String,
pub token_id: String,
pub maker_amount: String,
pub taker_amount: String,
pub expiration: String,
pub nonce: String,
pub fee_rate_bps: String,
pub side: String,
pub signature_type: u8,
pub timestamp: String,
pub metadata: String,
pub builder: String,
pub signature: String,
}
@@ -553,18 +615,95 @@ pub struct PostOrder {
pub order: SignedOrderRequest,
pub owner: String,
pub order_type: OrderType,
pub post_only: bool,
pub defer_exec: bool,
}
impl PostOrder {
pub fn new(order: SignedOrderRequest, owner: String, order_type: OrderType) -> Self {
pub fn new(order: SignedOrderRequest, owner: String, options: PostOrderOptions) -> Self {
Self {
order,
owner,
order_type,
order_type: options.order_type,
post_only: options.post_only,
defer_exec: options.defer_exec,
}
}
}
/// Typed response from `POST /order`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PostOrderResponse {
pub success: bool,
#[serde(rename = "orderID")]
pub order_id: String,
pub status: String,
pub making_amount: String,
pub taking_amount: String,
#[serde(default)]
pub transactions_hashes: Vec<String>,
#[serde(default)]
pub trade_ids: Vec<String>,
#[serde(default)]
pub error_msg: String,
}
/// Typed response from cancel endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrdersResponse {
#[serde(default)]
pub canceled: Vec<String>,
#[serde(default, alias = "not_canceled")]
pub not_canceled: std::collections::HashMap<String, String>,
}
/// Token info returned by `GET /clob-markets/{condition_id}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ClobTokenInfo {
pub t: String,
pub o: String,
}
/// Fee details returned by `GET /clob-markets/{condition_id}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ClobFeeDetails {
pub r: Decimal,
pub e: u32,
#[serde(default)]
pub to: bool,
}
/// CLOB market info returned by `GET /clob-markets/{condition_id}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ClobMarketInfo {
#[serde(default)]
pub gst: Option<String>,
pub r: serde_json::Value,
pub t: Vec<ClobTokenInfo>,
#[serde(deserialize_with = "crate::decode::deserializers::decimal_from_string")]
pub mos: Decimal,
#[serde(deserialize_with = "crate::decode::deserializers::decimal_from_string")]
pub mts: Decimal,
#[serde(deserialize_with = "crate::decode::deserializers::decimal_from_string")]
pub mbf: Decimal,
#[serde(deserialize_with = "crate::decode::deserializers::decimal_from_string")]
pub tbf: Decimal,
#[serde(default)]
pub rfqe: bool,
#[serde(default)]
pub itode: bool,
#[serde(default)]
pub ibce: bool,
#[serde(default)]
pub nr: Option<bool>,
#[serde(default)]
pub fd: Option<ClobFeeDetails>,
#[serde(default, deserialize_with = "crate::decode::deserializers::optional_number_from_string")]
pub oas: Option<u64>,
}
/// Market information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Market {
@@ -630,15 +769,13 @@ pub struct ClientConfig {
/// Base URL for the API
pub base_url: String,
/// Chain ID for the network
pub chain_id: u64,
pub chain: u64,
/// Private key for signing (optional)
pub private_key: Option<String>,
/// API credentials (optional)
pub api_credentials: Option<ApiCredentials>,
/// Maximum slippage tolerance
pub max_slippage: Option<Decimal>,
/// Fee rate in basis points
pub fee_rate: Option<Decimal>,
/// Builder code applied to orders when none is specified on the order itself.
pub builder_code: Option<String>,
/// Request timeout
pub timeout: Option<std::time::Duration>,
/// Maximum number of connections
@@ -648,14 +785,13 @@ pub struct ClientConfig {
impl Default for ClientConfig {
fn default() -> Self {
Self {
base_url: "https://clob.polymarket.com".to_string(),
chain_id: 137, // Polygon mainnet
base_url: "https://clob-v2.polymarket.com".to_string(),
chain: 137, // Polygon mainnet
private_key: None,
api_credentials: None,
builder_code: None,
timeout: Some(std::time::Duration::from_secs(30)),
max_connections: Some(100),
max_slippage: None,
fee_rate: None,
}
}
}
@@ -1374,7 +1510,8 @@ pub struct Rewards {
/// Fee rate in basis points for a given token.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeeRateResponse {
pub fee_rate_bps: u32,
#[serde(alias = "fee_rate_bps")]
pub base_fee: u32,
}
/// Create RFQ request (Requester).
@@ -1655,5 +1792,3 @@ pub type Result<T> = std::result::Result<T, crate::errors::PolyfillError>;
// Type aliases for 100% compatibility with baseline implementation
pub type ApiCreds = ApiCredentials;
pub type CreateOrderOptions = OrderOptions;
pub type OrderArgs = OrderRequest;