rs-clob-client-v2 0.2.0

Rust client for Polymarket's CLOB v2 protocol (Central Limit Order Book)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use crate::constants::{get_contract_config, COLLATERAL_TOKEN_DECIMALS};
use crate::errors::{ClobError, ClobResult};
use crate::types::{
    Chain, CreateOrderOptions, OrderSummary, OrderType, RoundConfig, Side, TickSize,
    UserMarketOrder, UserLimitOrder,
};
use crate::utilities::{decimal_places, round_down, round_normal, round_up};
use alloy_primitives::{Address, U256};
use alloy_signer_local::PrivateKeySigner;
use rs_order_utils::v2::{ExchangeOrderBuilder, OrderData, SignatureType, SignedOrder};
use std::str::FromStr;

pub fn get_rounding_config(tick_size: TickSize) -> RoundConfig {
    match tick_size {
        TickSize::ZeroPointOne => RoundConfig {
            price: 1,
            size: 2,
            amount: 3,
        },
        TickSize::ZeroPointZeroOne => RoundConfig {
            price: 2,
            size: 2,
            amount: 4,
        },
        TickSize::ZeroPointZeroZeroOne => RoundConfig {
            price: 3,
            size: 2,
            amount: 5,
        },
        TickSize::ZeroPointZeroZeroZeroOne => RoundConfig {
            price: 4,
            size: 2,
            amount: 6,
        },
    }
}

pub struct RawAmounts {
    pub side: Side,
    pub raw_maker_amt: f64,
    pub raw_taker_amt: f64,
}

pub fn get_order_raw_amounts(
    side: Side,
    size: f64,
    price: f64,
    round_config: &RoundConfig,
) -> RawAmounts {
    let raw_price = round_normal(price, round_config.price);

    match side {
        Side::Buy => {
            let raw_taker_amt = round_down(size, round_config.size);
            let mut raw_maker_amt = raw_taker_amt * raw_price;

            if decimal_places(raw_maker_amt) > round_config.amount {
                raw_maker_amt = round_up(raw_maker_amt, round_config.amount + 4);
                if decimal_places(raw_maker_amt) > round_config.amount {
                    raw_maker_amt = round_down(raw_maker_amt, round_config.amount);
                }
            }

            RawAmounts {
                side: Side::Buy,
                raw_maker_amt,
                raw_taker_amt,
            }
        }
        Side::Sell => {
            let raw_maker_amt = round_down(size, round_config.size);
            let mut raw_taker_amt = raw_maker_amt * raw_price;

            if decimal_places(raw_taker_amt) > round_config.amount {
                raw_taker_amt = round_up(raw_taker_amt, round_config.amount + 4);
                if decimal_places(raw_taker_amt) > round_config.amount {
                    raw_taker_amt = round_down(raw_taker_amt, round_config.amount);
                }
            }

            RawAmounts {
                side: Side::Sell,
                raw_maker_amt,
                raw_taker_amt,
            }
        }
    }
}

/// Polymarket API precision limits for market orders:
/// - maker_amount: max 2 decimal places
/// - taker_amount: max 4 decimal places
const MARKET_ORDER_MAKER_DECIMALS: u32 = 2;
const MARKET_ORDER_TAKER_DECIMALS: u32 = 4;

pub fn get_market_order_raw_amounts(
    side: Side,
    amount: f64,
    price: f64,
    round_config: &RoundConfig,
) -> RawAmounts {
    let raw_price = round_down(price, round_config.price);

    match side {
        Side::Buy => {
            // For buy orders: maker_amt is USDC paid, taker_amt is shares received
            // Always enforce maker precision to 2 decimals (API requirement)
            let raw_maker_amt = round_down(amount, MARKET_ORDER_MAKER_DECIMALS);
            // Calculate taker amount and enforce 4 decimal precision (API requirement)
            let raw_taker_amt = round_down(raw_maker_amt / raw_price, MARKET_ORDER_TAKER_DECIMALS);

            RawAmounts {
                side: Side::Buy,
                raw_maker_amt,
                raw_taker_amt,
            }
        }
        Side::Sell => {
            // For sell orders: maker_amt is shares sold, taker_amt is USDC received
            // Enforce maker precision to 2 decimals
            let raw_maker_amt = round_down(amount, MARKET_ORDER_MAKER_DECIMALS);
            // Calculate taker amount and enforce 4 decimal precision
            let raw_taker_amt = round_down(raw_maker_amt * raw_price, MARKET_ORDER_TAKER_DECIMALS);

            RawAmounts {
                side: Side::Sell,
                raw_maker_amt,
                raw_taker_amt,
            }
        }
    }
}

pub fn calculate_buy_market_price(
    positions: &[OrderSummary],
    amount_to_match: f64,
    order_type: OrderType,
) -> ClobResult<f64> {
    if positions.is_empty() {
        return Err(ClobError::NoMatch);
    }

    let mut sum = 0.0;

    for i in (0..positions.len()).rev() {
        let p = &positions[i];
        let price: f64 = p
            .price
            .parse()
            .map_err(|_| ClobError::Other("Invalid price in orderbook".to_string()))?;
        let size: f64 = p
            .size
            .parse()
            .map_err(|_| ClobError::Other("Invalid size in orderbook".to_string()))?;

        sum += size * price;
        if sum >= amount_to_match {
            return Ok(price);
        }
    }

    if order_type == OrderType::Fok {
        return Err(ClobError::NoMatch);
    }

    let first_price: f64 = positions[0]
        .price
        .parse()
        .map_err(|_| ClobError::Other("Invalid price in orderbook".to_string()))?;
    Ok(first_price)
}

pub fn calculate_sell_market_price(
    positions: &[OrderSummary],
    amount_to_match: f64,
    order_type: OrderType,
) -> ClobResult<f64> {
    if positions.is_empty() {
        return Err(ClobError::NoMatch);
    }

    let mut sum = 0.0;

    for i in (0..positions.len()).rev() {
        let p = &positions[i];
        let price: f64 = p
            .price
            .parse()
            .map_err(|_| ClobError::Other("Invalid price in orderbook".to_string()))?;
        let size: f64 = p
            .size
            .parse()
            .map_err(|_| ClobError::Other("Invalid size in orderbook".to_string()))?;

        sum += size;
        if sum >= amount_to_match {
            return Ok(price);
        }
    }

    if order_type == OrderType::Fok {
        return Err(ClobError::NoMatch);
    }

    let first_price: f64 = positions[0]
        .price
        .parse()
        .map_err(|_| ClobError::Other("Invalid price in orderbook".to_string()))?;
    Ok(first_price)
}

pub async fn build_order(
    signer: PrivateKeySigner,
    exchange_address: &str,
    chain_id: u64,
    order_data: OrderData,
) -> ClobResult<SignedOrder> {
    let exchange_addr = Address::from_str(exchange_address)
        .map_err(|e| ClobError::Other(format!("Invalid exchange address: {}", e)))?;

    let builder = ExchangeOrderBuilder::new(exchange_addr, chain_id, signer, None);

    builder
        .build_signed_order(order_data)
        .await
        .map_err(|e| ClobError::SigningError(e.to_string()))
}

fn parse_units(value: f64, decimals: u8) -> U256 {
    let multiplier = 10_f64.powi(decimals as i32);
    let raw_value = (value * multiplier).round() as u128;
    U256::from(raw_value)
}

/// Parse units for market order maker amount (max 2 decimals precision)
/// Result must be a multiple of 10000 (since USDC has 6 decimals, 2 decimal precision = 10^(6-2) = 10000)
fn parse_market_maker_units(value: f64, decimals: u8) -> U256 {
    let multiplier = 10_f64.powi(decimals as i32);
    let raw_value = (value * multiplier).round() as u128;
    // Align to 10000 (for 2 decimal precision with 6 decimal token)
    let alignment = 10_u128.pow((decimals - 2) as u32); // 10^4 = 10000
    let aligned_value = (raw_value / alignment) * alignment;
    U256::from(aligned_value)
}

/// Parse units for market order taker amount (max 4 decimals precision)
/// Result must be a multiple of 100 (since USDC has 6 decimals, 4 decimal precision = 10^(6-4) = 100)
fn parse_market_taker_units(value: f64, decimals: u8) -> U256 {
    let multiplier = 10_f64.powi(decimals as i32);
    let raw_value = (value * multiplier).round() as u128;
    // Align to 100 (for 4 decimal precision with 6 decimal token)
    let alignment = 10_u128.pow((decimals - 4) as u32); // 10^2 = 100
    let aligned_value = (raw_value / alignment) * alignment;
    U256::from(aligned_value)
}

pub fn build_limit_order_creation_args(
    signer_address: Address,
    maker: Address,
    signature_type: SignatureType,
    user_limit_order: &UserLimitOrder,
    round_config: &RoundConfig,
) -> ClobResult<OrderData> {
    let raw_amounts = get_order_raw_amounts(
        user_limit_order.side,
        user_limit_order.size,
        user_limit_order.price,
        round_config,
    );

    let maker_amount = parse_units(raw_amounts.raw_maker_amt, COLLATERAL_TOKEN_DECIMALS);
    let taker_amount = parse_units(raw_amounts.raw_taker_amt, COLLATERAL_TOKEN_DECIMALS);

    let token_id = U256::from_str(&user_limit_order.token_id)
        .map_err(|e| ClobError::Other(format!("Invalid token_id: {}", e)))?;

    let side = match raw_amounts.side {
        Side::Buy => rs_order_utils::Side::Buy,
        Side::Sell => rs_order_utils::Side::Sell,
    };

    Ok(OrderData {
        maker,
        signer: Some(signer_address),
        token_id,
        maker_amount,
        taker_amount,
        side,
        signature_type: Some(signature_type),
        timestamp: user_limit_order.timestamp.map(U256::from),
        metadata: user_limit_order.metadata,
        builder: user_limit_order.builder,
        expiration: user_limit_order.expiration.map(U256::from),
    })
}

pub async fn create_limit_order(
    wallet: PrivateKeySigner,
    chain_id: Chain,
    signature_type: SignatureType,
    funder_address: Option<Address>,
    user_limit_order: &UserLimitOrder,
    options: &CreateOrderOptions,
) -> ClobResult<SignedOrder> {
    let signer_address = wallet.address();
    let maker = funder_address.unwrap_or(signer_address);
    let contract_config =
        get_contract_config(chain_id.chain_id()).map_err(ClobError::Other)?;

    let round_config = get_rounding_config(options.tick_size);

    let order_data = build_limit_order_creation_args(
        signer_address,
        maker,
        signature_type,
        user_limit_order,
        &round_config,
    )?;

    let exchange_contract = if options.neg_risk.unwrap_or(false) {
        contract_config.neg_risk_exchange
    } else {
        contract_config.exchange
    };

    build_order(wallet, exchange_contract, chain_id.chain_id(), order_data).await
}

pub fn build_market_order_creation_args(
    signer_address: Address,
    maker: Address,
    signature_type: SignatureType,
    user_market_order: &UserMarketOrder,
    round_config: &RoundConfig,
) -> ClobResult<OrderData> {
    let price = user_market_order.price.unwrap_or(1.0);

    let raw_amounts = get_market_order_raw_amounts(
        user_market_order.side,
        user_market_order.amount,
        price,
        round_config,
    );

    let maker_amount = parse_market_maker_units(raw_amounts.raw_maker_amt, COLLATERAL_TOKEN_DECIMALS);
    let taker_amount = parse_market_taker_units(raw_amounts.raw_taker_amt, COLLATERAL_TOKEN_DECIMALS);

    let token_id = U256::from_str(&user_market_order.token_id)
        .map_err(|e| ClobError::Other(format!("Invalid token_id: {}", e)))?;

    let side = match raw_amounts.side {
        Side::Buy => rs_order_utils::Side::Buy,
        Side::Sell => rs_order_utils::Side::Sell,
    };

    Ok(OrderData {
        maker,
        signer: Some(signer_address),
        token_id,
        maker_amount,
        taker_amount,
        side,
        signature_type: Some(signature_type),
        timestamp: user_market_order.timestamp.map(U256::from),
        metadata: user_market_order.metadata,
        builder: user_market_order.builder,
        expiration: Some(U256::ZERO),
    })
}

pub async fn create_market_order(
    wallet: PrivateKeySigner,
    chain_id: Chain,
    signature_type: SignatureType,
    funder_address: Option<Address>,
    user_market_order: &UserMarketOrder,
    options: &CreateOrderOptions,
) -> ClobResult<SignedOrder> {
    let signer_address = wallet.address();
    let maker = funder_address.unwrap_or(signer_address);
    let contract_config =
        get_contract_config(chain_id.chain_id()).map_err(ClobError::Other)?;

    let round_config = get_rounding_config(options.tick_size);

    let order_data = build_market_order_creation_args(
        signer_address,
        maker,
        signature_type,
        user_market_order,
        &round_config,
    )?;

    let exchange_contract = if options.neg_risk.unwrap_or(false) {
        contract_config.neg_risk_exchange
    } else {
        contract_config.exchange
    };

    build_order(wallet, exchange_contract, chain_id.chain_id(), order_data).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_rounding_config() {
        let config = get_rounding_config(TickSize::ZeroPointZeroOne);
        assert_eq!(config.price, 2);
        assert_eq!(config.size, 2);
        assert_eq!(config.amount, 4);
    }

    #[test]
    fn test_get_order_raw_amounts_buy() {
        let round_config = RoundConfig {
            price: 2,
            size: 2,
            amount: 4,
        };
        let result = get_order_raw_amounts(Side::Buy, 100.0, 0.55, &round_config);
        assert_eq!(result.side, Side::Buy);
        assert_eq!(result.raw_taker_amt, 100.0);
        assert_eq!(result.raw_maker_amt, 55.0);
    }

    #[test]
    fn test_get_order_raw_amounts_sell() {
        let round_config = RoundConfig {
            price: 2,
            size: 2,
            amount: 4,
        };
        let result = get_order_raw_amounts(Side::Sell, 100.0, 0.55, &round_config);
        assert_eq!(result.side, Side::Sell);
        assert_eq!(result.raw_maker_amt, 100.0);
        assert_eq!(result.raw_taker_amt, 55.0);
    }

    #[test]
    fn test_calculate_buy_market_price() {
        let positions = vec![
            OrderSummary {
                price: "0.6".to_string(),
                size: "100".to_string(),
            },
            OrderSummary {
                price: "0.55".to_string(),
                size: "100".to_string(),
            },
            OrderSummary {
                price: "0.5".to_string(),
                size: "100".to_string(),
            },
        ];

        let price = calculate_buy_market_price(&positions, 150.0, OrderType::Fok).unwrap();
        assert_eq!(price, 0.6);
    }

    #[test]
    fn test_calculate_sell_market_price() {
        let positions = vec![
            OrderSummary {
                price: "0.4".to_string(),
                size: "100".to_string(),
            },
            OrderSummary {
                price: "0.45".to_string(),
                size: "100".to_string(),
            },
            OrderSummary {
                price: "0.5".to_string(),
                size: "100".to_string(),
            },
        ];

        let price = calculate_sell_market_price(&positions, 300.0, OrderType::Fok).unwrap();
        assert_eq!(price, 0.4);
    }

    #[test]
    fn test_fok_fails_on_insufficient_liquidity() {
        let positions = vec![OrderSummary {
            price: "0.5".to_string(),
            size: "10".to_string(),
        }];

        let result = calculate_buy_market_price(&positions, 100.0, OrderType::Fok);
        assert!(result.is_err());
    }

    #[test]
    fn test_fak_accepts_partial_fill() {
        let positions = vec![OrderSummary {
            price: "0.5".to_string(),
            size: "10".to_string(),
        }];

        let result = calculate_buy_market_price(&positions, 100.0, OrderType::Fak);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0.5);
    }

    #[test]
    fn test_empty_orderbook() {
        let positions: Vec<OrderSummary> = vec![];
        let result = calculate_buy_market_price(&positions, 10.0, OrderType::Fok);
        assert!(matches!(result, Err(ClobError::NoMatch)));
    }
}