polynode 0.12.3

Rust SDK for the PolyNode API — real-time Polymarket data
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
//! Trading module — place orders on Polymarket with local credential custody
//! and builder attribution via the polynode co-signer.
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use polynode::trading::{PolyNodeTrader, TraderConfig, PrivateKeySigner, OrderParams, OrderSide};
//!
//! #[tokio::main]
//! async fn main() -> polynode::Result<()> {
//!     let mut trader = PolyNodeTrader::new(TraderConfig {
//!         polynode_key: "pn_live_...".into(),
//!         ..Default::default()
//!     })?;
//!
//!     let signer = PrivateKeySigner::from_hex("0xdeadbeef...")?;
//!     let status = trader.ensure_ready(Box::new(signer), None).await?;
//!     println!("Ready: {:?}", status.funder_address);
//!
//!     let result = trader.order(OrderParams {
//!         token_id: "123...".into(),
//!         side: OrderSide::Buy,
//!         price: 0.55,
//!         size: 100.0,
//!         ..Default::default()
//!     }).await?;
//!
//!     println!("Order: {:?}", result);
//!     trader.close();
//!     Ok(())
//! }
//! ```

pub mod constants;
pub mod constants_v2;
pub mod types;
pub mod signer;
pub mod onboarding;
pub mod cosigner;
pub mod sqlite_backend;
pub mod position_management;
pub mod escrow;
pub mod relayer;

#[cfg(feature = "privy")]
pub mod privy;

use crate::error::{Error, Result};
use self::constants::{CLOB_HOST, CHAIN_ID, CTF_EXCHANGE, NEG_RISK_CTF_EXCHANGE};
use self::constants_v2::{V2_CLOB_HOST, V2_CTF_EXCHANGE, V2_NEG_RISK_EXCHANGE_A, V2_DOMAIN_VERSION, V2_DOMAIN_NAME};
use self::cosigner::{send_via_cosigner, CosignerConfig};
use self::onboarding::create_clob_credentials;
use self::sqlite_backend::OrderHistoryInsert;

// Re-exports for public API
pub use self::types::*;
pub use self::signer::{TradingSigner, PrivateKeySigner};
pub use self::onboarding::{
    derive_safe_address, derive_proxy_address, derive_funder_address,
    detect_wallet_type, is_safe_deployed,
};
pub use self::cosigner::build_l2_headers;
pub use self::sqlite_backend::TradingSqliteBackend;

/// Re-export `Address` so custom signer implementors don't need `alloy-primitives` as a direct dep.
pub use alloy_primitives::Address;

/// Re-export `async_trait` so custom signer implementors don't need it as a direct dep.
pub use async_trait::async_trait;

#[cfg(feature = "privy")]
pub use self::privy::{PrivyConfig, PrivySigner};

/// Main trading client with local credential custody.
pub struct PolyNodeTrader {
    config: TraderConfig,
    db: Option<TradingSqliteBackend>,
    active_signer: Option<Box<dyn TradingSigner>>,
    active_wallet: Option<String>,
    http: reqwest::Client,
}

impl PolyNodeTrader {
    /// Create a new trader instance.
    pub fn new(config: TraderConfig) -> Result<Self> {
        Ok(Self {
            config,
            db: None,
            active_signer: None,
            active_wallet: None,
            http: reqwest::Client::new(),
        })
    }

    /// Generate a fresh EOA wallet. Returns (private_key_hex, address_hex).
    pub fn generate_wallet() -> (String, String) {
        let (signer, key) = PrivateKeySigner::generate();
        let addr = format!("{}", signer.inner().address());
        (key, addr)
    }

    fn get_db_mut(&mut self) -> Result<&TradingSqliteBackend> {
        if self.db.is_none() {
            self.db = Some(TradingSqliteBackend::open(&self.config.db_path)?);
        }
        Ok(self.db.as_ref().unwrap())
    }

    fn cosigner_config(&self) -> CosignerConfig {
        CosignerConfig {
            cosigner_url: self.config.cosigner_url.clone(),
            polynode_key: self.config.polynode_key.clone(),
            fallback_direct: self.config.fallback_direct,
            builder_credentials: self.config.builder_credentials.clone(),
        }
    }

    // ── Onboarding ──

    /// One-call onboarding: derive addresses, deploy Safe if needed,
    /// set approvals if needed, create/derive CLOB credentials.
    pub async fn ensure_ready(
        &mut self,
        signer: Box<dyn TradingSigner>,
        opts: Option<EnsureReadyOpts>,
    ) -> Result<ReadyStatus> {
        let eoa = signer.address();
        let mut actions = Vec::new();

        // Detect or use explicit signature type
        let (sig_type, funder_address) = if let Some(ref o) = opts {
            if let Some(t) = o.signature_type {
                (t, derive_funder_address(eoa, t))
            } else {
                let (t, f) = detect_wallet_type(eoa).await?;
                actions.push(format!("auto_detected_type_{}", t.as_u8()));
                (t, f)
            }
        } else {
            let (t, f) = detect_wallet_type(eoa).await?;
            actions.push(format!("auto_detected_type_{}", t.as_u8()));
            (t, f)
        };

        // Check existing credentials
        let db = self.get_db_mut()?;
        let existing = db.get_credentials(&format!("{}", eoa))?;
        let mut safe_deployed = existing.as_ref().map(|c| c.safe_deployed).unwrap_or(false);
        let mut approvals_set = existing.as_ref().map(|c| c.approvals_set).unwrap_or(false);

        // For Safe wallets: check deployment
        if sig_type == SignatureType::PolyGnosisSafe && !safe_deployed {
            let deployed = is_safe_deployed(funder_address).await.unwrap_or(false);
            if deployed {
                safe_deployed = true;
                actions.push("safe_already_deployed".into());
            } else {
                actions.push("safe_needs_deployment".into());
                // Note: Safe deployment requires the cosigner/relayer integration.
                // For now, mark as needing deployment — users can deploy via the TS SDK
                // or a separate deployment step.
            }
        }

        // Check approvals
        if !approvals_set {
            match onboarding::check_approvals(funder_address, &self.config.rpc_url, self.config.exchange_version).await {
                Ok(status) => {
                    if status.all_approved {
                        approvals_set = true;
                        actions.push("approvals_already_set".into());
                    } else {
                        actions.push("approvals_missing".into());
                    }
                }
                Err(_) => {
                    actions.push("approval_check_failed".into());
                }
            }
        }

        // Create/derive CLOB credentials
        let creds = if let Some(ref existing) = existing {
            actions.push("credentials_loaded".into());
            ClobCredentials {
                api_key: existing.api_key.clone(),
                api_secret: existing.api_secret.clone(),
                api_passphrase: existing.api_passphrase.clone(),
            }
        } else {
            let creds = create_clob_credentials(&*signer, funder_address, sig_type).await?;
            actions.push("credentials_created".into());
            creds
        };

        // Store credentials
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();

        let db = self.get_db_mut()?;
        db.upsert_credentials(&StoredCredentials {
            wallet_address: format!("{}", eoa),
            funder_address: Some(format!("{}", funder_address)),
            api_key: creds.api_key.clone(),
            api_secret: creds.api_secret.clone(),
            api_passphrase: creds.api_passphrase.clone(),
            signature_type: sig_type,
            safe_deployed,
            approvals_set,
            created_at: existing.as_ref().map(|c| c.created_at).unwrap_or(now),
            updated_at: now,
        })?;

        self.active_wallet = Some(format!("{}", eoa));
        self.active_signer = Some(signer);

        Ok(ReadyStatus {
            wallet: format!("{}", eoa),
            funder_address: format!("{}", funder_address),
            signature_type: sig_type,
            safe_deployed,
            approvals_set,
            credentials_stored: true,
            credentials: creds,
            actions,
        })
    }

    /// Link a wallet manually (derive credentials, store locally).
    pub async fn link_wallet(
        &mut self,
        signer: Box<dyn TradingSigner>,
        opts: Option<LinkOpts>,
    ) -> Result<LinkResult> {
        let eoa = signer.address();
        let sig_type = opts
            .as_ref()
            .and_then(|o| o.signature_type)
            .unwrap_or(self.config.default_signature_type);
        let funder_address = derive_funder_address(eoa, sig_type);

        let db = self.get_db_mut()?;
        let existing = db.get_credentials(&format!("{}", eoa))?;

        let creds = if let Some(ref ex) = existing {
            ClobCredentials {
                api_key: ex.api_key.clone(),
                api_secret: ex.api_secret.clone(),
                api_passphrase: ex.api_passphrase.clone(),
            }
        } else {
            create_clob_credentials(&*signer, funder_address, sig_type).await?
        };

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();

        let db = self.get_db_mut()?;
        db.upsert_credentials(&StoredCredentials {
            wallet_address: format!("{}", eoa),
            funder_address: Some(format!("{}", funder_address)),
            api_key: creds.api_key.clone(),
            api_secret: creds.api_secret.clone(),
            api_passphrase: creds.api_passphrase.clone(),
            signature_type: sig_type,
            safe_deployed: existing.as_ref().map(|c| c.safe_deployed).unwrap_or(false),
            approvals_set: existing.as_ref().map(|c| c.approvals_set).unwrap_or(false),
            created_at: existing.as_ref().map(|c| c.created_at).unwrap_or(now),
            updated_at: now,
        })?;

        self.active_wallet = Some(format!("{}", eoa));
        self.active_signer = Some(signer);

        Ok(LinkResult {
            wallet: format!("{}", eoa),
            funder_address: format!("{}", funder_address),
            signature_type: sig_type,
            credentials: creds,
        })
    }

    /// Import existing CLOB credentials directly (no signing needed).
    pub fn link_credentials(&mut self, opts: LinkCredentialsOpts) -> Result<()> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();

        let db = self.get_db_mut()?;
        db.upsert_credentials(&StoredCredentials {
            wallet_address: opts.wallet.clone(),
            funder_address: opts.funder_address,
            api_key: opts.api_key,
            api_secret: opts.api_secret,
            api_passphrase: opts.api_passphrase,
            signature_type: opts.signature_type.unwrap_or(SignatureType::Eoa),
            safe_deployed: true,
            approvals_set: true,
            created_at: now,
            updated_at: now,
        })?;
        self.active_wallet = Some(opts.wallet);
        Ok(())
    }

    /// Get all linked wallets.
    pub fn get_linked_wallets(&mut self) -> Result<Vec<WalletInfo>> {
        let db = self.get_db_mut()?;
        let creds = db.get_all_credentials()?;
        Ok(creds
            .into_iter()
            .map(|c| WalletInfo {
                wallet: c.wallet_address.clone(),
                funder_address: c.funder_address.unwrap_or(c.wallet_address),
                signature_type: c.signature_type,
                credentials: ClobCredentials {
                    api_key: c.api_key,
                    api_secret: c.api_secret,
                    api_passphrase: c.api_passphrase,
                },
                created_at: c.created_at,
            })
            .collect())
    }

    // ── Export / Backup ──

    /// Export a wallet's full state for backup.
    pub fn export_wallet(&mut self, wallet: Option<&str>) -> Result<Option<WalletExport>> {
        let addr = wallet
            .map(String::from)
            .or_else(|| self.active_wallet.clone())
            .ok_or_else(|| Error::Trading("No wallet specified".into()))?;
        let db = self.get_db_mut()?;
        let creds = db.get_credentials(&addr)?;
        Ok(creds.map(|c| WalletExport {
            wallet: c.wallet_address.clone(),
            funder_address: c.funder_address.unwrap_or(c.wallet_address),
            signature_type: c.signature_type,
            credentials: ClobCredentials {
                api_key: c.api_key,
                api_secret: c.api_secret,
                api_passphrase: c.api_passphrase,
            },
            safe_deployed: c.safe_deployed,
            approvals_set: c.approvals_set,
            created_at: c.created_at,
        }))
    }

    /// Import a previously exported wallet.
    pub fn import_wallet(&mut self, exported: WalletExport) -> Result<()> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();
        let db = self.get_db_mut()?;
        db.upsert_credentials(&StoredCredentials {
            wallet_address: exported.wallet,
            funder_address: Some(exported.funder_address),
            api_key: exported.credentials.api_key,
            api_secret: exported.credentials.api_secret,
            api_passphrase: exported.credentials.api_passphrase,
            signature_type: exported.signature_type,
            safe_deployed: exported.safe_deployed,
            approvals_set: exported.approvals_set,
            created_at: exported.created_at,
            updated_at: now,
        })?;
        Ok(())
    }

    // ── Pre-Trade Checks ──

    /// Check on-chain token approvals.
    pub async fn check_approvals(&mut self, wallet: Option<&str>) -> Result<ApprovalStatus> {
        let creds = self.get_stored_creds(wallet)?;
        let funder = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address);
        let addr: Address = funder
            .parse()
            .map_err(|_| Error::Trading(format!("Invalid address: {}", funder)))?;
        onboarding::check_approvals(addr, &self.config.rpc_url, self.config.exchange_version).await
    }

    /// Check collateral (USDC.e for V1, pUSD for V2) and MATIC balances.
    pub async fn check_balance(&mut self, wallet: Option<&str>) -> Result<BalanceInfo> {
        let creds = self.get_stored_creds(wallet)?;
        let funder = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address);
        let addr: Address = funder
            .parse()
            .map_err(|_| Error::Trading(format!("Invalid address: {}", funder)))?;
        onboarding::check_balance(addr, &self.config.rpc_url, self.config.exchange_version).await
    }

    /// Ask the V2 CLOB to refresh its cached balance/allowance view.
    /// Call this after setting/changing on-chain approvals — the V2 CLOB
    /// rejects orders with "not enough balance / allowance" until it has
    /// seen the new state. No-op for V1.
    ///
    /// `asset_type` is "COLLATERAL" (pUSD) or "CONDITIONAL" (CTF tokens).
    pub async fn refresh_balance_allowance(
        &mut self,
        asset_type: &str,
        wallet: Option<&str>,
    ) -> Result<(bool, u16)> {
        if self.config.exchange_version != ExchangeVersion::V2 {
            return Ok((true, 0));
        }
        let creds = self.get_stored_creds(wallet)?;
        let sig_type = creds.signature_type.as_u8();
        let path = "/balance-allowance/update";
        let headers = build_l2_headers(
            &creds.api_key,
            &creds.api_secret,
            &creds.api_passphrase,
            &creds.wallet_address,
            "GET",
            path,          // HMAC over base path only (NO query string)
            None,
        );
        let url = format!(
            "{}{}?asset_type={}&signature_type={}",
            V2_CLOB_HOST, path, asset_type, sig_type
        );
        let mut req = self.http.get(&url);
        for (k, v) in &headers {
            req = req.header(k, v);
        }
        let resp = req.send().await
            .map_err(|e| Error::Trading(format!("refresh_balance_allowance failed: {}", e)))?;
        Ok((resp.status().is_success(), resp.status().as_u16()))
    }

    /// Read the V2 CLOB's current cached view of balance + allowance.
    /// Returns (balance_raw_string, allowances_by_spender) or None for V1.
    pub async fn get_balance_allowance(
        &mut self,
        asset_type: &str,
        wallet: Option<&str>,
    ) -> Result<Option<serde_json::Value>> {
        if self.config.exchange_version != ExchangeVersion::V2 {
            return Ok(None);
        }
        let creds = self.get_stored_creds(wallet)?;
        let sig_type = creds.signature_type.as_u8();
        let path = "/balance-allowance";
        let headers = build_l2_headers(
            &creds.api_key,
            &creds.api_secret,
            &creds.api_passphrase,
            &creds.wallet_address,
            "GET",
            path,
            None,
        );
        let url = format!(
            "{}{}?asset_type={}&signature_type={}",
            V2_CLOB_HOST, path, asset_type, sig_type
        );
        let mut req = self.http.get(&url);
        for (k, v) in &headers {
            req = req.header(k, v);
        }
        let resp = req.send().await
            .map_err(|e| Error::Trading(format!("get_balance_allowance failed: {}", e)))?;
        if !resp.status().is_success() {
            return Ok(None);
        }
        let json: serde_json::Value = resp.json().await
            .map_err(|e| Error::Trading(format!("get_balance_allowance parse: {}", e)))?;
        Ok(Some(json))
    }

    // ── V2 Collateral (wrap/unwrap/balance) ──

    /// Wrap USDC.e into PolyUSD via the Collateral Onramp.
    /// Routes through the Polymarket relayer (gasless) for Safe/Proxy wallets,
    /// and sends directly for EOA wallets.
    /// Amount is in raw units (6 decimals, e.g. 1_000_000 = 1 USDC).
    pub async fn wrap_to_polyusd(&mut self, amount: u64) -> Result<String> {
        let creds = self.get_stored_creds(None)?;
        let signer = self.active_signer.as_ref()
            .ok_or_else(|| Error::Trading("No active signer. Call ensure_ready() first.".into()))?;
        let _eoa = signer.address();
        let funder: Address = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address).parse()
            .map_err(|_| Error::Trading("bad funder address".into()))?;

        let usdc_addr: Address = constants::USDC.parse().unwrap();
        let onramp_addr: Address = constants_v2::COLLATERAL_ONRAMP.parse().unwrap();
        let amount_u256 = alloy_primitives::U256::from(amount);
        let max_u256 = alloy_primitives::U256::MAX;

        let approve_data = onboarding::encode_approve(onramp_addr, max_u256);
        let wrap_data = onboarding::encode_wrap(usdc_addr, funder, amount_u256);

        // Safe / Proxy wallets → relayer path
        if matches!(creds.signature_type, SignatureType::PolyGnosisSafe | SignatureType::PolyProxy) {
            let bc = self.config.builder_credentials.clone().ok_or_else(|| {
                Error::Trading(
                    "wrap_to_polyusd on a Safe/Proxy wallet requires builder_credentials in \
                     TraderConfig. Pass your Polymarket builder key/secret/passphrase.".into()
                )
            })?;
            let rc = relayer::RelayClient::new(bc);
            let txns = vec![
                relayer::SafeSubTx { to: usdc_addr, value: alloy_primitives::U256::ZERO, data: approve_data, operation: 0 },
                relayer::SafeSubTx { to: onramp_addr, value: alloy_primitives::U256::ZERO, data: wrap_data, operation: 0 },
            ];
            return rc.execute_safe(signer.as_ref(), txns).await;
        }

        // EOA path: direct send
        let rpc_url = &self.config.rpc_url;
        let client = &self.http;
        let tx1 = self.send_raw_tx(signer.as_ref(), client, rpc_url, usdc_addr, alloy_primitives::U256::ZERO, &approve_data).await?;
        tracing::info!("USDC.e approve tx: {}", tx1);
        self.send_raw_tx(signer.as_ref(), client, rpc_url, onramp_addr, alloy_primitives::U256::ZERO, &wrap_data).await
    }

    /// Unwrap PolyUSD back to USDC.e via the Collateral Offramp.
    /// Routes through the Polymarket relayer (gasless) for Safe/Proxy wallets,
    /// and sends directly for EOA wallets.
    /// Amount is in raw units (6 decimals, e.g. 1_000_000 = 1 USDC).
    pub async fn unwrap_from_polyusd(&mut self, amount: u64) -> Result<String> {
        let creds = self.get_stored_creds(None)?;
        let signer = self.active_signer.as_ref()
            .ok_or_else(|| Error::Trading("No active signer. Call ensure_ready() first.".into()))?;
        let _eoa = signer.address();
        let funder: Address = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address).parse()
            .map_err(|_| Error::Trading("bad funder address".into()))?;

        let usdc_addr: Address = constants::USDC.parse().unwrap();
        let polyusd_addr: Address = constants_v2::POLY_USD.parse().unwrap();
        let offramp_addr: Address = constants_v2::COLLATERAL_OFFRAMP.parse().unwrap();
        let amount_u256 = alloy_primitives::U256::from(amount);
        let max_u256 = alloy_primitives::U256::MAX;

        let approve_data = onboarding::encode_approve(offramp_addr, max_u256);
        let unwrap_data = onboarding::encode_unwrap(usdc_addr, funder, amount_u256);

        // Safe / Proxy wallets → relayer path
        if matches!(creds.signature_type, SignatureType::PolyGnosisSafe | SignatureType::PolyProxy) {
            let bc = self.config.builder_credentials.clone().ok_or_else(|| {
                Error::Trading(
                    "unwrap_from_polyusd on a Safe/Proxy wallet requires builder_credentials in \
                     TraderConfig. Pass your Polymarket builder key/secret/passphrase.".into()
                )
            })?;
            // Check allowance first — skip redundant approve
            let client = reqwest::Client::new();
            let allowance = onboarding::eth_call_u256(
                &client, &self.config.rpc_url, polyusd_addr,
                onboarding::encode_allowance(funder, offramp_addr),
            ).await.unwrap_or(alloy_primitives::U256::ZERO);
            let rc = relayer::RelayClient::new(bc);
            let mut txns = Vec::new();
            if allowance < amount_u256 {
                txns.push(relayer::SafeSubTx { to: polyusd_addr, value: alloy_primitives::U256::ZERO, data: approve_data, operation: 0 });
            }
            txns.push(relayer::SafeSubTx { to: offramp_addr, value: alloy_primitives::U256::ZERO, data: unwrap_data, operation: 0 });
            return rc.execute_safe(signer.as_ref(), txns).await;
        }

        // EOA path: direct send
        let rpc_url = &self.config.rpc_url;
        let client = &self.http;
        let tx1 = self.send_raw_tx(signer.as_ref(), client, rpc_url, polyusd_addr, alloy_primitives::U256::ZERO, &approve_data).await?;
        tracing::info!("PolyUSD approve tx: {}", tx1);
        self.send_raw_tx(signer.as_ref(), client, rpc_url, offramp_addr, alloy_primitives::U256::ZERO, &unwrap_data).await
    }

    /// Get PolyUSD balance for the funder address (Safe/Proxy/EOA as configured).
    /// Returns raw units (6 decimals).
    pub async fn get_polyusd_balance(&mut self) -> Result<u64> {
        let creds = self.get_stored_creds(None)?;
        let funder: Address = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address).parse()
            .map_err(|_| Error::Trading("bad funder address".into()))?;
        let polyusd_addr: Address = constants_v2::POLY_USD.parse().unwrap();
        let data = onboarding::encode_balance_of(funder);
        let val = onboarding::eth_call_u256(&self.http, &self.config.rpc_url, polyusd_addr, data).await?;
        Ok(u64::try_from(val).unwrap_or(u64::MAX))
    }

    /// Get USDC.e balance for the funder address (Safe/Proxy/EOA as configured).
    /// Returns raw units (6 decimals).
    pub async fn get_usdce_balance(&mut self) -> Result<u64> {
        let creds = self.get_stored_creds(None)?;
        let funder: Address = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address).parse()
            .map_err(|_| Error::Trading("bad funder address".into()))?;
        let usdc_addr: Address = constants::USDC.parse().unwrap();
        let data = onboarding::encode_balance_of(funder);
        let val = onboarding::eth_call_u256(&self.http, &self.config.rpc_url, usdc_addr, data).await?;
        Ok(u64::try_from(val).unwrap_or(u64::MAX))
    }

    /// Build, sign, and send a legacy transaction on-chain.
    async fn send_raw_tx(
        &self,
        signer: &dyn TradingSigner,
        client: &reqwest::Client,
        rpc_url: &str,
        to: Address,
        value: alloy_primitives::U256,
        data: &[u8],
    ) -> Result<String> {
        let from = signer.address();

        // Fetch nonce and gas price
        let nonce = onboarding::eth_get_transaction_count(client, rpc_url, from).await?;
        let gas_price = onboarding::eth_gas_price(client, rpc_url).await?;
        // Add 20% to gas price for faster inclusion
        let gas_price = gas_price + gas_price / 5;

        // Use a generous gas limit for approve/wrap/unwrap calls
        let gas_limit: u64 = 150_000;

        // Build the unsigned transaction hash (EIP-155)
        let tx_hash = onboarding::build_legacy_tx_hash(nonce, gas_price, gas_limit, to, value, data);

        // Sign the hash
        let signature = signer.sign_hash(&tx_hash).await?;

        // Build the signed raw transaction
        let raw_tx = onboarding::build_legacy_tx_raw(nonce, gas_price, gas_limit, to, value, data, &signature);

        // Send it
        onboarding::eth_send_raw_transaction(client, rpc_url, &raw_tx).await
    }

    // ── Trading ──

    /// Get the CLOB host URL based on the configured exchange version.
    fn get_clob_host(&self) -> &str {
        match self.config.exchange_version {
            ExchangeVersion::V1 => CLOB_HOST,
            ExchangeVersion::V2 => V2_CLOB_HOST,
        }
    }

    /// Place an order on Polymarket.
    pub async fn order(&mut self, params: OrderParams) -> Result<OrderResult> {
        let creds = self.get_stored_creds(None)?;

        // Get signer address before mutable borrow
        let signer_addr = self.active_signer.as_ref()
            .ok_or_else(|| Error::Trading("No active signer. Call ensure_ready() first.".into()))?
            .address();

        // Fetch market metadata
        let meta = self.fetch_meta(&params.token_id).await?;

        // Build the order EIP-712 payload — dispatch by exchange version
        let exchange_version = self.config.exchange_version;
        let order_payload = match exchange_version {
            ExchangeVersion::V1 => build_order_payload(signer_addr, &creds, &params, &meta)?,
            ExchangeVersion::V2 => build_v2_order_payload(signer_addr, &creds, &params, &meta)?,
        };

        let signer = self.active_signer.as_ref()
            .ok_or_else(|| Error::Trading("No active signer".into()))?;
        let signature = signer.sign_typed_data(&order_payload).await?;
        let sig_hex = format!("0x{}", hex::encode(&signature));

        // Build the order JSON body — dispatch by exchange version
        let body = match exchange_version {
            ExchangeVersion::V1 => build_order_body(&params, &order_payload, &sig_hex, &creds.api_key, &creds, &meta)?,
            ExchangeVersion::V2 => build_v2_order_body(&params, &order_payload, &sig_hex, &creds.api_key, &creds)?,
        };
        let body_str = serde_json::to_string(&body)
            .map_err(|e| Error::Trading(format!("Failed to serialize order: {}", e)))?;

        // Build L2 headers
        let headers = build_l2_headers(
            &creds.api_key,
            &creds.api_secret,
            &creds.api_passphrase,
            &creds.wallet_address,
            "POST",
            "/order",
            Some(&body_str),
        );

        // Log locally
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();

        let db = self.get_db_mut()?;
        let local_id = db.insert_order(&creds.wallet_address, &OrderHistoryInsert {
            order_id: None,
            token_id: params.token_id.clone(),
            side: params.side.to_string(),
            price: params.price,
            size: params.size,
            order_type: params.order_type.to_string(),
            status: "submitting".into(),
            error_msg: None,
            response_json: None,
            created_at: now,
            fee_amount_raw: None,
            escrow_order_id: None,
            fee_escrow_tx_hash: None,
        })?;

        // Build fee auth if escrow is enabled
        let fee_config = params.fee_config.as_ref().or(self.config.fee_config.as_ref());
        let mut fee_auth_req: Option<FeeAuthRequest> = None;
        let mut fee_amount_raw: u64 = 0;

        if let Some(fc) = fee_config {
            if fc.fee_bps > 0 {
                let aff = fc.affiliate.as_deref().unwrap_or("");
                if aff.is_empty() || aff == "0x0000000000000000000000000000000000000000" {
                    return Err(Error::Trading("fee_config.affiliate is required when fee_bps > 0 — set it to the wallet address where you want fees sent".into()));
                }
                fee_amount_raw = escrow::calculate_fee(params.price, params.size, fc.fee_bps);
                if fee_amount_raw > 0 {
                    let funder = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address);
                    let escrow_addr = escrow::fee_escrow_address_for(self.config.exchange_version);
                    let nonce = escrow::fetch_escrow_nonce(
                        &self.config.rpc_url,
                        &format!("{}", signer_addr),
                        escrow_addr,
                    ).await?;
                    let deadline = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap()
                        .as_secs() + 300;
                    let escrow_oid = escrow::generate_escrow_order_id();

                    let signer_ref = self.active_signer.as_ref()
                        .ok_or_else(|| Error::Trading("No active signer".into()))?;

                    fee_auth_req = Some(escrow::sign_fee_auth(
                        signer_ref.as_ref(),
                        &escrow_oid,
                        funder,
                        fee_amount_raw,
                        deadline,
                        nonce,
                        fc.affiliate.as_deref(),
                        fc.affiliate_share_bps,
                        self.config.exchange_version,
                    ).await?);
                }
            }
        }

        // Submit via co-signer
        let result = send_via_cosigner(
            &self.cosigner_config(),
            &CosignerRequest {
                method: "POST".into(),
                path: "/order".into(),
                body: Some(body_str),
                headers,
                builder_credentials: self.config.builder_credentials.clone(),
                fee_auth: fee_auth_req.clone(),
                clob_host: Some(self.get_clob_host().to_string()),
            },
        ).await?;

        // Update local record
        let order_id = result.get("orderID")
            .or_else(|| result.get("orderId"))
            .and_then(|v| v.as_str())
            .map(String::from);
        let success = order_id.is_some() || result.get("success").and_then(|v| v.as_bool()).unwrap_or(false);
        let error = result.get("error")
            .or_else(|| result.get("errorMsg"))
            .and_then(|v| v.as_str())
            .map(String::from);

        let db = self.get_db_mut()?;
        let fee_tx = result.get("feeEscrowTxHash").and_then(|v| v.as_str());
        db.update_order_status(
            local_id,
            if success { "submitted" } else { "failed" },
            order_id.as_deref(),
            error.as_deref(),
            Some(&result.to_string()),
            fee_auth_req.as_ref().map(|fa| fa.fee_amount.as_str()),
            fee_auth_req.as_ref().map(|fa| fa.escrow_order_id.as_str()),
            fee_tx,
        )?;

        Ok(OrderResult {
            success,
            order_id,
            status: result.get("status").and_then(|v| v.as_str()).map(String::from),
            error,
            making_amount: result.get("makingAmount").and_then(|v| v.as_str()).map(String::from),
            taking_amount: result.get("takingAmount").and_then(|v| v.as_str()).map(String::from),
            fee_escrow_tx_hash: result.get("feeEscrowTxHash").and_then(|v| v.as_str()).map(String::from),
            fee_amount: if fee_amount_raw > 0 { Some(format!("{:.6}", fee_amount_raw as f64 / 1e6)) } else { None },
        })
    }

    /// Cancel an order.
    pub async fn cancel_order(&mut self, order_id: &str) -> Result<CancelResult> {
        let creds = self.get_stored_creds(None)?;
        let body_str = serde_json::to_string(&serde_json::json!({ "orderID": order_id }))
            .map_err(|e| Error::Trading(format!("serialize failed: {}", e)))?;
        let headers = build_l2_headers(
            &creds.api_key, &creds.api_secret, &creds.api_passphrase,
            &creds.wallet_address, "DELETE", "/order", Some(&body_str),
        );

        let result = send_via_cosigner(&self.cosigner_config(), &CosignerRequest {
            method: "DELETE".into(),
            path: "/order".into(),
            body: Some(body_str),
            headers,
            builder_credentials: self.config.builder_credentials.clone(),
            fee_auth: None,
            clob_host: Some(self.get_clob_host().to_string()),
        }).await?;

        Ok(CancelResult {
            canceled: result.get("canceled")
                .and_then(|v| v.as_array())
                .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
                .unwrap_or_default(),
            not_canceled: result.get("not_canceled")
                .and_then(|v| serde_json::from_value(v.clone()).ok())
                .unwrap_or_default(),
        })
    }

    /// Cancel all orders, optionally for a specific market.
    pub async fn cancel_all(&mut self, market: Option<&str>) -> Result<CancelResult> {
        let creds = self.get_stored_creds(None)?;
        let path = if market.is_some() { "/cancel-market-orders" } else { "/cancel-all" };
        let body = market.map(|m| serde_json::json!({ "market": m }).to_string());
        let headers = build_l2_headers(
            &creds.api_key, &creds.api_secret, &creds.api_passphrase,
            &creds.wallet_address, "DELETE", path, body.as_deref(),
        );

        let result = send_via_cosigner(&self.cosigner_config(), &CosignerRequest {
            method: "DELETE".into(),
            path: path.into(),
            body,
            headers,
            builder_credentials: self.config.builder_credentials.clone(),
            fee_auth: None,
            clob_host: Some(self.get_clob_host().to_string()),
        }).await?;

        Ok(CancelResult {
            canceled: result.get("canceled")
                .and_then(|v| v.as_array())
                .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
                .unwrap_or_default(),
            not_canceled: result.get("not_canceled")
                .and_then(|v| serde_json::from_value(v.clone()).ok())
                .unwrap_or_default(),
        })
    }

    /// Get open orders from Polymarket CLOB.
    pub async fn get_open_orders(&mut self, market: Option<&str>) -> Result<Vec<OpenOrder>> {
        let creds = self.get_stored_creds(None)?;
        let mut path = "/data/orders".to_string();
        if let Some(m) = market {
            path = format!("{}?market={}", path, m);
        }
        let headers = build_l2_headers(
            &creds.api_key, &creds.api_secret, &creds.api_passphrase,
            &creds.wallet_address, "GET", &path, None,
        );

        let result = send_via_cosigner(&self.cosigner_config(), &CosignerRequest {
            method: "GET".into(),
            path,
            body: None,
            headers,
            builder_credentials: self.config.builder_credentials.clone(),
            fee_auth: None,
            clob_host: Some(self.get_clob_host().to_string()),
        }).await?;

        let orders: Vec<OpenOrder> = if result.is_array() {
            serde_json::from_value(result).unwrap_or_default()
        } else {
            result.get("data")
                .or_else(|| result.get("orders"))
                .and_then(|v| serde_json::from_value(v.clone()).ok())
                .unwrap_or_default()
        };
        Ok(orders)
    }

    // ── History ──

    /// Get local order history.
    pub fn get_order_history(&mut self, params: Option<HistoryParams>) -> Result<Vec<OrderHistoryRow>> {
        let wallet = self.active_wallet.as_ref()
            .ok_or_else(|| Error::Trading("No active wallet".into()))?
            .clone();
        let db = self.get_db_mut()?;
        db.get_order_history(&wallet, &params.unwrap_or_default())
    }

    // ── Position Management (split/merge/convert) ──

    /// Build a split transaction: USDC → YES + NO outcome tokens.
    /// Returns a [`TransactionRequest`] to submit via the Polymarket relayer or on-chain.
    ///
    /// For gasless execution via the relayer, use the TypeScript SDK's `trader.split()`.
    pub fn split(&self, params: types::SplitParams) -> Result<types::TransactionRequest> {
        // TODO: auto-detect neg_risk from metadata lookup
        // For now, default to neg-risk (most multi-outcome markets)
        Ok(position_management::build_split_txn(&params.condition_id, params.amount, true))
    }

    /// Build a merge transaction: YES + NO outcome tokens → USDC.
    /// Returns a [`TransactionRequest`] to submit via the Polymarket relayer or on-chain.
    pub fn merge(&self, params: types::MergeParams) -> Result<types::TransactionRequest> {
        Ok(position_management::build_merge_txn(&params.condition_id, params.amount, true))
    }

    /// Build a convert transaction: NO positions → USDC + YES on complementary outcomes.
    /// Only works on neg-risk multi-outcome markets.
    /// Returns a [`TransactionRequest`] to submit via the Polymarket relayer or on-chain.
    pub fn convert(&self, params: types::ConvertParams) -> Result<types::TransactionRequest> {
        Ok(position_management::build_convert_txn(
            &params.market_id,
            &params.outcome_indices,
            params.amount,
        ))
    }

    // ── Lifecycle ──

    /// Close the trader and release resources.
    pub fn close(&mut self) {
        if let Some(db) = self.db.take() {
            db.close();
        }
        self.active_signer = None;
        self.active_wallet = None;
    }

    // ── Internal ──

    fn get_stored_creds(&mut self, wallet: Option<&str>) -> Result<StoredCredentials> {
        let addr = wallet
            .map(String::from)
            .or_else(|| self.active_wallet.clone())
            .ok_or_else(|| Error::Trading("No active wallet. Call ensure_ready() first.".into()))?;
        let db = self.get_db_mut()?;
        db.get_credentials(&addr)?
            .ok_or_else(|| Error::Trading(format!("No credentials for {}. Call ensure_ready() first.", addr)))
    }

    async fn fetch_meta(&mut self, token_id: &str) -> Result<MarketMeta> {
        let db = self.get_db_mut()?;
        if let Some(cached) = db.get_market_meta(token_id)? {
            // Check TTL
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs_f64();
            if now - cached.fetched_at < constants::META_TTL_SECONDS {
                return Ok(cached);
            }
        }

        // Fetch tick size and neg_risk from CLOB (use version-appropriate host)
        let clob_host = self.get_clob_host();
        let tick_resp: serde_json::Value = self.http
            .get(format!("{}/tick-size?token_id={}", clob_host, token_id))
            .send().await?
            .json().await?;
        let neg_resp: serde_json::Value = self.http
            .get(format!("{}/neg-risk?token_id={}", clob_host, token_id))
            .send().await?
            .json().await?;

        // Fetch fee rate: get condition_id from book, then market details
        let mut fee_rate_bps: i32 = 0;
        let book_resp: serde_json::Value = self.http
            .get(format!("{}/book?token_id={}", clob_host, token_id))
            .send().await?
            .json().await?;
        if let Some(condition_id) = book_resp.get("market").and_then(|v| v.as_str()) {
            if let Ok(market_resp) = self.http
                .get(format!("{}/markets/{}", clob_host, condition_id))
                .send().await
            {
                if let Ok(market_data) = market_resp.json::<serde_json::Value>().await {
                    fee_rate_bps = market_data
                        .get("maker_base_fee")
                        .and_then(|v| v.as_i64())
                        .unwrap_or(0) as i32;
                }
            }
        }

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();

        let meta = MarketMeta {
            token_id: token_id.into(),
            tick_size: tick_resp.get("minimum_tick_size")
                .and_then(|v| v.as_f64())
                .map(|v| v.to_string())
                .or_else(|| tick_resp.as_str().map(|s| s.to_string()))
                .unwrap_or_else(|| "0.01".to_string()),
            fee_rate_bps,
            neg_risk: neg_resp.get("neg_risk")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            fetched_at: now,
        };

        let db = self.get_db_mut()?;
        db.upsert_market_meta(&meta)?;
        Ok(meta)
    }
}

// ── Options structs ──

#[derive(Debug, Clone, Default)]
pub struct EnsureReadyOpts {
    pub signature_type: Option<SignatureType>,
}

#[derive(Debug, Clone, Default)]
pub struct LinkOpts {
    pub signature_type: Option<SignatureType>,
}

#[derive(Debug, Clone)]
pub struct LinkCredentialsOpts {
    pub wallet: String,
    pub api_key: String,
    pub api_secret: String,
    pub api_passphrase: String,
    pub signature_type: Option<SignatureType>,
    pub funder_address: Option<String>,
}

// ── Order Building ──

fn build_order_payload(
    signer_address: Address,
    creds: &StoredCredentials,
    params: &OrderParams,
    meta: &MarketMeta,
) -> Result<Eip712Payload> {
    // Determine which exchange to use based on neg_risk
    let exchange = if meta.neg_risk { NEG_RISK_CTF_EXCHANGE } else { CTF_EXCHANGE };

    // Convert price and size to raw amounts using tick-size-based rounding
    // (matches TS SDK's ROUNDING_CONFIG + getOrderRawAmounts)
    let tick_size_str = meta.tick_size.as_str();
    let rc = match tick_size_str {
        "0.1"    => RoundingConfig { price: 1, size: 2, amount: 3 },
        "0.001"  => RoundingConfig { price: 3, size: 2, amount: 5 },
        "0.0001" => RoundingConfig { price: 4, size: 2, amount: 6 },
        _        => RoundingConfig { price: 2, size: 2, amount: 4 }, // "0.01" default
    };

    let raw_price = round_normal(params.price, rc.price);
    let side_num: u8;
    let making_amount: u64;
    let taking_amount: u64;

    match params.side {
        OrderSide::Buy => {
            side_num = 0;
            let raw_taker = round_down(params.size, rc.size);
            let mut raw_maker = raw_taker * raw_price;
            if decimal_places(raw_maker) > rc.amount {
                raw_maker = round_up(raw_maker, rc.amount + 4);
                if decimal_places(raw_maker) > rc.amount {
                    raw_maker = round_down(raw_maker, rc.amount);
                }
            }
            // parseUnits(x, 6) — `.round() as u64` avoids the float-truncation bug
            // where e.g. 0.43 * 4 = 1.7199999... cast to u64 yields 1719999, not 1720000.
            making_amount = (raw_maker * 1_000_000.0).round() as u64;
            taking_amount = (raw_taker * 1_000_000.0).round() as u64;
        }
        OrderSide::Sell => {
            side_num = 1;
            let raw_maker = round_down(params.size, rc.size);
            let mut raw_taker = raw_maker * raw_price;
            if decimal_places(raw_taker) > rc.amount {
                raw_taker = round_up(raw_taker, rc.amount + 4);
                if decimal_places(raw_taker) > rc.amount {
                    raw_taker = round_down(raw_taker, rc.amount);
                }
            }
            making_amount = (raw_maker * 1_000_000.0).round() as u64;
            taking_amount = (raw_taker * 1_000_000.0).round() as u64;
        }
    }

    let funder = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address);
    // Polymarket CLOB requires GTD expiration >= now + 1 minute (security threshold).
    // Automatically add the 60-second buffer if the user's expiration is too close.
    let expiration = match params.expiration {
        Some(exp) => {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs();
            if exp > 0 && exp < now + 90 {
                // Too close to now — add the 60-second security threshold
                exp + 60
            } else {
                exp
            }
        }
        None => 0,
    };
    // Salt must fit in u32 range (Python SDK uses randbelow(2**32), TS uses random u32)
    let nonce: u64 = (rand::random::<u32>()) as u64;

    let domain = serde_json::json!({
        "name": "Polymarket CTF Exchange",
        "version": "1",
        "chainId": CHAIN_ID,
        "verifyingContract": exchange,
    });

    let types = serde_json::json!({
        "EIP712Domain": [
            {"name": "name", "type": "string"},
            {"name": "version", "type": "string"},
            {"name": "chainId", "type": "uint256"},
            {"name": "verifyingContract", "type": "address"}
        ],
        "Order": [
            {"name": "salt", "type": "uint256"},
            {"name": "maker", "type": "address"},
            {"name": "signer", "type": "address"},
            {"name": "taker", "type": "address"},
            {"name": "tokenId", "type": "uint256"},
            {"name": "makerAmount", "type": "uint256"},
            {"name": "takerAmount", "type": "uint256"},
            {"name": "expiration", "type": "uint256"},
            {"name": "nonce", "type": "uint256"},
            {"name": "feeRateBps", "type": "uint256"},
            {"name": "side", "type": "uint8"},
            {"name": "signatureType", "type": "uint8"}
        ]
    });

    let message = serde_json::json!({
        "salt": nonce.to_string(),
        "maker": funder,
        "signer": format!("{}", signer_address),
        "taker": "0x0000000000000000000000000000000000000000",
        "tokenId": params.token_id,
        "makerAmount": making_amount.to_string(),
        "takerAmount": taking_amount.to_string(),
        "expiration": expiration.to_string(),
        "nonce": "0",
        "feeRateBps": meta.fee_rate_bps.to_string(),
        "side": side_num.to_string(),
        "signatureType": creds.signature_type.as_u8().to_string(),
    });

    Ok(Eip712Payload {
        domain,
        types,
        primary_type: "Order".into(),
        message,
    })
}

fn build_order_body(
    params: &OrderParams,
    payload: &Eip712Payload,
    signature: &str,
    funder: &str,
    creds: &StoredCredentials,
    _meta: &MarketMeta,
) -> Result<serde_json::Value> {
    let order_type = params.order_type.to_string();

    // The CLOB expects specific types in the order JSON body:
    // - salt: number (parsed from string)
    // - side: "BUY" or "SELL" (not numeric)
    // - signatureType: number (not string)
    // The EIP-712 message uses string representations, but the body format differs.
    let salt: u64 = payload.message["salt"].as_str()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);

    let side_str = match params.side {
        OrderSide::Buy => "BUY",
        OrderSide::Sell => "SELL",
    };

    let sig_type = creds.signature_type.as_u8();

    let mut body = serde_json::json!({
        "order": {
            "salt": salt,
            "maker": payload.message["maker"],
            "signer": payload.message["signer"],
            "taker": payload.message["taker"],
            "tokenId": payload.message["tokenId"],
            "makerAmount": payload.message["makerAmount"],
            "takerAmount": payload.message["takerAmount"],
            "expiration": payload.message["expiration"],
            "nonce": payload.message["nonce"],
            "feeRateBps": payload.message["feeRateBps"],
            "side": side_str,
            "signatureType": sig_type,
            "signature": signature,
        },
        "owner": funder,
        "orderType": order_type,
        "deferExec": false,
    });

    if params.post_only {
        body["postOnly"] = serde_json::Value::Bool(true);
    }

    Ok(body)
}

// ── V2 Order Building ──

fn build_v2_order_payload(
    signer_address: Address,
    creds: &StoredCredentials,
    params: &OrderParams,
    meta: &MarketMeta,
) -> Result<Eip712Payload> {
    // V2 exchange selection: CTF_EXCHANGE for normal, NEG_RISK_EXCHANGE_A for neg_risk
    let exchange = if meta.neg_risk { V2_NEG_RISK_EXCHANGE_A } else { V2_CTF_EXCHANGE };

    // Same rounding logic as V1
    let tick_size_str = meta.tick_size.as_str();
    let rc = match tick_size_str {
        "0.1"    => RoundingConfig { price: 1, size: 2, amount: 3 },
        "0.001"  => RoundingConfig { price: 3, size: 2, amount: 5 },
        "0.0001" => RoundingConfig { price: 4, size: 2, amount: 6 },
        _        => RoundingConfig { price: 2, size: 2, amount: 4 }, // "0.01" default
    };

    let raw_price = round_normal(params.price, rc.price);
    let side_num: u8;
    let making_amount: u64;
    let taking_amount: u64;

    match params.side {
        OrderSide::Buy => {
            side_num = 0;
            let raw_taker = round_down(params.size, rc.size);
            let mut raw_maker = raw_taker * raw_price;
            if decimal_places(raw_maker) > rc.amount {
                raw_maker = round_up(raw_maker, rc.amount + 4);
                if decimal_places(raw_maker) > rc.amount {
                    raw_maker = round_down(raw_maker, rc.amount);
                }
            }
            // `.round() as u64` — float->int cast truncates toward zero; `.round()` avoids the
            // 0.43 * 4 = 1.7199999...  →  1719999 bug that breaks V2 CLOB amount validation.
            making_amount = (raw_maker * 1_000_000.0).round() as u64;
            taking_amount = (raw_taker * 1_000_000.0).round() as u64;
        }
        OrderSide::Sell => {
            side_num = 1;
            let raw_maker = round_down(params.size, rc.size);
            let mut raw_taker = raw_maker * raw_price;
            if decimal_places(raw_taker) > rc.amount {
                raw_taker = round_up(raw_taker, rc.amount + 4);
                if decimal_places(raw_taker) > rc.amount {
                    raw_taker = round_down(raw_taker, rc.amount);
                }
            }
            making_amount = (raw_maker * 1_000_000.0).round() as u64;
            taking_amount = (raw_taker * 1_000_000.0).round() as u64;
        }
    }

    let funder = creds.funder_address.as_deref().unwrap_or(&creds.wallet_address);

    // V2 uses timestamp in milliseconds (not salt from random u32)
    let timestamp_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;

    // V2 salt = timestamp in ms (matching verified working order format)
    let salt = timestamp_ms;

    // V2 metadata defaults to zero bytes32; builder optionally supplied by caller.
    let zero_bytes32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
    let builder_hex = params.builder.as_deref().unwrap_or(zero_bytes32);

    let domain = serde_json::json!({
        "name": V2_DOMAIN_NAME,
        "version": V2_DOMAIN_VERSION,
        "chainId": CHAIN_ID,
        "verifyingContract": exchange,
    });

    let types = serde_json::json!({
        "EIP712Domain": [
            {"name": "name", "type": "string"},
            {"name": "version", "type": "string"},
            {"name": "chainId", "type": "uint256"},
            {"name": "verifyingContract", "type": "address"}
        ],
        "Order": [
            {"name": "salt", "type": "uint256"},
            {"name": "maker", "type": "address"},
            {"name": "signer", "type": "address"},
            {"name": "tokenId", "type": "uint256"},
            {"name": "makerAmount", "type": "uint256"},
            {"name": "takerAmount", "type": "uint256"},
            {"name": "side", "type": "uint8"},
            {"name": "signatureType", "type": "uint8"},
            {"name": "timestamp", "type": "uint256"},
            {"name": "metadata", "type": "bytes32"},
            {"name": "builder", "type": "bytes32"}
        ]
    });

    let message = serde_json::json!({
        "salt": salt.to_string(),
        "maker": funder,
        "signer": format!("{}", signer_address),
        "tokenId": params.token_id,
        "makerAmount": making_amount.to_string(),
        "takerAmount": taking_amount.to_string(),
        "side": side_num.to_string(),
        "signatureType": creds.signature_type.as_u8().to_string(),
        "timestamp": timestamp_ms.to_string(),
        "metadata": zero_bytes32,
        "builder": builder_hex,
    });

    Ok(Eip712Payload {
        domain,
        types,
        primary_type: "Order".into(),
        message,
    })
}

fn build_v2_order_body(
    params: &OrderParams,
    payload: &Eip712Payload,
    signature: &str,
    owner: &str,
    creds: &StoredCredentials,
) -> Result<serde_json::Value> {
    let order_type = params.order_type.to_string();

    // V2 CLOB body format (matches @polymarket/clob-client-v2):
    // - salt: NUMBER (not string)
    // - side: "BUY"/"SELL" string
    // - signatureType: NUMBER
    // - tokenId: string
    // - makerAmount/takerAmount: string
    // - timestamp: string (ms since epoch)
    // - expiration: string ("0" = no expiration)
    // - metadata/builder: bytes32 hex string
    // - NO taker, nonce, feeRateBps fields (OrderV2 type drops them)

    let salt: u64 = payload.message["salt"].as_str()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);

    let side_str = match params.side {
        OrderSide::Buy => "BUY",
        OrderSide::Sell => "SELL",
    };

    let sig_type = creds.signature_type.as_u8();

    // V2 CLOB wire format (matches @polymarket/clob-client-v2):
    //   top-level: { order, owner, orderType, postOnly, deferExec }
    //   order:     includes taker = zero address, expiration = "0" (post-sign fields)
    let body = serde_json::json!({
        "order": {
            "salt": salt,
            "maker": payload.message["maker"],
            "signer": payload.message["signer"],
            "taker": "0x0000000000000000000000000000000000000000",
            "tokenId": payload.message["tokenId"],
            "makerAmount": payload.message["makerAmount"],
            "takerAmount": payload.message["takerAmount"],
            "side": side_str,
            "signatureType": sig_type,
            "timestamp": payload.message["timestamp"],
            "expiration": "0",
            "metadata": payload.message["metadata"],
            "builder": payload.message["builder"],
            "signature": signature,
        },
        "owner": owner,
        "orderType": order_type,
        "postOnly": params.post_only,
        "deferExec": false,
    });

    Ok(body)
}

impl Default for OrderParams {
    fn default() -> Self {
        Self {
            token_id: String::new(),
            side: OrderSide::Buy,
            price: 0.0,
            size: 0.0,
            order_type: OrderType::GTC,
            expiration: None,
            post_only: false,
            fee_config: None,
            builder: None,
        }
    }
}

// ── Rounding helpers (ported from TS SDK's ROUNDING_CONFIG + utilities) ──

struct RoundingConfig {
    price: u32,
    size: u32,
    amount: u32,
}

fn decimal_places(num: f64) -> u32 {
    if num.fract() == 0.0 {
        return 0;
    }
    let s = format!("{}", num);
    match s.split_once('.') {
        Some((_, frac)) => frac.len() as u32,
        None => 0,
    }
}

fn round_normal(num: f64, decimals: u32) -> f64 {
    if decimal_places(num) <= decimals {
        return num;
    }
    let factor = 10f64.powi(decimals as i32);
    ((num + f64::EPSILON) * factor).round() / factor
}

fn round_down(num: f64, decimals: u32) -> f64 {
    if decimal_places(num) <= decimals {
        return num;
    }
    let factor = 10f64.powi(decimals as i32);
    (num * factor).floor() / factor
}

fn round_up(num: f64, decimals: u32) -> f64 {
    if decimal_places(num) <= decimals {
        return num;
    }
    let factor = 10f64.powi(decimals as i32);
    (num * factor).ceil() / factor
}