polyfill2 0.3.0

Polymarket CLOB V2 Rust client (fork of polyfill-rs). High-performance, EIP-712 signing, WebSocket streaming.
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
//! Order creation and signing functionality
//!
//! 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::errors::{PolyfillError, Result};
use crate::types::{
    ExtraOrderArgs, ExtraOrderArgsV1, MarketOrderArgs, OrderOptions, RfqOrderExecutionRequest,
    Side, SignedOrderRequest,
};
use alloy_primitives::{Address, U256};
use alloy_signer_local::PrivateKeySigner;
use rand::RngExt;
use rust_decimal::Decimal;
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};

/// Signature types for orders
#[derive(Copy, Clone)]
pub enum SigType {
    /// ECDSA EIP712 signatures signed by EOAs
    Eoa = 0,
    /// EIP712 signatures signed by EOAs that own Polymarket Proxy wallets
    PolyProxy = 1,
    /// EIP712 signatures signed by EOAs that own Polymarket Gnosis safes
    PolyGnosisSafe = 2,
    /// EIP-1271 smart-contract wallets / account abstraction (V2).
    Poly1271 = 3,
}

/// Rounding configuration for different tick sizes
pub struct RoundConfig {
    price: u32,
    size: u32,
    amount: u32,
}

/// Contract configuration
pub struct ContractConfig {
    pub exchange: String,
    pub collateral: String,
    pub conditional_tokens: String,
    pub neg_risk_adapter: String,
}

/// Order builder for creating and signing orders
pub struct OrderBuilder {
    signer: PrivateKeySigner,
    sig_type: SigType,
    funder: Address,
}

/// Rounding configurations for different tick sizes
static ROUNDING_CONFIG: LazyLock<HashMap<Decimal, RoundConfig>> = LazyLock::new(|| {
    HashMap::from([
        (
            Decimal::from_str("0.1").unwrap(),
            RoundConfig {
                price: 1,
                size: 2,
                amount: 3,
            },
        ),
        (
            Decimal::from_str("0.01").unwrap(),
            RoundConfig {
                price: 2,
                size: 2,
                amount: 4,
            },
        ),
        (
            Decimal::from_str("0.001").unwrap(),
            RoundConfig {
                price: 3,
                size: 2,
                amount: 5,
            },
        ),
        (
            Decimal::from_str("0.0001").unwrap(),
            RoundConfig {
                price: 4,
                size: 2,
                amount: 6,
            },
        ),
    ])
});

/// V1 contract addresses for RFQ accept/approve signing only.
/// V1 exchange contracts remain active on Polygon mainnet for RFQ flows even
/// after the CLOB V2 migration.
pub fn get_v1_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(),
            conditional_tokens: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045".to_string(),
            neg_risk_adapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296".to_string(),
        }),
        (137, true) => Some(ContractConfig {
            exchange: "0xC5d563A36AE78145C45a50134d48A1215220f80a".to_string(),
            collateral: "0x2791Bca1f2de4661ED88A30C99a7a9449Aa84174".to_string(),
            conditional_tokens: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045".to_string(),
            neg_risk_adapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296".to_string(),
        }),
        _ => None,
    }
}

/// Get contract configuration for chain (CLOB V2)
pub fn get_contract_config(chain_id: u64, neg_risk: bool) -> Option<ContractConfig> {
    match (chain_id, neg_risk) {
        (137, false) => Some(ContractConfig {
            exchange: "0xE111180000d2663C0091e4f400237545B87B996B".to_string(),
            collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".to_string(),
            conditional_tokens: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045".to_string(),
            neg_risk_adapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296".to_string(),
        }),
        (137, true) => Some(ContractConfig {
            exchange: "0xe2222d279d744050d28e00520010520000310F59".to_string(),
            collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".to_string(),
            conditional_tokens: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045".to_string(),
            neg_risk_adapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296".to_string(),
        }),
        (80002, false) => Some(ContractConfig {
            exchange: "0xE111180000d2663C0091e4f400237545B87B996B".to_string(),
            collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".to_string(),
            conditional_tokens: "0x69308FB512518e39F9b16112fA8d994F4e2Bf8bB".to_string(),
            neg_risk_adapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296".to_string(),
        }),
        (80002, true) => Some(ContractConfig {
            exchange: "0xe2222d279d744050d28e00520010520000310F59".to_string(),
            collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".to_string(),
            conditional_tokens: "0x69308FB512518e39F9b16112fA8d994F4e2Bf8bB".to_string(),
            neg_risk_adapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296".to_string(),
        }),
        _ => None,
    }
}

/// Generate a random seed for order salt
fn generate_seed() -> u64 {
    let mut rng = rand::rng();
    let y: f64 = rng.random();
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards")
        .as_secs();
    (timestamp as f64 * y) as u64
}

/// Convert decimal to token units (multiply by 1e6)
fn decimal_to_token_u32(amt: Decimal) -> u32 {
    let mut amt = Decimal::from_scientific("1e6").expect("1e6 is not scientific") * amt;
    if amt.scale() > 0 {
        amt = amt.round_dp_with_strategy(0, MidpointTowardZero);
    }
    amt.try_into().expect("Couldn't round decimal to integer")
}

impl OrderBuilder {
    /// Create a new order builder
    pub fn new(
        signer: PrivateKeySigner,
        sig_type: Option<SigType>,
        funder: Option<Address>,
    ) -> Self {
        let sig_type = sig_type.unwrap_or(SigType::Eoa);
        let funder = funder.unwrap_or(signer.address());

        OrderBuilder {
            signer,
            sig_type,
            funder,
        }
    }

    /// Get signature type as u8
    pub fn get_sig_type(&self) -> u8 {
        self.sig_type as u8
    }

    /// Fix amount rounding according to configuration
    fn fix_amount_rounding(&self, mut amt: Decimal, round_config: &RoundConfig) -> Decimal {
        if amt.scale() > round_config.amount {
            amt = amt.round_dp_with_strategy(round_config.amount + 4, AwayFromZero);
            if amt.scale() > round_config.amount {
                amt = amt.round_dp_with_strategy(round_config.amount, ToZero);
            }
        }
        amt
    }

    /// Get order amounts (maker and taker) for a regular order
    fn get_order_amounts(
        &self,
        side: Side,
        size: Decimal,
        price: Decimal,
        round_config: &RoundConfig,
    ) -> (u32, u32) {
        let raw_price = price.round_dp_with_strategy(round_config.price, MidpointTowardZero);

        match side {
            Side::BUY => {
                let raw_taker_amt = size.round_dp_with_strategy(round_config.size, ToZero);
                let raw_maker_amt = raw_taker_amt * raw_price;
                let raw_maker_amt = self.fix_amount_rounding(raw_maker_amt, round_config);
                (
                    decimal_to_token_u32(raw_maker_amt),
                    decimal_to_token_u32(raw_taker_amt),
                )
            },
            Side::SELL => {
                let raw_maker_amt = size.round_dp_with_strategy(round_config.size, ToZero);
                let raw_taker_amt = raw_maker_amt * raw_price;
                let raw_taker_amt = self.fix_amount_rounding(raw_taker_amt, round_config);

                (
                    decimal_to_token_u32(raw_maker_amt),
                    decimal_to_token_u32(raw_taker_amt),
                )
            },
        }
    }

    /// 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_price = price.round_dp_with_strategy(round_config.price, MidpointTowardZero);
        match side {
            Side::BUY => {
                let raw_maker_amt = amount.round_dp_with_strategy(round_config.size, ToZero);
                let raw_taker_amt = raw_maker_amt / raw_price;
                let raw_taker_amt = self.fix_amount_rounding(raw_taker_amt, round_config);
                (
                    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 = raw_maker_amt * raw_price;
                let raw_taker_amt = self.fix_amount_rounding(raw_taker_amt, round_config);
                (
                    decimal_to_token_u32(raw_maker_amt),
                    decimal_to_token_u32(raw_taker_amt),
                )
            },
        }
    }

    /// Calculate market price from order book levels
    pub fn calculate_market_price(
        &self,
        side: Side,
        positions: &[crate::types::BookLevel],
        amount_to_match: Decimal,
    ) -> Result<Decimal> {
        let mut sum = Decimal::ZERO;

        for level in positions {
            sum += match side {
                Side::BUY => level.size * level.price,
                Side::SELL => level.size,
            };
            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,
        ))
    }

    /// Create a market order
    pub fn create_market_order(
        &self,
        chain_id: u64,
        order_args: &MarketOrderArgs,
        price: Decimal,
        extras: &ExtraOrderArgs,
        options: &OrderOptions,
    ) -> Result<SignedOrderRequest> {
        let tick_size = options
            .tick_size
            .ok_or_else(|| PolyfillError::validation("Cannot create order without tick size"))?;

        let (maker_amount, taker_amount) = self.get_market_order_amounts(
            order_args.side,
            order_args.amount,
            price,
            &ROUNDING_CONFIG[&tick_size],
        );

        let neg_risk = options
            .neg_risk
            .ok_or_else(|| PolyfillError::validation("Cannot create order without neg_risk"))?;

        let contract_config = get_contract_config(chain_id, neg_risk).ok_or_else(|| {
            PolyfillError::config("No contract found with given chain_id and neg_risk")
        })?;

        let exchange_address = Address::from_str(&contract_config.exchange)
            .map_err(|e| PolyfillError::config(format!("Invalid exchange address: {}", e)))?;

        self.build_signed_order(
            order_args.token_id.clone(),
            order_args.side,
            chain_id,
            exchange_address,
            maker_amount,
            taker_amount,
            0,
            extras,
        )
    }

    /// Create a regular order
    pub fn create_order(
        &self,
        chain_id: u64,
        order_args: &OrderArgs,
        expiration: u64,
        extras: &ExtraOrderArgs,
        options: &OrderOptions,
    ) -> Result<SignedOrderRequest> {
        let tick_size = options
            .tick_size
            .ok_or_else(|| PolyfillError::validation("Cannot create order without tick size"))?;

        let (maker_amount, taker_amount) = self.get_order_amounts(
            order_args.side,
            order_args.size,
            order_args.price,
            &ROUNDING_CONFIG[&tick_size],
        );

        let neg_risk = options
            .neg_risk
            .ok_or_else(|| PolyfillError::validation("Cannot create order without neg_risk"))?;

        let contract_config = get_contract_config(chain_id, neg_risk).ok_or_else(|| {
            PolyfillError::config("No contract found with given chain_id and neg_risk")
        })?;

        let exchange_address = Address::from_str(&contract_config.exchange)
            .map_err(|e| PolyfillError::config(format!("Invalid exchange address: {}", e)))?;

        self.build_signed_order(
            order_args.token_id.clone(),
            order_args.side,
            chain_id,
            exchange_address,
            maker_amount,
            taker_amount,
            expiration,
            extras,
        )
    }

    /// Build and sign a V1 order for RFQ accept/approve. This is the only path
    /// that still uses V1 signing in CLOB V2 — regular trading uses V2 orders.
    #[allow(clippy::too_many_arguments)]
    pub fn build_v1_signed_rfq_payload(
        &self,
        chain_id: u64,
        order_args: &OrderArgs,
        expiration: u64,
        extras: &ExtraOrderArgsV1,
        options: &OrderOptions,
        request_id: String,
        quote_id: String,
        owner: String,
    ) -> Result<RfqOrderExecutionRequest> {
        let tick_size = options
            .tick_size
            .ok_or_else(|| PolyfillError::validation("Cannot create V1 order without tick size"))?;
        let neg_risk = options
            .neg_risk
            .ok_or_else(|| PolyfillError::validation("Cannot create V1 order without neg_risk"))?;

        let contract_config = get_v1_contract_config(chain_id, neg_risk).ok_or_else(|| {
            PolyfillError::config(
                "No V1 contract for chain_id/neg_risk (RFQ supports Polygon mainnet)",
            )
        })?;
        let exchange = Address::from_str(&contract_config.exchange)
            .map_err(|e| PolyfillError::config(format!("Invalid V1 exchange address: {}", e)))?;

        let (maker_amount, taker_amount) = self.get_order_amounts(
            order_args.side,
            order_args.size,
            order_args.price,
            &ROUNDING_CONFIG[&tick_size],
        );

        let seed = generate_seed();
        let taker_address = Address::from_str(&extras.taker)
            .map_err(|e| PolyfillError::validation(format!("Invalid taker address: {}", e)))?;
        let u256_token_id = U256::from_str_radix(&order_args.token_id, 10)
            .map_err(|e| PolyfillError::validation(format!("Incorrect tokenId format: {}", e)))?;

        let order = crate::auth::OrderV1 {
            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),
            side: order_args.side as u8,
            signatureType: self.sig_type as u8,
        };

        let signature =
            crate::auth::sign_v1_order_message(&self.signer, order, chain_id, exchange)?;

        Ok(RfqOrderExecutionRequest {
            request_id,
            quote_id,
            owner,
            salt: seed,
            maker: self.funder.to_checksum(None),
            signer: self.signer.address().to_checksum(None),
            taker: taker_address.to_checksum(None),
            token_id: order_args.token_id.clone(),
            maker_amount: maker_amount.to_string(),
            taker_amount: taker_amount.to_string(),
            expiration,
            nonce: extras.nonce.to_string(),
            fee_rate_bps: extras.fee_rate_bps.to_string(),
            side: order_args.side.as_str().to_string(),
            signature_type: self.sig_type as u8,
            signature,
        })
    }

    /// Build and sign an order (V2).
    #[allow(clippy::too_many_arguments)]
    fn build_signed_order(
        &self,
        token_id: String,
        side: Side,
        chain_id: u64,
        exchange: Address,
        maker_amount: u32,
        taker_amount: u32,
        expiration: u64,
        extras: &ExtraOrderArgs,
    ) -> Result<SignedOrderRequest> {
        let seed = generate_seed();

        let u256_token_id = U256::from_str_radix(&token_id, 10)
            .map_err(|e| PolyfillError::validation(format!("Incorrect tokenId format: {}", e)))?;

        let timestamp_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| {
                PolyfillError::validation(format!("System clock before UNIX epoch: {}", e))
            })?
            .as_millis() as u64;

        let order = crate::auth::Order {
            salt: U256::from(seed),
            maker: self.funder,
            signer: self.signer.address(),
            tokenId: u256_token_id,
            makerAmount: U256::from(maker_amount),
            takerAmount: U256::from(taker_amount),
            side: side as u8,
            signatureType: self.sig_type as u8,
            timestamp: U256::from(timestamp_ms),
            metadata: extras.metadata,
            builder: extras.builder,
        };

        let signature = sign_order_message(&self.signer, order, chain_id, exchange)?;

        Ok(SignedOrderRequest {
            salt: seed,
            maker: self.funder.to_checksum(None),
            signer: self.signer.address().to_checksum(None),
            taker: "0x0000000000000000000000000000000000000000".to_string(),
            token_id,
            maker_amount: maker_amount.to_string(),
            taker_amount: taker_amount.to_string(),
            side: side.as_str().to_string(),
            signature_type: self.sig_type as u8,
            timestamp: timestamp_ms.to_string(),
            expiration: expiration.to_string(),
            metadata: format!("{:#x}", extras.metadata),
            builder: format!("{:#x}", extras.builder),
            signature,
        })
    }
}

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

    #[test]
    fn test_decimal_to_token_u32() {
        let result = decimal_to_token_u32(Decimal::from_str("1.5").unwrap());
        assert_eq!(result, 1_500_000);
    }

    #[test]
    fn test_generate_seed() {
        let seed1 = generate_seed();
        let seed2 = generate_seed();
        assert_ne!(seed1, seed2);
    }

    #[test]
    fn test_decimal_to_token_u32_edge_cases() {
        // Test zero
        let result = decimal_to_token_u32(Decimal::ZERO);
        assert_eq!(result, 0);

        // Test small decimal
        let result = decimal_to_token_u32(Decimal::from_str("0.000001").unwrap());
        assert_eq!(result, 1);

        // Test large number
        let result = decimal_to_token_u32(Decimal::from_str("1000.0").unwrap());
        assert_eq!(result, 1_000_000_000);
    }

    #[test]
    fn test_get_contract_config() {
        // Test Polygon mainnet
        let config = get_contract_config(137, false);
        assert!(config.is_some());

        // Test with neg risk
        let config_neg = get_contract_config(137, true);
        assert!(config_neg.is_some());

        // Test unsupported chain
        let config_unsupported = get_contract_config(999, false);
        assert!(config_unsupported.is_none());
    }

    #[test]
    fn test_v1_contract_config_mainnet() {
        let config = get_v1_contract_config(137, false).expect("mainnet V1 config");
        assert_eq!(
            config.exchange.to_lowercase(),
            "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E".to_lowercase(),
        );
        assert_eq!(
            config.collateral.to_lowercase(),
            "0x2791Bca1f2de4661ED88A30C99a7a9449Aa84174".to_lowercase(),
        );
    }

    #[test]
    fn test_v2_contract_config_mainnet() {
        let config = get_contract_config(137, false).expect("mainnet config must exist");
        assert_eq!(
            config.exchange.to_lowercase(),
            "0xE111180000d2663C0091e4f400237545B87B996B".to_lowercase(),
        );
        assert_eq!(
            config.collateral.to_lowercase(),
            "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".to_lowercase(),
        );
    }

    #[test]
    fn test_v2_neg_risk_exchange() {
        let config = get_contract_config(137, true).expect("neg-risk config must exist");
        assert_eq!(
            config.exchange.to_lowercase(),
            "0xe2222d279d744050d28e00520010520000310F59".to_lowercase(),
        );
    }

    #[test]
    fn test_amoy_conditional_tokens() {
        let config = get_contract_config(80002, false).expect("amoy config must exist");
        assert_eq!(
            config.conditional_tokens.to_lowercase(),
            "0x69308FB512518e39F9b16112fA8d994F4e2Bf8bB".to_lowercase(),
        );
    }

    #[test]
    fn test_seed_generation_uniqueness() {
        let mut seeds = std::collections::HashSet::new();

        // Generate 1000 seeds and ensure they're all unique
        for _ in 0..1000 {
            let seed = generate_seed();
            assert!(seeds.insert(seed), "Duplicate seed generated");
        }
    }

    #[test]
    fn test_seed_generation_range() {
        for _ in 0..100 {
            let seed = generate_seed();
            // Seeds should be positive and within reasonable range
            assert!(seed > 0);
            assert!(seed < u64::MAX);
        }
    }

    #[test]
    fn test_calculate_market_price_respects_side_amount_semantics() {
        let signer: PrivateKeySigner =
            "0x1234567890123456789012345678901234567890123456789012345678901234"
                .parse()
                .unwrap();
        let builder = OrderBuilder::new(signer, None, None);

        let levels = vec![
            crate::types::BookLevel {
                price: Decimal::from_str("0.50").unwrap(),
                size: Decimal::from_str("10").unwrap(),
            },
            crate::types::BookLevel {
                price: Decimal::from_str("0.55").unwrap(),
                size: Decimal::from_str("10").unwrap(),
            },
        ];

        // BUY amounts are quote-denominated: need 6 USDC -> first level (10 * 0.50 = 5) is not enough.
        let buy_price = builder
            .calculate_market_price(Side::BUY, &levels, Decimal::from_str("6").unwrap())
            .unwrap();
        assert_eq!(buy_price, Decimal::from_str("0.55").unwrap());

        // SELL amounts are base-denominated: need 6 tokens -> first level (size 10) is enough.
        let sell_price = builder
            .calculate_market_price(Side::SELL, &levels, Decimal::from_str("6").unwrap())
            .unwrap();
        assert_eq!(sell_price, Decimal::from_str("0.50").unwrap());
    }

    #[test]
    fn test_create_market_order_uses_input_side() {
        let signer: PrivateKeySigner =
            "0x1234567890123456789012345678901234567890123456789012345678901234"
                .parse()
                .unwrap();
        let builder = OrderBuilder::new(signer, None, None);

        let order = builder
            .create_market_order(
                137,
                &MarketOrderArgs {
                    token_id: "123".to_string(),
                    side: Side::SELL,
                    amount: Decimal::from_str("5").unwrap(),
                },
                Decimal::from_str("0.40").unwrap(),
                &ExtraOrderArgs::default(),
                &OrderOptions {
                    tick_size: Some(Decimal::from_str("0.01").unwrap()),
                    neg_risk: Some(false),
                    fee_rate_bps: None,
                },
            )
            .unwrap();

        assert_eq!(order.side, "SELL");
    }
}