polyoxide-clob 0.12.4

Rust client library for Polymarket CLOB (order book) API
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
use polyoxide_core::{
    HttpClient, HttpClientBuilder, RateLimiter, RetryConfig, DEFAULT_POOL_SIZE, DEFAULT_TIMEOUT_MS,
};

use crate::{
    account::{Account, Credentials},
    api::{
        account::AccountApi, auth::Auth, notifications::Notifications, orders::OrderResponse,
        rewards::Rewards, rfq::Rfq, Health, Markets, Orders,
    },
    core::chain::Chain,
    error::ClobError,
    request::{AuthMode, Request},
    types::*,
    utils::{
        calculate_market_order_amounts, calculate_market_price, calculate_order_amounts,
        generate_salt,
    },
};
use alloy::primitives::Address;
#[cfg(feature = "gamma")]
use polyoxide_gamma::Gamma;

const DEFAULT_BASE_URL: &str = "https://clob.polymarket.com";

/// CLOB (Central Limit Order Book) trading client for Polymarket.
///
/// Provides authenticated order creation, signing, and submission, plus read-only
/// market data and order book access. Use [`Clob::public()`] for unauthenticated
/// read-only access, or [`Clob::builder()`] for full trading capabilities.
#[derive(Clone)]
pub struct Clob {
    pub(crate) http_client: HttpClient,
    pub(crate) chain_id: u64,
    pub(crate) account: Option<Account>,
    #[cfg(feature = "gamma")]
    pub(crate) gamma: Gamma,
}

impl Clob {
    /// Create a new CLOB client with default configuration
    pub fn new(
        private_key: impl Into<String>,
        credentials: Credentials,
    ) -> Result<Self, ClobError> {
        Self::builder(private_key, credentials)?.build()
    }

    /// Create a new public CLOB client (read-only)
    pub fn public() -> Self {
        ClobBuilder::new().build().unwrap() // unwrap safe because default build never fails
    }

    /// Create a new CLOB client builder with required authentication
    pub fn builder(
        private_key: impl Into<String>,
        credentials: Credentials,
    ) -> Result<ClobBuilder, ClobError> {
        let account = Account::new(private_key, credentials)?;
        Ok(ClobBuilder::new().with_account(account))
    }

    /// Create a new CLOB client from an Account
    pub fn from_account(account: Account) -> Result<Self, ClobError> {
        ClobBuilder::new().with_account(account).build()
    }

    /// Get a reference to the account
    pub fn account(&self) -> Option<&Account> {
        self.account.as_ref()
    }

    /// Get markets namespace
    pub fn markets(&self) -> Markets {
        Markets {
            http_client: self.http_client.clone(),
            chain_id: self.chain_id,
        }
    }

    /// Get health namespace for latency and health checks
    pub fn health(&self) -> Health {
        Health {
            http_client: self.http_client.clone(),
            chain_id: self.chain_id,
        }
    }

    /// Get orders namespace
    pub fn orders(&self) -> Result<Orders, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required for orders API"))?;

        Ok(Orders {
            http_client: self.http_client.clone(),
            wallet: account.wallet().clone(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
            chain_id: self.chain_id,
        })
    }

    /// Get account API namespace
    pub fn account_api(&self) -> Result<AccountApi, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required for account API"))?;

        Ok(AccountApi {
            http_client: self.http_client.clone(),
            wallet: account.wallet().clone(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
            chain_id: self.chain_id,
        })
    }

    /// Get notifications namespace
    pub fn notifications(&self) -> Result<Notifications, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required for notifications API"))?;

        Ok(Notifications {
            http_client: self.http_client.clone(),
            wallet: account.wallet().clone(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
            chain_id: self.chain_id,
        })
    }

    /// Get RFQ namespace for request-for-quote operations
    pub fn rfq(&self) -> Result<Rfq, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required for RFQ API"))?;

        Ok(Rfq {
            http_client: self.http_client.clone(),
            wallet: account.wallet().clone(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
            chain_id: self.chain_id,
        })
    }

    /// Get rewards namespace for liquidity reward operations
    pub fn rewards(&self) -> Result<Rewards, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required for rewards API"))?;

        Ok(Rewards {
            http_client: self.http_client.clone(),
            wallet: account.wallet().clone(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
            chain_id: self.chain_id,
        })
    }

    /// Get auth namespace for API key management
    pub fn auth(&self) -> Result<Auth, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required for auth API"))?;

        Ok(Auth {
            http_client: self.http_client.clone(),
            wallet: account.wallet().clone(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
            chain_id: self.chain_id,
        })
    }

    /// Create an unsigned order from parameters
    pub async fn create_order(
        &self,
        params: &CreateOrderParams,
        options: Option<PartialCreateOrderOptions>,
    ) -> Result<Order, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required to create order"))?;

        params.validate()?;

        // Fetch market metadata (neg_risk and tick_size)
        let (neg_risk, tick_size) = self.get_market_metadata(&params.token_id, options).await?;

        // Get fee rate
        let fee_rate_bps = self.get_fee_rate(&params.token_id).await?;

        // Calculate amounts
        let (maker_amount, taker_amount) =
            calculate_order_amounts(params.price, params.size, params.side, tick_size);

        // Resolve maker address
        let signature_type = params.signature_type.unwrap_or_default();
        let maker = self
            .resolve_maker_address(params.funder, signature_type, account)
            .await?;

        // Build order
        Ok(Self::build_order(
            params.token_id.clone(),
            maker,
            account.address(),
            maker_amount,
            taker_amount,
            fee_rate_bps,
            params.side,
            signature_type,
            neg_risk,
            params.expiration,
        ))
    }

    /// Create an unsigned market order from parameters
    pub async fn create_market_order(
        &self,
        params: &MarketOrderArgs,
        options: Option<PartialCreateOrderOptions>,
    ) -> Result<Order, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required to create order"))?;

        if !params.amount.is_finite() {
            return Err(ClobError::validation(
                "Amount must be finite (no NaN or infinity)",
            ));
        }
        if params.amount <= 0.0 {
            return Err(ClobError::validation(format!(
                "Amount must be positive, got {}",
                params.amount
            )));
        }
        if let Some(p) = params.price {
            if !p.is_finite() || p <= 0.0 || p > 1.0 {
                return Err(ClobError::validation(format!(
                    "Price must be finite and between 0.0 and 1.0, got {}",
                    p
                )));
            }
        }

        // Fetch market metadata (neg_risk and tick_size)
        let (neg_risk, tick_size) = self.get_market_metadata(&params.token_id, options).await?;

        // Determine price
        let price = if let Some(p) = params.price {
            p
        } else {
            // Fetch orderbook and calculate price
            let book = self
                .markets()
                .order_book(params.token_id.clone())
                .send()
                .await?;

            let levels = match params.side {
                OrderSide::Buy => book.asks,
                OrderSide::Sell => book.bids,
            };

            calculate_market_price(&levels, params.amount, params.side)
                .ok_or_else(|| ClobError::validation("Not enough liquidity to fill market order"))?
        };

        // Get fee rate
        let fee_rate_bps = self.get_fee_rate(&params.token_id).await?;

        // Calculate amounts
        let (maker_amount, taker_amount) =
            calculate_market_order_amounts(params.amount, price, params.side, tick_size);

        // Resolve maker address
        let signature_type = params.signature_type.unwrap_or_default();
        let maker = self
            .resolve_maker_address(params.funder, signature_type, account)
            .await?;

        // Build order with expiration set to 0 for market orders
        Ok(Self::build_order(
            params.token_id.clone(),
            maker,
            account.address(),
            maker_amount,
            taker_amount,
            fee_rate_bps,
            params.side,
            signature_type,
            neg_risk,
            Some(0),
        ))
    }
    /// Sign an order using the configured account's EIP-712 signer.
    pub async fn sign_order(&self, order: &Order) -> Result<SignedOrder, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required to sign order"))?;
        account.sign_order(order, self.chain_id).await
    }

    // Helper methods for order creation

    /// Fetch market metadata (neg_risk and tick_size) for a token
    async fn get_market_metadata(
        &self,
        token_id: &str,
        options: Option<PartialCreateOrderOptions>,
    ) -> Result<(bool, TickSize), ClobError> {
        // Fetch or use provided neg_risk status
        let neg_risk = if let Some(neg_risk) = options.and_then(|o| o.neg_risk) {
            neg_risk
        } else {
            let neg_risk_resp = self.markets().neg_risk(token_id.to_string()).send().await?;
            neg_risk_resp.neg_risk
        };

        // Fetch or use provided tick size
        let tick_size = if let Some(tick_size) = options.and_then(|o| o.tick_size) {
            tick_size
        } else {
            let tick_size_resp = self
                .markets()
                .tick_size(token_id.to_string())
                .send()
                .await?;
            let tick_size_val = tick_size_resp
                .minimum_tick_size
                .parse::<f64>()
                .map_err(|e| {
                    ClobError::validation(format!("Invalid minimum_tick_size field: {}", e))
                })?;
            TickSize::try_from(tick_size_val)?
        };

        Ok((neg_risk, tick_size))
    }

    /// Fetch the current fee rate for a token from the API
    async fn get_fee_rate(&self, token_id: &str) -> Result<String, ClobError> {
        let resp = self.markets().fee_rate(token_id).send().await?;
        Ok(resp.base_fee.to_string())
    }

    /// Resolve the maker address based on funder and signature type
    async fn resolve_maker_address(
        &self,
        funder: Option<Address>,
        signature_type: SignatureType,
        account: &Account,
    ) -> Result<Address, ClobError> {
        if let Some(funder) = funder {
            Ok(funder)
        } else if signature_type.is_proxy() {
            #[cfg(feature = "gamma")]
            {
                // Fetch proxy from Gamma
                let profile = self
                    .gamma
                    .user()
                    .get(account.address().to_string())
                    .send()
                    .await
                    .map_err(|e| {
                        ClobError::service(format!("Failed to fetch user profile: {}", e))
                    })?;

                profile
                    .proxy
                    .ok_or_else(|| {
                        ClobError::validation(format!(
                            "Signature type {:?} requires proxy, but none found for {}",
                            signature_type,
                            account.address()
                        ))
                    })?
                    .parse::<Address>()
                    .map_err(|e| {
                        ClobError::validation(format!(
                            "Invalid proxy address format from Gamma: {}",
                            e
                        ))
                    })
            }
            #[cfg(not(feature = "gamma"))]
            {
                Err(ClobError::validation(format!(
                    "Signature type {:?} requires the `gamma` feature to resolve proxy address; \
                     enable `polyoxide-clob/gamma` or provide an explicit `funder` address",
                    signature_type
                )))
            }
        } else {
            Ok(account.address())
        }
    }

    /// Build an Order struct from the provided parameters
    #[allow(clippy::too_many_arguments)]
    fn build_order(
        token_id: String,
        maker: Address,
        signer: Address,
        maker_amount: String,
        taker_amount: String,
        fee_rate_bps: String,
        side: OrderSide,
        signature_type: SignatureType,
        neg_risk: bool,
        expiration: Option<u64>,
    ) -> Order {
        Order {
            salt: generate_salt(),
            maker,
            signer,
            taker: alloy::primitives::Address::ZERO,
            token_id,
            maker_amount,
            taker_amount,
            expiration: expiration.unwrap_or(0).to_string(),
            nonce: "0".to_string(),
            fee_rate_bps,
            side,
            signature_type,
            neg_risk,
        }
    }

    /// Post multiple signed orders (up to 15)
    pub async fn post_orders(
        &self,
        orders: &[SignedOrderPayload],
    ) -> Result<Vec<OrderResponse>, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required to post orders"))?;

        let auth = AuthMode::L2 {
            address: account.address(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
        };

        let payload: Vec<_> = orders
            .iter()
            .map(|o| {
                serde_json::json!({
                    "order": o.order,
                    "owner": account.credentials().key,
                    "orderType": o.order_type,
                    "postOnly": o.post_only,
                })
            })
            .collect();

        Request::post(
            self.http_client.clone(),
            "/orders".to_string(),
            auth,
            self.chain_id,
        )
        .body(&payload)?
        .send()
        .await
    }

    /// Post a signed order
    pub async fn post_order(
        &self,
        signed_order: &SignedOrder,
        order_type: OrderKind,
        post_only: bool,
    ) -> Result<OrderResponse, ClobError> {
        let account = self
            .account
            .as_ref()
            .ok_or_else(|| ClobError::validation("Account required to post order"))?;

        let auth = AuthMode::L2 {
            address: account.address(),
            credentials: account.credentials().clone(),
            signer: account.signer().clone(),
        };

        // Create the payload wrapping the signed order
        let payload = serde_json::json!({
            "order": signed_order,
            "owner": account.credentials().key,
            "orderType": order_type,
            "postOnly": post_only,
        });

        Request::post(
            self.http_client.clone(),
            "/order".to_string(),
            auth,
            self.chain_id,
        )
        .body(&payload)?
        .send()
        .await
    }

    /// Create, sign, and post an order (convenience method)
    pub async fn place_order(
        &self,
        params: &CreateOrderParams,
        options: Option<PartialCreateOrderOptions>,
    ) -> Result<OrderResponse, ClobError> {
        let order = self.create_order(params, options).await?;
        let signed_order = self.sign_order(&order).await?;
        self.post_order(&signed_order, params.order_type, params.post_only)
            .await
    }

    /// Create, sign, and post a market order (convenience method)
    pub async fn place_market_order(
        &self,
        params: &MarketOrderArgs,
        options: Option<PartialCreateOrderOptions>,
    ) -> Result<OrderResponse, ClobError> {
        let order = self.create_market_order(params, options).await?;
        let signed_order = self.sign_order(&order).await?;

        let order_type = params.order_type.unwrap_or(OrderKind::Fok);
        // Market orders are usually FOK

        self.post_order(&signed_order, order_type, false) // Market orders cannot be post_only
            .await
    }
}

/// Parameters for creating an order
#[derive(Debug, Clone)]
pub struct CreateOrderParams {
    pub token_id: String,
    pub price: f64,
    pub size: f64,
    pub side: OrderSide,
    pub order_type: OrderKind,
    pub post_only: bool,
    pub expiration: Option<u64>,
    pub funder: Option<Address>,
    pub signature_type: Option<SignatureType>,
}

impl CreateOrderParams {
    /// Validate price and size are finite and within expected ranges.
    pub fn validate(&self) -> Result<(), ClobError> {
        if !self.price.is_finite() || !self.size.is_finite() {
            return Err(ClobError::validation(
                "Price and size must be finite (no NaN or infinity)",
            ));
        }
        if self.price <= 0.0 || self.price > 1.0 {
            return Err(ClobError::validation(format!(
                "Price must be between 0.0 and 1.0, got {}",
                self.price
            )));
        }
        if self.size <= 0.0 {
            return Err(ClobError::validation(format!(
                "Size must be positive, got {}",
                self.size
            )));
        }
        Ok(())
    }
}

/// Payload for batch order submission via [`Clob::post_orders`]
#[derive(Debug, Clone)]
pub struct SignedOrderPayload {
    pub order: SignedOrder,
    pub order_type: OrderKind,
    pub post_only: bool,
}

/// Builder for CLOB client
pub struct ClobBuilder {
    base_url: String,
    timeout_ms: u64,
    pool_size: usize,
    chain: Chain,
    account: Option<Account>,
    #[cfg(feature = "gamma")]
    gamma: Option<Gamma>,
    retry_config: Option<RetryConfig>,
    max_concurrent: Option<usize>,
}

impl ClobBuilder {
    /// Create a new builder with default configuration
    pub fn new() -> Self {
        Self {
            base_url: DEFAULT_BASE_URL.to_string(),
            timeout_ms: DEFAULT_TIMEOUT_MS,
            pool_size: DEFAULT_POOL_SIZE,
            chain: Chain::PolygonMainnet,
            account: None,
            #[cfg(feature = "gamma")]
            gamma: None,
            retry_config: None,
            max_concurrent: None,
        }
    }

    /// Set account for the client
    pub fn with_account(mut self, account: Account) -> Self {
        self.account = Some(account);
        self
    }

    /// Set base URL for the API
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// Set request timeout in milliseconds
    pub fn timeout_ms(mut self, timeout: u64) -> Self {
        self.timeout_ms = timeout;
        self
    }

    /// Set connection pool size
    pub fn pool_size(mut self, size: usize) -> Self {
        self.pool_size = size;
        self
    }

    /// Set chain
    pub fn chain(mut self, chain: Chain) -> Self {
        self.chain = chain;
        self
    }

    /// Set Gamma client
    #[cfg(feature = "gamma")]
    pub fn gamma(mut self, gamma: Gamma) -> Self {
        self.gamma = Some(gamma);
        self
    }

    /// Set retry configuration for 429 responses
    pub fn with_retry_config(mut self, config: RetryConfig) -> Self {
        self.retry_config = Some(config);
        self
    }

    /// Set the maximum number of concurrent in-flight requests.
    ///
    /// Default: 8. Prevents Cloudflare 1015 errors from request bursts.
    pub fn max_concurrent(mut self, max: usize) -> Self {
        self.max_concurrent = Some(max);
        self
    }

    /// Build the CLOB client
    pub fn build(self) -> Result<Clob, ClobError> {
        let mut builder = HttpClientBuilder::new(&self.base_url)
            .timeout_ms(self.timeout_ms)
            .pool_size(self.pool_size)
            .with_rate_limiter(RateLimiter::clob_default())
            .with_max_concurrent(self.max_concurrent.unwrap_or(8));
        if let Some(config) = self.retry_config {
            builder = builder.with_retry_config(config);
        }
        let http_client = builder.build()?;

        #[cfg(feature = "gamma")]
        let gamma = if let Some(gamma) = self.gamma {
            gamma
        } else {
            polyoxide_gamma::Gamma::builder()
                .timeout_ms(self.timeout_ms)
                .pool_size(self.pool_size)
                .build()
                .map_err(|e| {
                    ClobError::service(format!("Failed to build default Gamma client: {}", e))
                })?
        };

        Ok(Clob {
            http_client,
            chain_id: self.chain.chain_id(),
            account: self.account,
            #[cfg(feature = "gamma")]
            gamma,
        })
    }
}

impl Default for ClobBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_builder_custom_max_concurrent() {
        let builder = ClobBuilder::new().max_concurrent(16);
        assert_eq!(builder.max_concurrent, Some(16));
    }

    #[tokio::test]
    async fn test_default_concurrency_limit_is_8() {
        let clob = Clob::public();
        let mut permits = Vec::new();
        for _ in 0..8 {
            permits.push(clob.http_client.acquire_concurrency().await);
        }
        assert!(permits.iter().all(|p| p.is_some()));

        let result = tokio::time::timeout(
            std::time::Duration::from_millis(50),
            clob.http_client.acquire_concurrency(),
        )
        .await;
        assert!(
            result.is_err(),
            "9th permit should block with default limit of 8"
        );
    }

    #[test]
    fn test_builder_custom_retry_config() {
        let config = RetryConfig {
            max_retries: 5,
            initial_backoff_ms: 1000,
            max_backoff_ms: 30_000,
        };
        let builder = ClobBuilder::new().with_retry_config(config);
        let config = builder.retry_config.unwrap();
        assert_eq!(config.max_retries, 5);
        assert_eq!(config.initial_backoff_ms, 1000);
    }

    fn make_params(price: f64, size: f64) -> CreateOrderParams {
        CreateOrderParams {
            token_id: "test".to_string(),
            price,
            size,
            side: OrderSide::Buy,
            order_type: OrderKind::Gtc,
            post_only: false,
            expiration: None,
            funder: None,
            signature_type: None,
        }
    }

    #[test]
    fn test_validate_rejects_nan_price() {
        let params = make_params(f64::NAN, 100.0);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("finite"));
    }

    #[test]
    fn test_validate_rejects_nan_size() {
        let params = make_params(0.5, f64::NAN);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("finite"));
    }

    #[test]
    fn test_validate_rejects_infinite_price() {
        let params = make_params(f64::INFINITY, 100.0);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("finite"));
    }

    #[test]
    fn test_validate_rejects_infinite_size() {
        let params = make_params(0.5, f64::INFINITY);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("finite"));
    }

    #[test]
    fn test_validate_rejects_neg_infinity_size() {
        let params = make_params(0.5, f64::NEG_INFINITY);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("finite"));
    }

    #[test]
    fn test_validate_rejects_price_out_of_range() {
        let params = make_params(1.5, 100.0);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("between 0.0 and 1.0"));
    }

    #[test]
    fn test_validate_rejects_zero_price() {
        let params = make_params(0.0, 100.0);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("between 0.0 and 1.0"));
    }

    #[test]
    fn test_validate_rejects_negative_size() {
        let params = make_params(0.5, -10.0);
        let err = params.validate().unwrap_err();
        assert!(err.to_string().contains("positive"));
    }

    #[test]
    fn test_validate_accepts_valid_params() {
        let params = make_params(0.5, 100.0);
        assert!(params.validate().is_ok());
    }

    #[test]
    fn test_validate_accepts_boundary_price() {
        // Price exactly 1.0 should be valid
        let params = make_params(1.0, 100.0);
        assert!(params.validate().is_ok());
    }
}