polymarket-rs-sdk 0.1.14

Rust SDK for Polymarket prediction markets - REST APIs, WebSocket streams, order signing, and Safe wallet integration
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
//! Polymarket CLOB REST API Client
//!
//! This module provides a high-level client for interacting with the
//! Polymarket CLOB (Central Limit Order Book) REST API.
//!
//! ## Features
//!
//! - **API Credential Management**: Create, derive, and manage API credentials
//! - **Order Submission**: Submit, cancel, and query orders
//! - **Market Data**: Get order books and market information
//!
//! ## Example
//!
//! ```rust,ignore
//! use polymarket_sdk::clob::{ClobClient, ClobConfig};
//! use alloy_signer_local::PrivateKeySigner;
//!
//! let signer: PrivateKeySigner = "0x...".parse()?;
//! let client = ClobClient::new(ClobConfig::default(), signer)?;
//!
//! // Create API credentials (first time)
//! let creds = client.create_api_credentials().await?;
//!
//! // Submit an order
//! let order = client.submit_order(&signed_order).await?;
//! ```

use std::collections::HashMap;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;

use alloy_primitives::U256;
use alloy_signer_local::PrivateKeySigner;
use governor::{Quota, RateLimiter as GovRateLimiter};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tracing::{debug, info, instrument, warn};

use crate::auth::{
    create_l1_headers, create_l2_headers_with_address, create_l2_headers_with_body_string,
    get_current_unix_time_secs,
};
use crate::core::clob_api_url;
use crate::core::{PolymarketError, Result};
use crate::types::{
    ApiCredentials, BalanceAllowanceParams, BalanceAllowanceResponse, OrderType,
    SignedOrderRequest,
};

// Builder API authentication
use crate::auth::{BuilderApiKeyCreds, BuilderSigner};

type RateLimiter = GovRateLimiter<
    governor::state::NotKeyed,
    governor::state::InMemoryState,
    governor::clock::DefaultClock,
>;

/// CLOB API configuration
#[derive(Debug, Clone)]
pub struct ClobConfig {
    /// CLOB API base URL
    pub base_url: String,
    /// Request timeout
    pub timeout: Duration,
    /// Rate limit (requests per second)
    pub rate_limit_per_second: u32,
    /// User agent string
    pub user_agent: String,
}

impl Default for ClobConfig {
    fn default() -> Self {
        Self {
            // Use helper function to support env var override (POLYMARKET_CLOB_URL)
            base_url: clob_api_url(),
            timeout: Duration::from_secs(30),
            rate_limit_per_second: 5,
            user_agent: "polymarket-sdk/0.1.0".to_string(),
        }
    }
}

impl ClobConfig {
    /// Create a new configuration builder with defaults.
    #[must_use]
    pub fn builder() -> Self {
        Self::default()
    }

    /// Create config from environment variables.
    ///
    /// **Deprecated**: Use `ClobConfig::default()` instead.
    /// The default implementation already supports `POLYMARKET_CLOB_URL` env var override.
    #[must_use]
    #[deprecated(
        since = "0.1.0",
        note = "Use ClobConfig::default() instead. URL override via POLYMARKET_CLOB_URL env var is already supported."
    )]
    pub fn from_env() -> Self {
        Self::default()
    }

    /// Set base URL
    #[must_use]
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// Set request timeout
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set rate limit (requests per second)
    #[must_use]
    pub fn with_rate_limit(mut self, rate_limit: u32) -> Self {
        self.rate_limit_per_second = rate_limit;
        self
    }

    /// Set user agent string
    #[must_use]
    pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = user_agent.into();
        self
    }
}

/// Derive API key response
#[derive(Debug, Deserialize)]
pub struct DeriveApiKeyResponse {
    /// The derived API key
    #[serde(rename = "apiKey")]
    pub api_key: String,
    /// The API secret (base64 encoded)
    pub secret: String,
    /// The passphrase
    pub passphrase: String,
}

/// API key response
#[derive(Debug, Deserialize)]
pub struct ApiKeyResponse {
    /// API key
    #[serde(rename = "apiKey")]
    pub api_key: String,
    /// API secret
    pub secret: String,
    /// Passphrase
    pub passphrase: String,
}

/// Create API key request
#[derive(Debug, Serialize)]
struct CreateApiKeyRequest {
    /// Nonce from derive endpoint
    nonce: String,
}

/// Order response from CLOB
/// Matches official Polymarket API response format
#[derive(Debug, Deserialize)]
pub struct OrderResponse {
    /// Whether the order submission was successful
    pub success: bool,
    /// Error message (empty string if no error)
    #[serde(rename = "errorMsg")]
    pub error_msg: String,
    /// Order ID assigned by the CLOB
    #[serde(rename = "orderID")]
    pub order_id: String,
    /// Transaction hashes if any
    #[serde(rename = "transactionsHashes", default)]
    pub transactions_hashes: Vec<String>,
    /// Order status
    pub status: String,
}

/// Paginated response wrapper from CLOB /data/* endpoints
#[derive(Debug, Deserialize)]
pub struct PaginatedResponse<T> {
    /// Limit used for this page
    pub limit: Option<i32>,
    /// Total count
    pub count: Option<i32>,
    /// Cursor for next page
    pub next_cursor: String,
    /// Data items
    pub data: Vec<T>,
}

/// Open order from CLOB /data/orders endpoint
/// Field names match the actual API response (TypeScript client format)
#[derive(Debug, Deserialize)]
pub struct OpenOrder {
    /// Order ID
    pub id: String,
    /// Order status
    pub status: String,
    /// Owner address
    #[serde(default)]
    pub owner: Option<String>,
    /// Maker address
    pub maker_address: String,
    /// Market slug
    #[serde(default)]
    pub market: Option<String>,
    /// Asset ID (token ID)
    pub asset_id: String,
    /// Side (BUY/SELL)
    pub side: String,
    /// Original size
    pub original_size: String,
    /// Size matched
    pub size_matched: String,
    /// Price
    pub price: String,
    /// Associated trades
    #[serde(default)]
    pub associate_trades: Option<Vec<String>>,
    /// Outcome
    #[serde(default)]
    pub outcome: Option<String>,
    /// Created at timestamp (unix timestamp as number)
    pub created_at: Option<i64>,
    /// Expiration
    #[serde(default)]
    pub expiration: Option<String>,
    /// Order type (GTC, FOK, GTD, FAK)
    #[serde(default, rename = "type")]
    pub order_type: Option<String>,
}

impl OpenOrder {
    /// Get token_id (alias for asset_id for backward compatibility)
    #[must_use]
    pub fn token_id(&self) -> &str {
        &self.asset_id
    }

    /// Get maker (alias for maker_address for backward compatibility)
    #[must_use]
    pub fn maker(&self) -> &str {
        &self.maker_address
    }

    /// Get signer (same as maker for CLOB orders)
    #[must_use]
    pub fn signer(&self) -> &str {
        // Note: CLOB API doesn't return signer separately, it's the same as maker
        &self.maker_address
    }
}

/// Cancel single order request (DELETE /order)
///
/// Polymarket API expects: `{"orderID": "0x..."}`
#[derive(Debug, Serialize)]
struct CancelOrderRequest {
    /// Order ID to cancel
    #[serde(rename = "orderID")]
    order_id: String,
}

/// Cancel response from Polymarket CLOB API
///
/// Used by all cancel endpoints (single, batch, cancel-all, cancel-market-orders).
/// The `not_canceled` field is a map of order_id -> reason explaining why an order
/// couldn't be canceled.
#[derive(Debug, Deserialize)]
pub struct CancelResponse {
    /// Successfully cancelled order IDs
    pub canceled: Vec<String>,
    /// Map of order_id -> reason for orders that couldn't be canceled
    #[serde(default)]
    pub not_canceled: HashMap<String, String>,
}

/// Neg risk response from /neg-risk endpoint
#[derive(Debug, Deserialize)]
pub struct NegRiskResponse {
    /// Whether the token is a negative risk market
    pub neg_risk: bool,
}

/// Tick size response from /tick-size endpoint
#[derive(Debug, Deserialize)]
pub struct TickSizeResponse {
    /// The tick size for the token (e.g., "0.01", "0.001")
    pub minimum_tick_size: String,
}

/// Fee rate response from /fee-rate endpoint
#[derive(Debug, Deserialize)]
pub struct FeeRateResponse {
    /// The base fee rate in basis points (e.g., 0 for 0%, 100 for 1%)
    pub base_fee: u32,
}

/// Order book level (price/size pair)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderBookLevel {
    /// Price level
    pub price: String,
    /// Size at this price level
    pub size: String,
}

/// Order book summary response from /book endpoint
///
/// This is the comprehensive response from the Polymarket CLOB `/book` endpoint
/// that contains all market parameters including neg_risk, tick_size, and min_order_size.
///
/// Reference: <https://docs.polymarket.com/api-reference/orderbook/get-order-book-summary>
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderBookSummary {
    /// Market identifier (condition ID)
    pub market: String,
    /// Asset identifier (token ID)
    pub asset_id: String,
    /// Timestamp of the order book snapshot
    pub timestamp: String,
    /// Hash of the order book state
    pub hash: String,
    /// Array of bid levels (buy orders)
    pub bids: Vec<OrderBookLevel>,
    /// Array of ask levels (sell orders)
    pub asks: Vec<OrderBookLevel>,
    /// Minimum order size for this market
    pub min_order_size: String,
    /// Minimum price increment (tick size)
    pub tick_size: String,
    /// Whether negative risk is enabled for this market
    pub neg_risk: bool,
}

impl OrderBookSummary {
    /// Check if the orderbook has any liquidity (bids or asks)
    #[must_use]
    pub fn has_liquidity(&self) -> bool {
        !self.bids.is_empty() || !self.asks.is_empty()
    }

    /// Get the best bid price (highest buy price)
    #[must_use]
    pub fn best_bid(&self) -> Option<&str> {
        self.bids.first().map(|l| l.price.as_str())
    }

    /// Get the best ask price (lowest sell price)
    #[must_use]
    pub fn best_ask(&self) -> Option<&str> {
        self.asks.first().map(|l| l.price.as_str())
    }

    /// Calculate the spread between best bid and best ask
    #[must_use]
    pub fn spread(&self) -> Option<f64> {
        let bid: f64 = self.best_bid()?.parse().ok()?;
        let ask: f64 = self.best_ask()?.parse().ok()?;
        Some(ask - bid)
    }
}

/// CLOB API client
#[derive(Clone)]
pub struct ClobClient {
    config: ClobConfig,
    client: Client,
    signer: PrivateKeySigner,
    rate_limiter: Arc<RateLimiter>,
    /// Stored API credentials (set after creation)
    api_credentials: Option<ApiCredentials>,
    /// Optional explicit address for Builder API auth (when signer ≠ API key owner)
    auth_address: Option<String>,
    /// Optional Builder signer for Integrator authentication
    builder_signer: Option<BuilderSigner>,
}

impl ClobClient {
    /// Create a new CLOB client
    pub fn new(config: ClobConfig, signer: PrivateKeySigner) -> Result<Self> {
        let client = Client::builder()
            .timeout(config.timeout)
            .user_agent(&config.user_agent)
            .gzip(true)
            .build()
            .map_err(|e| PolymarketError::config(format!("Failed to create HTTP client: {e}")))?;

        let quota = Quota::per_second(
            NonZeroU32::new(config.rate_limit_per_second).unwrap_or(NonZeroU32::new(5).unwrap()),
        );
        let rate_limiter = Arc::new(GovRateLimiter::direct(quota));

        Ok(Self {
            config,
            client,
            signer,
            rate_limiter,
            api_credentials: None,
            auth_address: None,
            builder_signer: None,
        })
    }

    /// Create client from environment variables.
    ///
    /// **Deprecated**: Use `ClobClient::new(ClobConfig::default(), signer)` instead.
    #[deprecated(
        since = "0.1.0",
        note = "Use ClobClient::new(ClobConfig::default(), signer) instead"
    )]
    #[allow(deprecated)]
    pub fn from_env(signer: PrivateKeySigner) -> Result<Self> {
        Self::new(ClobConfig::from_env(), signer)
    }

    /// Set API credentials for L2 authentication
    #[must_use]
    pub fn with_api_credentials(mut self, credentials: ApiCredentials) -> Self {
        self.api_credentials = Some(credentials);
        self
    }

    /// Set explicit auth address (for Builder API authentication)
    ///
    /// Use this when the order signer and API credentials owner are different addresses.
    /// This is common when using Builder API credentials.
    #[must_use]
    pub fn with_auth_address(mut self, address: impl Into<String>) -> Self {
        self.auth_address = Some(address.into());
        self
    }

    /// Set Builder API signer for Integrator authentication
    ///
    /// Use this when submitting orders on behalf of users via Builder API.
    /// The Builder credentials authenticate the Integrator, while the order
    /// signature authenticates the user's wallet.
    ///
    /// # Example
    /// ```ignore
    /// let clob_client = ClobClient::from_env(dummy_signer)
    ///     .with_api_credentials(builder_credentials)
    ///     .with_builder_signer(builder_credentials)  // Enables Builder headers
    ///     .with_auth_address(server_wallet_address);
    /// ```
    #[must_use]
    pub fn with_builder_signer(mut self, credentials: ApiCredentials) -> Self {
        let builder_creds = BuilderApiKeyCreds {
            key: credentials.api_key,
            secret: credentials.secret, // Base64 encoded
            passphrase: credentials.passphrase,
        };
        self.builder_signer = Some(BuilderSigner::new(builder_creds));
        self
    }

    /// Get the signer's address
    #[must_use]
    pub fn address(&self) -> String {
        format!("{:?}", self.signer.address())
    }

    /// Get the address to use for L2 authentication.
    ///
    /// Uses explicit `auth_address` if set (for Builder API scenarios where the
    /// order signer and API credentials owner are different), otherwise falls
    /// back to the signer's address.
    ///
    /// This ensures consistent address handling across all L2-authenticated methods.
    fn get_auth_address(&self) -> String {
        if let Some(ref addr) = self.auth_address {
            if addr.starts_with("0x") {
                addr.clone()
            } else {
                format!("0x{}", addr)
            }
        } else {
            format!("{:?}", self.signer.address())
        }
    }

    /// Wait for rate limiter
    async fn wait_for_rate_limit(&self) {
        self.rate_limiter.until_ready().await;
    }

    /// Derive API key (step 1 of credential creation)
    ///
    /// This gets a nonce and derives the API key from the wallet signature.
    #[instrument(skip(self))]
    pub async fn derive_api_key(&self, nonce: Option<U256>) -> Result<DeriveApiKeyResponse> {
        self.wait_for_rate_limit().await;

        let endpoint = "/auth/derive-api-key";
        let url = format!("{}{}", self.config.base_url, endpoint);

        let headers = create_l1_headers(&self.signer, nonce)?;

        debug!(address = %self.address(), "Deriving API key");

        let mut req_builder = self.client.get(&url);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: DeriveApiKeyResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse derive response: {e}"), e)
        })?;

        info!(address = %self.address(), "API key derived successfully");

        Ok(result)
    }

    /// Derive API key with pre-computed signature (for Privy ServerWallet)
    ///
    /// This variant accepts a pre-computed EIP-712 signature, useful when using
    /// external signing services like Privy ServerWallet that don't expose private keys.
    ///
    /// # Workflow
    ///
    /// 1. Generate timestamp and nonce
    /// 2. Use `build_clob_auth_typed_data` from auth module to construct typed data
    /// 3. Call Privy ServerWallet API to sign the typed data
    /// 4. Call this method with the signature
    ///
    /// # Arguments
    ///
    /// * `address` - Wallet address (hex string with or without 0x prefix)
    /// * `signature` - EIP-712 signature (hex string with 0x prefix)
    /// * `timestamp` - Unix timestamp string used in signature
    /// * `nonce` - Nonce value used in signature
    ///
    /// # Returns
    ///
    /// Derived API credentials (api_key, secret, passphrase)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use polymarket_sdk::auth::{build_clob_auth_typed_data, get_current_unix_time_secs};
    /// use alloy_primitives::{Address, U256};
    ///
    /// // 1. Prepare signature data
    /// let address: Address = "0x1234...".parse()?;
    /// let timestamp = get_current_unix_time_secs().to_string();
    /// let nonce = U256::ZERO;
    ///
    /// // 2. Build typed data for Privy
    /// let typed_data = build_clob_auth_typed_data(address, &timestamp, nonce);
    ///
    /// // 3. Call Privy ServerWallet API (pseudo-code)
    /// let signature = privy_client.sign_typed_data(server_wallet_id, typed_data).await?;
    ///
    /// // 4. Derive API key with signature
    /// let credentials = clob_client
    ///     .derive_api_key_with_signature(&format!("{:?}", address), &signature, &timestamp, nonce)
    ///     .await?;
    /// ```
    #[instrument(skip(self, signature))]
    pub async fn derive_api_key_with_signature(
        &self,
        address: &str,
        signature: &str,
        timestamp: &str,
        nonce: U256,
    ) -> Result<DeriveApiKeyResponse> {
        self.wait_for_rate_limit().await;

        let endpoint = "/auth/derive-api-key";
        let url = format!("{}{}", self.config.base_url, endpoint);

        // Ensure address has 0x prefix
        let address = if address.starts_with("0x") {
            address.to_string()
        } else {
            format!("0x{}", address)
        };

        // Ensure signature has 0x prefix
        let signature = if signature.starts_with("0x") {
            signature.to_string()
        } else {
            format!("0x{}", signature)
        };

        // Build L1 auth headers manually with pre-computed signature
        let headers = HashMap::from([
            ("poly_address", address.clone()),
            ("poly_signature", signature),
            ("poly_timestamp", timestamp.to_string()),
            ("poly_nonce", nonce.to_string()),
        ]);

        debug!(address = %address, "Deriving API key with pre-computed signature");

        let mut req_builder = self.client.get(&url);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: DeriveApiKeyResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse derive response: {e}"), e)
        })?;

        info!(address = %address, "API key derived successfully with pre-computed signature");

        Ok(result)
    }

    /// Create API key with pre-computed signature (for server wallet registration)
    ///
    /// This is the first-time registration step that tells Polymarket about this wallet.
    /// After calling this once, you can use derive_api_key_with_signature for subsequent requests.
    #[instrument(skip(self, signature))]
    pub async fn create_api_key_with_signature(
        &self,
        address: &str,
        signature: &str,
        timestamp: &str,
        nonce: U256,
    ) -> Result<ApiKeyResponse> {
        self.wait_for_rate_limit().await;

        let endpoint = "/auth/api-key";
        let url = format!("{}{}", self.config.base_url, endpoint);

        // Ensure address has 0x prefix
        let address = if address.starts_with("0x") {
            address.to_string()
        } else {
            format!("0x{}", address)
        };

        // Ensure signature has 0x prefix
        let signature = if signature.starts_with("0x") {
            signature.to_string()
        } else {
            format!("0x{}", signature)
        };

        // Build L1 auth headers manually with pre-computed signature
        let headers = HashMap::from([
            ("poly_address", address.clone()),
            ("poly_signature", signature),
            ("poly_timestamp", timestamp.to_string()),
            ("poly_nonce", nonce.to_string()),
        ]);

        let body = CreateApiKeyRequest {
            nonce: nonce.to_string(),
        };

        debug!(address = %address, "Creating API key with pre-computed signature (first-time registration)");

        let mut req_builder = self.client.post(&url).json(&body);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: ApiKeyResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse create response: {e}"), e)
        })?;

        info!(address = %address, "API key created successfully (wallet registered)");

        Ok(result)
    }

    /// Derive or create API key with pre-computed signature (for Privy ServerWallet)
    ///
    /// This is a convenience method that handles the common case where a wallet
    /// may or may not have been registered with Polymarket CLOB API yet.
    ///
    /// # Workflow
    ///
    /// 1. Try to derive API key (for existing registrations)
    /// 2. If "Could not derive api key" error (wallet not registered):
    ///    - First call create_api_key_with_signature to register the wallet
    ///    - Then retry derive_api_key_with_signature
    /// 3. Return the derived credentials
    ///
    /// # Arguments
    ///
    /// * `address` - Wallet address (hex string with or without 0x prefix)
    /// * `signature` - EIP-712 signature (hex string with 0x prefix)
    /// * `timestamp` - Unix timestamp string used in signature
    /// * `nonce` - Nonce value used in signature
    ///
    /// # Returns
    ///
    /// Derived API credentials (api_key, secret, passphrase)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use polymarket_sdk::auth::{build_clob_auth_typed_data, get_current_unix_time_secs};
    /// use alloy_primitives::{Address, U256};
    ///
    /// // Prepare and sign typed data (see derive_api_key_with_signature for details)
    /// let credentials = clob_client
    ///     .derive_or_create_api_key(&address, &signature, &timestamp, nonce)
    ///     .await?;
    /// ```
    #[instrument(skip(self, signature))]
    pub async fn derive_or_create_api_key(
        &self,
        address: &str,
        signature: &str,
        timestamp: &str,
        nonce: U256,
    ) -> Result<DeriveApiKeyResponse> {
        // Try derive first (common case: wallet already registered)
        match self
            .derive_api_key_with_signature(address, signature, timestamp, nonce)
            .await
        {
            Ok(response) => Ok(response),
            Err(e) if e.is_wallet_not_registered() => {
                // Wallet not registered - register it first, then retry derive
                info!(
                    address = %address,
                    "Wallet not registered with CLOB API, registering first"
                );

                // Step 1: Create/register the API key (first-time registration)
                self.create_api_key_with_signature(address, signature, timestamp, nonce)
                    .await?;

                // Step 2: Retry derive (should succeed now)
                info!(address = %address, "Wallet registered, retrying derive");
                self.derive_api_key_with_signature(address, signature, timestamp, nonce)
                    .await
            }
            Err(e) => Err(e),
        }
    }

    /// Create API key (step 2 of credential creation)
    ///
    /// This registers the derived API key with the CLOB.
    #[instrument(skip(self))]
    pub async fn create_api_key(&self, nonce: U256) -> Result<ApiKeyResponse> {
        self.wait_for_rate_limit().await;

        let endpoint = "/auth/api-key";
        let url = format!("{}{}", self.config.base_url, endpoint);

        let headers = create_l1_headers(&self.signer, Some(nonce))?;

        let body = CreateApiKeyRequest {
            nonce: nonce.to_string(),
        };

        debug!(address = %self.address(), "Creating API key");

        let mut req_builder = self.client.post(&url).json(&body);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: ApiKeyResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse create response: {e}"), e)
        })?;

        info!(address = %self.address(), "API key created successfully");

        Ok(result)
    }

    /// Create API credentials (complete flow)
    ///
    /// This performs the full API credential creation flow:
    /// 1. Derive API key with L1 signature
    /// 2. Create/register API key
    ///
    /// # Returns
    /// Complete API credentials ready for L2 authentication
    #[instrument(skip(self))]
    pub async fn create_api_credentials(&self) -> Result<ApiCredentials> {
        info!(address = %self.address(), "Creating API credentials");

        // Step 1: Derive API key (ensures the key derivation is set up)
        let _derive_result = self.derive_api_key(None).await?;

        // Step 2: Create API key with nonce 0 (typical for new credentials)
        let create_result = self.create_api_key(U256::ZERO).await?;

        let credentials = ApiCredentials {
            api_key: create_result.api_key,
            secret: create_result.secret,
            passphrase: create_result.passphrase,
        };

        info!(address = %self.address(), "API credentials created successfully");

        Ok(credentials)
    }

    /// Submit an order
    ///
    /// Requires API credentials to be set via `with_api_credentials`.
    ///
    /// # Arguments
    ///
    /// * `order` - The signed order request
    /// * `order_type` - The order type (GTC for limit orders, FOK for market orders, etc.)
    ///
    /// # Order Types
    ///
    /// - `OrderType::GTC` - Good Till Cancelled (limit order)
    /// - `OrderType::FOK` - Fill Or Kill (market order, must fill completely or cancel)
    /// - `OrderType::GTD` - Good Till Date
    /// - `OrderType::FAK` - Fill And Kill (partial fills allowed, unfilled portion cancelled)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use polymarket_sdk::types::OrderType;
    ///
    /// // Limit order (GTC)
    /// client.submit_order(&signed_order, OrderType::GTC).await?;
    ///
    /// // Market order (FOK)
    /// client.submit_order(&signed_order, OrderType::FOK).await?;
    /// ```
    #[instrument(skip(self, order))]
    pub async fn submit_order(
        &self,
        order: &SignedOrderRequest,
        order_type: OrderType,
    ) -> Result<OrderResponse> {
        use crate::types::NewOrder;

        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for order submission")
        })?;

        let endpoint = "/order";
        let url = format!("{}{}", self.config.base_url, endpoint);

        // IMPORTANT: Convert SignedOrderRequest to NewOrder format
        // - Use api_key as owner (NOT wallet address) - matches TypeScript SDK behavior
        // - Wrap order data in nested structure with orderType and deferExec
        let new_order = NewOrder::from_signed_order(order, &api_creds.api_key, order_type, false);

        // CRITICAL FIX: Serialize JSON ONCE and reuse for all operations
        // This ensures L2 HMAC, Builder HMAC, and HTTP body all use identical JSON
        let body_str = serde_json::to_string(&new_order)
            .map_err(|e| PolymarketError::parse(format!("Failed to serialize order: {}", e)))?;

        // CRITICAL FIX: Get timestamp ONCE and reuse for L2 and Builder headers
        // This ensures both headers use the same timestamp, avoiding signature mismatches
        let timestamp = get_current_unix_time_secs();

        // Get the auth address (either explicit or derived from signer)
        let address = if let Some(ref addr) = self.auth_address {
            if addr.starts_with("0x") {
                addr.clone()
            } else {
                format!("0x{}", addr)
            }
        } else {
            format!("{:?}", self.signer.address())
        };

        // 1. Create standard L2 headers (POLY_*) using pre-serialized body string and shared timestamp
        let mut headers = create_l2_headers_with_body_string(
            &address, api_creds, "POST", endpoint, &body_str, timestamp,
        )?;

        // 2. Inject Builder headers (POLY_BUILDER_*) if Builder signer is configured
        // Use the SAME body_str and SAME timestamp for consistency
        if let Some(ref builder) = self.builder_signer {
            info!("Builder signer configured, generating Builder headers");

            let builder_headers = builder
                .create_builder_header_payload(
                    "POST",
                    endpoint,
                    Some(&body_str),
                    Some(timestamp as i64),
                )
                .map_err(|e| PolymarketError::internal(format!("Builder header error: {}", e)))?;

            info!(
                header_count = builder_headers.len(),
                timestamp = timestamp,
                "Builder headers generated with shared timestamp"
            );

            // Merge Builder headers into existing headers
            // Note: We leak the strings to get 'static lifetime for HashMap keys
            for (key, value) in builder_headers {
                let static_key: &'static str = Box::leak(key.into_boxed_str());
                headers.insert(static_key, value);
            }

            info!(token_id = %order.token_id, side = %order.side, "Submitting order with Builder authentication");
        } else {
            warn!("Builder signer NOT configured - order may fail with 401 Unauthorized");
            info!(token_id = %order.token_id, side = %order.side, "Submitting order WITHOUT Builder authentication");
        }

        // Debug: Print the actual JSON being sent (NewOrder format)
        info!(order_json = %body_str, timestamp = timestamp, "Order JSON payload being sent to Polymarket (NewOrder format)");

        // CRITICAL FIX: Use pre-serialized body string instead of re-serializing with .json()
        // This ensures HTTP body matches exactly what was used for HMAC calculation
        let mut req_builder = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .body(body_str.clone());
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: OrderResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse order response: {e}"), e)
        })?;

        // Check if order submission was successful
        if !result.success {
            return Err(PolymarketError::api(
                400,
                format!(
                    "Order rejected: {} (status: {})",
                    result.error_msg, result.status
                ),
            ));
        }

        info!(
            order_id = %result.order_id,
            status = %result.status,
            success = result.success,
            "Order submitted successfully"
        );

        Ok(result)
    }

    /// Get a single order by its ID
    ///
    /// Retrieves detailed information about an existing order.
    /// This endpoint requires L2 authentication headers.
    ///
    /// Reference: <https://docs.polymarket.com/developers/CLOB/orders/get-order>
    ///
    /// # Arguments
    /// * `order_id` - The order hash/ID to query
    ///
    /// # Returns
    /// * `Ok(Some(OpenOrder))` - Order details if found
    /// * `Ok(None)` - Order not found
    /// * `Err(...)` - API error
    ///
    /// # Example
    /// ```rust,ignore
    /// let order = client.get_order("0xb816482a5187a3d3db49cbaf6fe3ddf24f53e6c712b5a4bf5e01d0ec7b11dabc").await?;
    /// if let Some(order) = order {
    ///     println!("Order status: {}", order.status);
    ///     println!("Price: {}", order.price);
    ///     println!("Size matched: {}", order.size_matched);
    /// }
    /// ```
    #[instrument(skip(self))]
    pub async fn get_order(&self, order_id: &str) -> Result<Option<OpenOrder>> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for querying order")
        })?;

        let endpoint = format!("/data/order/{}", order_id);
        let url = format!("{}{}", self.config.base_url, endpoint);

        // Use auth_address for L2 authentication (supports Builder API scenarios)
        let address = self.get_auth_address();
        let headers =
            create_l2_headers_with_address::<String>(&address, api_creds, "GET", &endpoint, None)?;

        debug!(order_id = %order_id, "Getting order details");

        let mut req_builder = self.client.get(&url);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        // Handle 404 as order not found
        if status.as_u16() == 404 {
            info!(order_id = %order_id, "Order not found (404)");
            return Ok(None);
        }

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        // Get response body as text first to handle various response formats
        // The API may return HTTP 200 with null, empty object, or error message
        // when the order is not found (similar to official SDK 0.3.x behavior)
        let body = response.text().await.unwrap_or_default();

        // Handle empty response or null
        if body.is_empty() || body == "null" || body == "{}" {
            info!(order_id = %order_id, "Order not found (empty/null response)");
            return Ok(None);
        }

        // Try to parse as JSON Value first to check for error responses
        let json_value: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
            PolymarketError::parse_with_source(
                format!("Failed to parse order response as JSON: {e}"),
                e,
            )
        })?;

        // Check if response contains an error field or indicates not found
        if let Some(obj) = json_value.as_object() {
            // Handle {"error": "..."} responses
            if obj.contains_key("error") {
                let error_msg = obj
                    .get("error")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown error");
                // Treat error responses as "not found" if they indicate the order doesn't exist
                if error_msg.to_lowercase().contains("not found")
                    || error_msg.to_lowercase().contains("does not exist")
                {
                    info!(order_id = %order_id, error = %error_msg, "Order not found (error response)");
                    return Ok(None);
                }
                // For other errors, return as API error
                return Err(PolymarketError::api(200, format!("API error: {error_msg}")));
            }

            // Check if the response has required fields for OpenOrder
            // If it's missing essential fields, treat as not found
            if !obj.contains_key("id") && !obj.contains_key("order_id") {
                info!(order_id = %order_id, "Order not found (missing required fields)");
                return Ok(None);
            }
        } else if json_value.is_null() {
            info!(order_id = %order_id, "Order not found (null JSON)");
            return Ok(None);
        }

        // Now try to deserialize as OpenOrder
        let order: OpenOrder = serde_json::from_value(json_value).map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse order response: {e}"), e)
        })?;

        debug!(
            order_id = %order_id,
            status = %order.status,
            price = %order.price,
            "Retrieved order details"
        );

        Ok(Some(order))
    }

    /// Get open orders for the signer
    #[instrument(skip(self))]
    pub async fn get_open_orders(&self) -> Result<Vec<OpenOrder>> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for querying orders")
        })?;

        // IMPORTANT: Use /data/orders endpoint for GET (not /orders which is for POST)
        let endpoint = "/data/orders";
        let url = format!("{}{}", self.config.base_url, endpoint);

        // Use auth_address for L2 authentication (supports Builder API scenarios)
        let address = self.get_auth_address();
        let headers =
            create_l2_headers_with_address::<String>(&address, api_creds, "GET", endpoint, None)?;

        debug!(address = %self.address(), "Getting open orders");

        let mut req_builder = self.client.get(&url);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        // Parse as paginated response
        let paginated: PaginatedResponse<OpenOrder> = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse orders response: {e}"), e)
        })?;

        debug!(count = %paginated.data.len(), "Retrieved open orders");

        Ok(paginated.data)
    }

    /// Cancel a single order by ID
    ///
    /// Sends `DELETE /order` with body `{"orderID": "0x..."}`.
    ///
    /// Reference: <https://docs.polymarket.com/developers/CLOB/orders/cancel-orders#cancel-an-single-order>
    ///
    /// # Arguments
    /// * `order_id` - The order hash/ID to cancel
    ///
    /// # Example
    /// ```rust,ignore
    /// let resp = client.cancel_order("0x38a73eed...").await?;
    /// println!("Canceled: {:?}", resp.canceled);
    /// ```
    #[instrument(skip(self))]
    pub async fn cancel_order(&self, order_id: &str) -> Result<CancelResponse> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for cancelling order")
        })?;

        let endpoint = "/order";
        let url = format!("{}{}", self.config.base_url, endpoint);

        let body = CancelOrderRequest {
            order_id: order_id.to_string(),
        };

        // Use auth_address for L2 authentication (supports Builder API scenarios)
        // Serialize body once to ensure consistent HMAC calculation
        let address = self.get_auth_address();
        let body_str = serde_json::to_string(&body)
            .map_err(|e| PolymarketError::parse(format!("Failed to serialize: {}", e)))?;
        let timestamp = get_current_unix_time_secs();
        let headers = create_l2_headers_with_body_string(
            &address, api_creds, "DELETE", endpoint, &body_str, timestamp,
        )?;

        debug!(order_id = %order_id, "Cancelling single order");

        let mut req_builder = self
            .client
            .delete(&url)
            .header("Content-Type", "application/json")
            .body(body_str);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: CancelResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse cancel response: {e}"), e)
        })?;

        info!(order_id = %order_id, cancelled = ?result.canceled, "Order cancelled");

        Ok(result)
    }

    /// Cancel multiple orders by IDs
    ///
    /// Sends `DELETE /orders` with body `["0x...", "0x..."]` (pure JSON array).
    ///
    /// Reference: <https://docs.polymarket.com/developers/CLOB/orders/cancel-orders#cancel-multiple-orders>
    ///
    /// # Arguments
    /// * `order_ids` - List of order hashes/IDs to cancel
    ///
    /// # Example
    /// ```rust,ignore
    /// let resp = client.cancel_orders(vec![
    ///     "0x38a73eed...".to_string(),
    ///     "0xaaaa...".to_string(),
    /// ]).await?;
    /// println!("Canceled: {:?}", resp.canceled);
    /// ```
    #[instrument(skip(self))]
    pub async fn cancel_orders(&self, order_ids: Vec<String>) -> Result<CancelResponse> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for cancelling orders")
        })?;

        // NOTE: Batch cancel uses /orders (plural), not /order
        let endpoint = "/orders";
        let url = format!("{}{}", self.config.base_url, endpoint);

        // Polymarket expects a raw JSON array: ["0x...", "0x..."]
        // NOT an object like {"orderIds": [...]}
        let body_str = serde_json::to_string(&order_ids)
            .map_err(|e| PolymarketError::parse(format!("Failed to serialize: {}", e)))?;

        // Use auth_address for L2 authentication (supports Builder API scenarios)
        let address = self.get_auth_address();
        let timestamp = get_current_unix_time_secs();
        let headers = create_l2_headers_with_body_string(
            &address, api_creds, "DELETE", endpoint, &body_str, timestamp,
        )?;

        debug!(count = order_ids.len(), "Cancelling multiple orders");

        let mut req_builder = self
            .client
            .delete(&url)
            .header("Content-Type", "application/json")
            .body(body_str);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: CancelResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse cancel response: {e}"), e)
        })?;

        info!(cancelled = ?result.canceled, "Orders cancelled");

        Ok(result)
    }

    /// Cancel all open orders
    ///
    /// Sends `DELETE /cancel-all` with no body.
    ///
    /// Reference: <https://docs.polymarket.com/developers/CLOB/orders/cancel-orders#cancel-all-orders>
    ///
    /// # Example
    /// ```rust,ignore
    /// let resp = client.cancel_all_orders().await?;
    /// println!("Canceled: {:?}", resp.canceled);
    /// ```
    #[instrument(skip(self))]
    pub async fn cancel_all_orders(&self) -> Result<CancelResponse> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for cancelling orders")
        })?;

        let endpoint = "/cancel-all";
        let url = format!("{}{}", self.config.base_url, endpoint);

        // Use auth_address for L2 authentication (supports Builder API scenarios)
        let address = self.get_auth_address();
        let headers = create_l2_headers_with_address::<String>(
            &address, api_creds, "DELETE", endpoint, None,
        )?;

        debug!(address = %self.address(), "Cancelling all orders");

        let mut req_builder = self.client.delete(&url);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: CancelResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse cancel response: {e}"), e)
        })?;

        info!(cancelled = ?result.canceled, "All orders cancelled");

        Ok(result)
    }

    /// Cancel orders for a specific market
    ///
    /// Sends `DELETE /cancel-market-orders` with body `{"market": "...", "asset_id": "..."}`.
    /// At least one of `market` (condition_id) or `asset_id` (token_id) should be provided.
    ///
    /// Reference: <https://docs.polymarket.com/developers/CLOB/orders/cancel-orders#cancel-orders-from-market>
    ///
    /// # Arguments
    /// * `market` - Optional condition ID of the market
    /// * `asset_id` - Optional token/asset ID
    ///
    /// # Example
    /// ```rust,ignore
    /// // Cancel all orders for a specific market
    /// let resp = client.cancel_market_orders(
    ///     Some("0xbd31dc8a..."),
    ///     None,
    /// ).await?;
    ///
    /// // Cancel all orders for a specific asset
    /// let resp = client.cancel_market_orders(
    ///     None,
    ///     Some("52114319501245915516055106046884209969926127482827954674443846427813813222426"),
    /// ).await?;
    /// ```
    #[instrument(skip(self))]
    pub async fn cancel_market_orders(
        &self,
        market: Option<&str>,
        asset_id: Option<&str>,
    ) -> Result<CancelResponse> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for cancelling market orders")
        })?;

        let endpoint = "/cancel-market-orders";
        let url = format!("{}{}", self.config.base_url, endpoint);

        // Build the body with optional fields
        let mut body_map = serde_json::Map::new();
        if let Some(m) = market {
            body_map.insert(
                "market".to_string(),
                serde_json::Value::String(m.to_string()),
            );
        }
        if let Some(a) = asset_id {
            body_map.insert(
                "asset_id".to_string(),
                serde_json::Value::String(a.to_string()),
            );
        }
        let body_str = serde_json::to_string(&body_map)
            .map_err(|e| PolymarketError::parse(format!("Failed to serialize: {}", e)))?;

        // Use auth_address for L2 authentication (supports Builder API scenarios)
        let address = self.get_auth_address();
        let timestamp = get_current_unix_time_secs();
        let headers = create_l2_headers_with_body_string(
            &address, api_creds, "DELETE", endpoint, &body_str, timestamp,
        )?;

        debug!(market = ?market, asset_id = ?asset_id, "Cancelling market orders");

        let mut req_builder = self
            .client
            .delete(&url)
            .header("Content-Type", "application/json")
            .body(body_str);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: CancelResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse cancel response: {e}"), e)
        })?;

        info!(market = ?market, asset_id = ?asset_id, cancelled = ?result.canceled, "Market orders cancelled");

        Ok(result)
    }

    /// Get the order book summary for a token ID
    ///
    /// Queries the Polymarket CLOB `/book` endpoint to retrieve the complete
    /// order book summary including market parameters like `neg_risk`, `tick_size`,
    /// and `min_order_size`, as well as the current bid/ask levels.
    ///
    /// This is the recommended method to use instead of separate calls to
    /// `get_neg_risk`, `get_tick_size`, and `check_orderbook_exists`.
    ///
    /// Reference: <https://docs.polymarket.com/api-reference/orderbook/get-order-book-summary>
    ///
    /// # Arguments
    /// * `token_id` - The token ID (CLOB token / asset ID) to query
    ///
    /// # Returns
    /// * `Ok(Some(OrderBookSummary))` - The order book exists and summary is returned
    /// * `Ok(None)` - The order book does not exist (market closed or invalid token)
    /// * `Err(...)` - API error occurred
    ///
    /// # Example
    /// ```rust,ignore
    /// let summary = client.get_orderbook_summary(token_id).await?;
    /// if let Some(book) = summary {
    ///     println!("neg_risk: {}", book.neg_risk);
    ///     println!("tick_size: {}", book.tick_size);
    ///     println!("min_order_size: {}", book.min_order_size);
    ///     println!("bids: {:?}", book.bids);
    ///     println!("asks: {:?}", book.asks);
    /// } else {
    ///     println!("Orderbook does not exist");
    /// }
    /// ```
    #[instrument(skip(self))]
    pub async fn get_orderbook_summary(&self, token_id: &str) -> Result<Option<OrderBookSummary>> {
        self.wait_for_rate_limit().await;

        let endpoint = "/book";
        let url = format!("{}{}?token_id={}", self.config.base_url, endpoint, token_id);

        debug!(token_id = %token_id, "Fetching orderbook summary");

        let response = self.client.get(&url).send().await?;
        let status = response.status();

        // Get response body
        let body = response.text().await.unwrap_or_default();

        // API returns 200 with {"error": "..."} for non-existent orderbooks
        if body.contains("does not exist") || body.contains("No orderbook") {
            info!(token_id = %token_id, "Orderbook does not exist");
            return Ok(None);
        }

        // Handle 404 as orderbook not found
        if status.as_u16() == 404 {
            info!(token_id = %token_id, "Orderbook not found (404)");
            return Ok(None);
        }

        if !status.is_success() {
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        // Parse the orderbook summary
        let summary: OrderBookSummary = serde_json::from_str(&body).map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse orderbook summary: {e}"), e)
        })?;

        debug!(
            token_id = %token_id,
            neg_risk = %summary.neg_risk,
            tick_size = %summary.tick_size,
            min_order_size = %summary.min_order_size,
            bids_count = %summary.bids.len(),
            asks_count = %summary.asks.len(),
            "Got orderbook summary"
        );

        Ok(Some(summary))
    }

    /// Get the neg_risk status for a token ID
    ///
    /// **Deprecated**: Use [`Self::get_orderbook_summary`] instead, which returns all market
    /// parameters in a single API call.
    ///
    /// Queries the Polymarket CLOB API to determine if a market/token uses
    /// negative risk contracts. This is crucial for signing orders with the
    /// correct exchange contract address.
    ///
    /// # Arguments
    /// * `token_id` - The token ID (condition token) to check
    ///
    /// # Returns
    /// * `true` if the market uses negative risk contracts (use negRiskExchange)
    /// * `false` if the market uses standard contracts (use exchange)
    #[deprecated(
        since = "0.2.0",
        note = "Use get_orderbook_summary() instead, which returns neg_risk, tick_size, and min_order_size in a single API call"
    )]
    #[instrument(skip(self))]
    pub async fn get_neg_risk(&self, token_id: &str) -> Result<bool> {
        self.wait_for_rate_limit().await;

        let endpoint = "/neg-risk";
        let url = format!("{}{}?token_id={}", self.config.base_url, endpoint, token_id);

        debug!(token_id = %token_id, "Querying neg_risk status");

        let response = self.client.get(&url).send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: NegRiskResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse neg_risk response: {e}"), e)
        })?;

        debug!(token_id = %token_id, neg_risk = %result.neg_risk, "Got neg_risk status");

        Ok(result.neg_risk)
    }

    /// Get the tick size for a token ID
    ///
    /// **Deprecated**: Use [`Self::get_orderbook_summary`] instead, which returns all market
    /// parameters in a single API call.
    ///
    /// Queries the Polymarket CLOB API to get the minimum tick size for
    /// price rounding on a specific market.
    ///
    /// # Arguments
    /// * `token_id` - The token ID (condition token) to check
    ///
    /// # Returns
    /// The tick size as a string (e.g., "0.01", "0.001", "0.0001")
    #[deprecated(
        since = "0.2.0",
        note = "Use get_orderbook_summary() instead, which returns neg_risk, tick_size, and min_order_size in a single API call"
    )]
    #[instrument(skip(self))]
    pub async fn get_tick_size(&self, token_id: &str) -> Result<String> {
        self.wait_for_rate_limit().await;

        let endpoint = "/tick-size";
        let url = format!("{}{}?token_id={}", self.config.base_url, endpoint, token_id);

        debug!(token_id = %token_id, "Querying tick size");

        let response = self.client.get(&url).send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: TickSizeResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(
                format!("Failed to parse tick_size response: {e}"),
                e,
            )
        })?;

        debug!(token_id = %token_id, tick_size = %result.minimum_tick_size, "Got tick size");

        Ok(result.minimum_tick_size)
    }

    /// Get the fee rate for a token ID
    ///
    /// Queries the Polymarket CLOB API to get the fee rate (in basis points)
    /// for a specific market/token. This is crucial for signing orders with
    /// the correct fee rate that matches what the API expects.
    ///
    /// # Arguments
    /// * `token_id` - The token ID (condition token) to check
    ///
    /// # Returns
    /// The fee rate in basis points (e.g., 0 for 0%, 100 for 1%)
    ///
    /// # Note
    /// Orders MUST use the fee rate returned by this API, otherwise the
    /// EIP-712 signature will not match and the order will be rejected
    /// with "invalid signature".
    #[instrument(skip(self))]
    pub async fn get_fee_rate(&self, token_id: &str) -> Result<u32> {
        self.wait_for_rate_limit().await;

        let endpoint = "/fee-rate";
        let url = format!("{}{}?token_id={}", self.config.base_url, endpoint, token_id);

        debug!(token_id = %token_id, "Querying fee rate");

        let response = self.client.get(&url).send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: FeeRateResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(format!("Failed to parse fee_rate response: {e}"), e)
        })?;

        debug!(token_id = %token_id, fee_rate_bps = %result.base_fee, "Got fee rate");

        Ok(result.base_fee)
    }

    /// Check if an orderbook exists for a token ID
    ///
    /// **Deprecated**: Use [`Self::get_orderbook_summary`] instead, which returns all market
    /// parameters in a single API call. Check for `Some(...)` vs `None` to determine
    /// if the orderbook exists.
    ///
    /// Queries the Polymarket CLOB `/book` endpoint to verify that an
    /// active orderbook exists for the given token. This should be called
    /// before submitting orders to avoid "orderbook does not exist" errors.
    ///
    /// # Arguments
    /// * `token_id` - The token ID (CLOB token / asset ID) to check
    ///
    /// # Returns
    /// * `true` if the orderbook exists and is active
    /// * `false` if the orderbook does not exist or the market is closed
    ///
    /// # Note
    /// Markets can have valid neg_risk and fee_rate data but no active
    /// orderbook (e.g., resolved or closed markets). Always verify
    /// orderbook existence before submitting orders.
    #[deprecated(
        since = "0.2.0",
        note = "Use get_orderbook_summary() instead. Check for Some(...) vs None to determine if orderbook exists"
    )]
    #[instrument(skip(self))]
    pub async fn check_orderbook_exists(&self, token_id: &str) -> Result<bool> {
        self.wait_for_rate_limit().await;

        let endpoint = "/book";
        let url = format!("{}{}?token_id={}", self.config.base_url, endpoint, token_id);

        debug!(token_id = %token_id, "Checking orderbook existence");

        let response = self.client.get(&url).send().await?;
        let status = response.status();

        // Check response body for error
        let body = response.text().await.unwrap_or_default();

        // API returns 200 with {"error": "..."} for non-existent orderbooks
        if body.contains("does not exist") || body.contains("No orderbook") {
            info!(token_id = %token_id, "Orderbook does not exist");
            return Ok(false);
        }

        if !status.is_success() {
            // Other API errors
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        // If we got here, the orderbook exists
        debug!(token_id = %token_id, "Orderbook exists");
        Ok(true)
    }

    /// Get balance and allowance for specific tokens
    ///
    /// Retrieves the cached balance and allowance for your account.
    /// Use [`Self::update_balance_allowance`] to refresh the cached values first
    /// if you suspect they are stale.
    ///
    /// Reference: <https://docs.polymarket.com/trading/clients/l2#getbalanceallowance>
    ///
    /// # Arguments
    /// * `params` - Asset type and optional token ID to query
    ///
    /// # Example
    /// ```rust,ignore
    /// use polymarket_sdk::types::{BalanceAllowanceParams, AssetType};
    ///
    /// // Query USDC collateral balance
    /// let result = client.get_balance_allowance(
    ///     &BalanceAllowanceParams::collateral()
    /// ).await?;
    /// println!("Balance: {}, Allowance: {}", result.balance, result.allowance);
    ///
    /// // Query conditional token balance
    /// let result = client.get_balance_allowance(
    ///     &BalanceAllowanceParams::conditional("52114319...")
    /// ).await?;
    /// ```
    #[instrument(skip(self))]
    pub async fn get_balance_allowance(
        &self,
        params: &BalanceAllowanceParams,
    ) -> Result<BalanceAllowanceResponse> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for querying balance allowance")
        })?;

        let endpoint = "/balance-allowance";
        let query_string = params.to_query_string();
        let url = format!("{}{}?{}", self.config.base_url, endpoint, query_string);

        let address = self.get_auth_address();
        let headers =
            create_l2_headers_with_address::<String>(&address, api_creds, "GET", endpoint, None)?;

        debug!(asset_type = %params.asset_type, "Getting balance allowance");

        let mut req_builder = self.client.get(&url);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        let result: BalanceAllowanceResponse = response.json().await.map_err(|e| {
            PolymarketError::parse_with_source(
                format!("Failed to parse balance allowance response: {e}"),
                e,
            )
        })?;

        debug!(
            balance = %result.balance,
            allowance = %result.allowance,
            "Got balance allowance"
        );

        Ok(result)
    }

    /// Update (refresh) the cached balance and allowance for specific tokens
    ///
    /// Forces the CLOB API to re-read on-chain balance and allowance values.
    /// Call this after on-chain operations (deposits, approvals) to ensure
    /// the API has up-to-date values before placing orders.
    ///
    /// Reference: <https://docs.polymarket.com/trading/clients/l2#updatebalanceallowance>
    ///
    /// # Arguments
    /// * `params` - Asset type and optional token ID to update
    ///
    /// # Example
    /// ```rust,ignore
    /// use polymarket_sdk::types::{BalanceAllowanceParams, AssetType};
    ///
    /// // Refresh USDC collateral balance after a deposit
    /// client.update_balance_allowance(
    ///     &BalanceAllowanceParams::collateral().with_signature_type(2)
    /// ).await?;
    ///
    /// // Now get the updated balance
    /// let result = client.get_balance_allowance(
    ///     &BalanceAllowanceParams::collateral()
    /// ).await?;
    /// ```
    #[instrument(skip(self))]
    pub async fn update_balance_allowance(
        &self,
        params: &BalanceAllowanceParams,
    ) -> Result<()> {
        self.wait_for_rate_limit().await;

        let api_creds = self.api_credentials.as_ref().ok_or_else(|| {
            PolymarketError::config("API credentials required for updating balance allowance")
        })?;

        let endpoint = "/balance-allowance/update";
        let query_string = params.to_query_string();
        let url = format!("{}{}?{}", self.config.base_url, endpoint, query_string);

        let address = self.get_auth_address();
        let headers =
            create_l2_headers_with_address::<String>(&address, api_creds, "GET", endpoint, None)?;

        debug!(asset_type = %params.asset_type, "Updating balance allowance");

        let mut req_builder = self.client.get(&url);
        for (key, value) in &headers {
            req_builder = req_builder.header(*key, value);
        }

        let response = req_builder.send().await?;
        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PolymarketError::api(status.as_u16(), body));
        }

        info!(asset_type = %params.asset_type, "Balance allowance updated");

        Ok(())
    }
}

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

    #[test]
    fn test_clob_config_default() {
        let config = ClobConfig::default();
        // URL uses helper function which may be overridden by env var
        assert_eq!(config.base_url, clob_api_url());
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert_eq!(config.rate_limit_per_second, 5);
    }

    #[test]
    fn test_clob_config_with_base_url() {
        let config = ClobConfig::default().with_base_url("https://custom.example.com");
        assert_eq!(config.base_url, "https://custom.example.com");
    }
}