perpcity-sdk 0.2.1

Rust SDK for the PerpCity perpetual futures protocol on Base L2
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
//! High-level client for the PerpCity perpetual futures protocol.
//!
//! [`PerpClient`] wires together the transport layer, HFT infrastructure,
//! and contract bindings into a single ergonomic API. It is the primary
//! entry point for interacting with PerpCity on Base L2.
//!
//! # Example
//!
//! ```rust,no_run
//! use perpcity_sdk::{PerpClient, Deployments, HftTransport, TransportConfig};
//! use alloy::primitives::{address, Address, B256};
//! use alloy::signers::local::PrivateKeySigner;
//!
//! # async fn example() -> perpcity_sdk::Result<()> {
//! let transport = HftTransport::new(
//!     TransportConfig::builder()
//!         .shared_endpoint("https://mainnet.base.org")
//!         .build()?
//! )?;
//!
//! let signer: PrivateKeySigner = "your_private_key_hex".parse().unwrap();
//!
//! let deployments = Deployments {
//!     perp_manager: address!("0000000000000000000000000000000000000001"),
//!     usdc: address!("C1a5D4E99BB224713dd179eA9CA2Fa6600706210"),
//!     fees_module: None,
//!     margin_ratios_module: None,
//!     lockup_period_module: None,
//!     sqrt_price_impact_limit_module: None,
//! };
//!
//! let client = PerpClient::new(transport, signer, deployments, 8453)?;
//! # Ok(())
//! # }
//! ```

use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use alloy::network::{Ethereum, EthereumWallet, TransactionBuilder};
use alloy::primitives::{Address, B256, Bytes, I256, U256};
use alloy::providers::{Provider, RootProvider};
use alloy::rpc::client::RpcClient;
use alloy::rpc::types::TransactionRequest;
use alloy::signers::local::PrivateKeySigner;
use alloy::transports::BoxTransport;

use crate::constants::SCALE_1E6;
use alloy::sol_types::{SolCall, SolValue};

use crate::constants::MULTICALL3;
use crate::contracts::{IBeacon, IERC20, IFees, IMarginRatios, IMulticall3, PerpManager};
use crate::convert::{
    leverage_to_margin_ratio, margin_ratio_to_leverage, scale_from_6dec, scale_to_6dec,
};
use crate::errors::{PerpCityError, Result};
use crate::hft::gas::{FeeCache, GasLimitCache, GasLimits, Urgency};
use crate::hft::pipeline::{PipelineConfig, TxPipeline, TxRequest};
use crate::hft::state_cache::{CachedBounds, CachedFees, StateCache, StateCacheConfig};
use crate::math::tick::{align_tick_down, align_tick_up, price_to_tick};
use crate::transport::provider::HftTransport;
use crate::types::{
    AdjustMarginParams, AdjustMarginResult, AdjustNotionalParams, AdjustNotionalResult, Bounds,
    CloseParams, CloseResult, Deployments, Fees, LiveDetails, OpenInterest, OpenMakerParams,
    OpenMakerQuote, OpenResult, OpenTakerParams, OpenTakerQuote, PerpData, PerpSnapshot, SwapQuote,
};

// ── Constants ────────────────────────────────────────────────────────

/// Base L2 chain ID.
const BASE_CHAIN_ID: u64 = 8453;

/// Default gas cache TTL: 2 seconds (2 Base L2 blocks).
const DEFAULT_GAS_TTL_MS: u64 = 2_000;

/// Default priority fee: 0.01 gwei.
///
/// Base L2 uses a single sequencer, so priority fees are near-meaningless.
/// 10 Mwei is sufficient for reliable inclusion while keeping gas escrow low.
const DEFAULT_PRIORITY_FEE: u64 = 10_000_000;

/// Default receipt polling timeout.
const RECEIPT_TIMEOUT: Duration = Duration::from_secs(30);

/// Maximum USDC approval amount (2^256 - 1).
const MAX_APPROVAL: U256 = U256::MAX;

/// SCALE_1E6 as f64, used for converting on-chain fixed-point values.
const SCALE_F64: f64 = SCALE_1E6 as f64;

/// Convert a Q96 fixed-point funding-per-second value to a daily rate.
fn funding_x96_to_daily(funding_x96: I256) -> f64 {
    let funding_i128 = i128_from_i256(funding_x96);
    let rate_per_sec = funding_i128 as f64 / 2.0_f64.powi(96);
    rate_per_sec * crate::constants::INTERVAL as f64
}

// ── From impls for cache↔client type bridging ────────────────────────

impl From<CachedFees> for Fees {
    fn from(c: CachedFees) -> Self {
        Self {
            creator_fee: c.creator_fee,
            insurance_fee: c.insurance_fee,
            lp_fee: c.lp_fee,
            liquidation_fee: c.liquidation_fee,
        }
    }
}

impl From<Fees> for CachedFees {
    fn from(f: Fees) -> Self {
        Self {
            creator_fee: f.creator_fee,
            insurance_fee: f.insurance_fee,
            lp_fee: f.lp_fee,
            liquidation_fee: f.liquidation_fee,
        }
    }
}

impl From<CachedBounds> for Bounds {
    fn from(c: CachedBounds) -> Self {
        Self {
            min_margin: c.min_margin,
            min_taker_leverage: c.min_taker_leverage,
            max_taker_leverage: c.max_taker_leverage,
            liquidation_taker_ratio: c.liquidation_taker_ratio,
        }
    }
}

impl From<Bounds> for CachedBounds {
    fn from(b: Bounds) -> Self {
        Self {
            min_margin: b.min_margin,
            min_taker_leverage: b.min_taker_leverage,
            max_taker_leverage: b.max_taker_leverage,
            liquidation_taker_ratio: b.liquidation_taker_ratio,
        }
    }
}

// ── PerpClient ───────────────────────────────────────────────────────

/// High-level client for the PerpCity protocol.
///
/// Combines transport, signing, transaction pipeline, state caching, and
/// contract bindings into one ergonomic API. All write operations go
/// through the [`TxPipeline`] for zero-RPC-on-hot-path nonce/gas resolution.
/// Read operations use the [`StateCache`] to avoid redundant RPC calls.
pub struct PerpClient {
    /// Alloy provider wired to HftTransport (multi-endpoint, health-aware).
    provider: RootProvider<Ethereum>,
    /// The underlying transport (kept for health diagnostics).
    transport: HftTransport,
    /// Wallet for signing transactions.
    wallet: EthereumWallet,
    /// The signer's address.
    address: Address,
    /// Deployed contract addresses.
    deployments: Deployments,
    /// Chain ID for transaction building.
    chain_id: u64,
    /// Transaction pipeline (nonce + gas). Mutex for interior mutability.
    pipeline: Mutex<TxPipeline>,
    /// Gas fee cache, updated from block headers.
    fee_cache: Mutex<FeeCache>,
    /// Cached gas estimates from `eth_estimateGas`, keyed by function selector.
    gas_limit_cache: Mutex<GasLimitCache>,
    /// Multi-layer state cache for on-chain reads.
    state_cache: Mutex<StateCache>,
}

impl std::fmt::Debug for PerpClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PerpClient")
            .field("address", &self.address)
            .field("chain_id", &self.chain_id)
            .field("deployments", &self.deployments)
            .finish_non_exhaustive()
    }
}

impl PerpClient {
    /// Create a new PerpClient.
    ///
    /// - `transport`: Multi-endpoint RPC transport (from [`crate::TransportConfig`])
    /// - `signer`: Private key for signing transactions
    /// - `deployments`: Contract addresses for this PerpCity instance
    /// - `chain_id`: Chain ID (8453 for Base mainnet, 84532 for Base Sepolia)
    ///
    /// This does NOT make any network calls. Call [`Self::refresh_gas`] and
    /// [`Self::sync_nonce`] before submitting transactions.
    pub fn new(
        transport: HftTransport,
        signer: PrivateKeySigner,
        deployments: Deployments,
        chain_id: u64,
    ) -> Result<Self> {
        let address = signer.address();
        let wallet = EthereumWallet::from(signer);

        let boxed = BoxTransport::new(transport.clone());
        let rpc_client = RpcClient::new(boxed, false);
        let provider = RootProvider::<Ethereum>::new(rpc_client);

        Ok(Self {
            provider,
            transport,
            wallet,
            address,
            deployments,
            chain_id,
            // Pipeline starts at nonce 0; call sync_nonce() before first tx
            pipeline: Mutex::new(TxPipeline::new(0, PipelineConfig::default())),
            fee_cache: Mutex::new(FeeCache::new(DEFAULT_GAS_TTL_MS, DEFAULT_PRIORITY_FEE)),
            gas_limit_cache: Mutex::new(GasLimitCache::new()),
            state_cache: Mutex::new(StateCache::new(StateCacheConfig::default())),
        })
    }

    /// Create a client pre-configured for Base mainnet.
    pub fn new_base_mainnet(
        transport: HftTransport,
        signer: PrivateKeySigner,
        deployments: Deployments,
    ) -> Result<Self> {
        Self::new(transport, signer, deployments, BASE_CHAIN_ID)
    }

    // ── Initialization ───────────────────────────────────────────────

    /// Sync the nonce manager with the on-chain transaction count.
    ///
    /// Must be called before the first transaction. After this, the
    /// pipeline manages nonces locally (zero RPC per transaction).
    pub async fn sync_nonce(&self) -> Result<()> {
        let count = self.provider.get_transaction_count(self.address).await?;
        let mut pipeline = self.pipeline.lock().unwrap();
        *pipeline = TxPipeline::new(count, PipelineConfig::default());
        tracing::info!(nonce = count, address = %self.address, "nonce synced");
        Ok(())
    }

    /// Refresh the gas cache from the latest block header.
    ///
    /// Fetches the latest block directly in a single RPC call and extracts
    /// the base fee for EIP-1559 fee computation. Should be called
    /// periodically (every 1-2 seconds on Base L2) or from a `newHeads`
    /// subscription callback.
    pub async fn refresh_gas(&self) -> Result<()> {
        let header = self
            .provider
            .get_block_by_number(alloy::eips::BlockNumberOrTag::Latest)
            .await?
            .ok_or_else(|| PerpCityError::GasPriceUnavailable {
                reason: "latest block not found".into(),
            })?;

        let base_fee =
            header
                .header
                .base_fee_per_gas
                .ok_or_else(|| PerpCityError::GasPriceUnavailable {
                    reason: "block has no base fee (pre-EIP-1559?)".into(),
                })?;

        let now = now_ms();
        self.fee_cache.lock().unwrap().update(base_fee, now);
        tracing::debug!(base_fee, "gas cache refreshed");
        Ok(())
    }

    /// Inject a base fee from an external source (e.g. a shared poller).
    ///
    /// Updates the gas cache as if `refresh_gas` had been called, but without
    /// any RPC calls. The cache TTL is reset to now.
    pub fn set_base_fee(&self, base_fee: u64) {
        let now = now_ms();
        self.fee_cache.lock().unwrap().update(base_fee, now);
        tracing::debug!(base_fee, "base fee injected");
    }

    /// Return the current cached base fee, if any (ignores TTL).
    ///
    /// Intended for reading the base fee after `refresh_gas` in order to
    /// distribute it to other clients via [`set_base_fee`](Self::set_base_fee).
    pub fn base_fee(&self) -> Option<u64> {
        self.fee_cache.lock().unwrap().base_fee()
    }

    /// Override the gas cache TTL (milliseconds).
    ///
    /// When gas is managed externally via [`set_base_fee`](Self::set_base_fee),
    /// the default 2s TTL may be too tight. Set this to match the poller's
    /// cadence with headroom (e.g. `tick_secs * 2 * 1000`).
    pub fn set_gas_ttl(&self, ttl_ms: u64) {
        self.fee_cache.lock().unwrap().set_ttl(ttl_ms);
        tracing::debug!(ttl_ms, "gas cache TTL updated");
    }

    // ── Write operations ─────────────────────────────────────────────

    /// Open a taker (long/short) position.
    ///
    /// Returns an [`OpenResult`] with the position ID and entry deltas
    /// parsed from the `PositionOpened` event, so callers can construct
    /// position tracking data without a follow-up RPC read.
    ///
    /// # Errors
    ///
    /// Returns [`PerpCityError::TxReverted`] if the transaction reverts,
    /// or [`PerpCityError::EventNotFound`] if the `PositionOpened` event
    /// is missing from the receipt.
    pub async fn open_taker(
        &self,
        perp_id: B256,
        params: &OpenTakerParams,
        urgency: Urgency,
    ) -> Result<OpenResult> {
        let margin_scaled = scale_to_6dec(params.margin)?;
        if margin_scaled <= 0 {
            return Err(PerpCityError::InvalidMargin {
                reason: format!("margin must be positive, got {}", params.margin),
            });
        }
        let margin_ratio = leverage_to_margin_ratio(params.leverage)?;

        let wire_params = PerpManager::OpenTakerPositionParams {
            holder: self.address,
            isLong: params.is_long,
            margin: margin_scaled as u128,
            marginRatio: u32_to_u24(margin_ratio),
            unspecifiedAmountLimit: params.unspecified_amount_limit,
        };

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let calldata = contract
            .openTakerPos(perp_id, wire_params)
            .calldata()
            .clone();

        tracing::info!(%perp_id, margin = params.margin, leverage = params.leverage, is_long = params.is_long, ?urgency, "opening taker position");

        let receipt = self
            .send_tx(self.deployments.perp_manager, calldata, None, urgency)
            .await?;

        let result = parse_open_result(&receipt)?;
        tracing::info!(%perp_id, pos_id = %result.pos_id, perp_delta = result.perp_delta, usd_delta = result.usd_delta, "taker position opened");
        Ok(result)
    }

    /// Open a maker (LP) position within a price range.
    ///
    /// Converts `price_lower`/`price_upper` to aligned ticks internally.
    /// Returns an [`OpenResult`] with the position ID and entry deltas.
    pub async fn open_maker(
        &self,
        perp_id: B256,
        params: &OpenMakerParams,
        urgency: Urgency,
    ) -> Result<OpenResult> {
        let margin_scaled = scale_to_6dec(params.margin)?;
        if margin_scaled <= 0 {
            return Err(PerpCityError::InvalidMargin {
                reason: format!("margin must be positive, got {}", params.margin),
            });
        }

        let tick_lower = align_tick_down(
            price_to_tick(params.price_lower)?,
            crate::constants::TICK_SPACING,
        );
        let tick_upper = align_tick_up(
            price_to_tick(params.price_upper)?,
            crate::constants::TICK_SPACING,
        );

        if tick_lower >= tick_upper {
            return Err(PerpCityError::InvalidTickRange {
                lower: tick_lower,
                upper: tick_upper,
            });
        }

        // Liquidity must fit in u120 on-chain
        let liquidity: u128 = params.liquidity;
        let max_u120: u128 = (1u128 << 120) - 1;
        if liquidity > max_u120 {
            return Err(PerpCityError::Overflow {
                context: format!("liquidity {} exceeds uint120 max", liquidity),
            });
        }

        let wire_params = PerpManager::OpenMakerPositionParams {
            holder: self.address,
            margin: margin_scaled as u128,
            liquidity: alloy::primitives::Uint::<120, 2>::from(liquidity),
            tickLower: i32_to_i24(tick_lower),
            tickUpper: i32_to_i24(tick_upper),
            maxAmt0In: params.max_amt0_in,
            maxAmt1In: params.max_amt1_in,
        };

        tracing::info!(%perp_id, margin = params.margin, tick_lower, tick_upper, ?urgency, "opening maker position");

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let calldata = contract
            .openMakerPos(perp_id, wire_params)
            .calldata()
            .clone();

        let receipt = self
            .send_tx(self.deployments.perp_manager, calldata, None, urgency)
            .await?;

        let result = parse_open_result(&receipt)?;
        tracing::info!(%perp_id, pos_id = %result.pos_id, perp_delta = result.perp_delta, usd_delta = result.usd_delta, "maker position opened");
        Ok(result)
    }

    /// Close a position (taker or maker).
    ///
    /// Returns a [`CloseResult`] with the transaction hash and optional
    /// remaining position ID (for partial closes).
    pub async fn close_position(
        &self,
        pos_id: U256,
        params: &CloseParams,
        urgency: Urgency,
    ) -> Result<CloseResult> {
        let wire_params = PerpManager::ClosePositionParams {
            posId: pos_id,
            minAmt0Out: params.min_amt0_out,
            minAmt1Out: params.min_amt1_out,
            maxAmt1In: params.max_amt1_in,
        };

        tracing::info!(pos_id = %pos_id, ?urgency, "closing position");

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let calldata = contract.closePosition(wire_params).calldata().clone();

        let receipt = self
            .send_tx(self.deployments.perp_manager, calldata, None, urgency)
            .await?;

        let result = parse_close_result(&receipt, pos_id)?;
        tracing::info!(pos_id = %pos_id, was_liquidated = result.was_liquidated, net_margin = result.net_margin, "position closed");
        Ok(result)
    }

    /// Adjust the notional exposure of a taker position.
    ///
    /// - `usd_delta > 0`: receive USD by selling perp tokens (reduce exposure)
    /// - `usd_delta < 0`: spend USD to buy perp tokens (increase exposure)
    pub async fn adjust_notional(
        &self,
        pos_id: U256,
        params: &AdjustNotionalParams,
        urgency: Urgency,
    ) -> Result<AdjustNotionalResult> {
        let usd_delta_scaled = scale_to_6dec(params.usd_delta)?;

        let wire_params = PerpManager::AdjustNotionalParams {
            posId: pos_id,
            usdDelta: I256::try_from(usd_delta_scaled).map_err(|_| PerpCityError::Overflow {
                context: format!("usd_delta {} overflows I256", usd_delta_scaled),
            })?,
            perpLimit: params.perp_limit,
        };

        tracing::info!(pos_id = %pos_id, usd_delta = params.usd_delta, ?urgency, "adjusting notional");

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let calldata = contract.adjustNotional(wire_params).calldata().clone();

        let receipt = self
            .send_tx(self.deployments.perp_manager, calldata, None, urgency)
            .await?;

        let result = parse_adjust_result(&receipt)?;
        tracing::info!(pos_id = %pos_id, new_perp_delta = result.new_perp_delta, "notional adjusted");
        Ok(result)
    }

    /// Add or remove margin from a position.
    ///
    /// - `margin_delta > 0`: deposit more margin
    /// - `margin_delta < 0`: withdraw margin
    pub async fn adjust_margin(
        &self,
        pos_id: U256,
        params: &AdjustMarginParams,
        urgency: Urgency,
    ) -> Result<AdjustMarginResult> {
        let delta_scaled = scale_to_6dec(params.margin_delta)?;

        let wire_params = PerpManager::AdjustMarginParams {
            posId: pos_id,
            marginDelta: I256::try_from(delta_scaled).map_err(|_| PerpCityError::Overflow {
                context: format!("margin_delta {} overflows I256", delta_scaled),
            })?,
        };

        tracing::info!(pos_id = %pos_id, margin_delta = params.margin_delta, ?urgency, "adjusting margin");

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let calldata = contract.adjustMargin(wire_params).calldata().clone();

        let receipt = self
            .send_tx(self.deployments.perp_manager, calldata, None, urgency)
            .await?;

        let result = parse_margin_result(&receipt)?;
        tracing::info!(pos_id = %pos_id, new_margin = result.new_margin, "margin adjusted");
        Ok(result)
    }

    /// Ensure USDC is approved for the PerpManager to spend.
    ///
    /// Checks current allowance and only sends an `approve` transaction
    /// if the allowance is below `min_amount`. Approves for `U256::MAX`
    /// (infinite approval) to avoid repeated approve calls.
    pub async fn ensure_approval(&self, min_amount: U256) -> Result<Option<B256>> {
        let usdc = IERC20::new(self.deployments.usdc, &self.provider);
        let allowance: U256 = usdc
            .allowance(self.address, self.deployments.perp_manager)
            .call()
            .await?;

        if allowance >= min_amount {
            tracing::debug!(allowance = %allowance, "USDC approval sufficient");
            return Ok(None);
        }

        tracing::info!(allowance = %allowance, min_amount = %min_amount, "approving USDC");

        let calldata = usdc
            .approve(self.deployments.perp_manager, MAX_APPROVAL)
            .calldata()
            .clone();

        let receipt = self
            .send_tx(self.deployments.usdc, calldata, None, Urgency::Normal)
            .await?;

        tracing::info!(tx_hash = %receipt.transaction_hash, "USDC approved");
        Ok(Some(receipt.transaction_hash))
    }

    // ── Read operations ──────────────────────────────────────────────

    /// Get the full perp configuration, fees, and bounds for a market.
    ///
    /// Uses the [`StateCache`] for fees and bounds (60s TTL). The perp
    /// config itself is always fetched fresh (it's cheap and rarely changes).
    pub async fn get_perp_config(&self, perp_id: B256) -> Result<PerpData> {
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);

        // Fetch perp config — sol!(rpc) returns the struct directly
        let config: PerpManager::PerpConfig = contract.cfgs(perp_id).call().await?;

        // Zero beacon means the perp was never created
        if config.beacon == Address::ZERO {
            return Err(PerpCityError::PerpNotFound { perp_id });
        }

        let beacon = config.beacon;

        // Fetch mark price via TWAP (short window = ~current price)
        let sqrt_price_x96: U256 = contract
            .timeWeightedAvgSqrtPriceX96(perp_id, 1)
            .call()
            .await?;
        let mark = crate::convert::sqrt_price_x96_to_price(sqrt_price_x96)?;

        let fees = self.get_or_fetch_fees(&config).await?;
        let bounds = self.get_or_fetch_bounds(&config).await?;

        Ok(PerpData {
            id: perp_id,
            tick_spacing: i24_to_i32(config.key.tickSpacing),
            mark,
            beacon,
            bounds,
            fees,
        })
    }

    /// Get perp data: beacon, tick spacing, and current mark price.
    ///
    /// Lighter-weight than [`Self::get_perp_config`] — skips fees/bounds lookups.
    pub async fn get_perp_data(&self, perp_id: B256) -> Result<(Address, i32, f64)> {
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let config: PerpManager::PerpConfig = contract.cfgs(perp_id).call().await?;

        let sqrt_price_x96: U256 = contract
            .timeWeightedAvgSqrtPriceX96(perp_id, 1)
            .call()
            .await?;
        let mark = crate::convert::sqrt_price_x96_to_price(sqrt_price_x96)?;

        Ok((config.beacon, i24_to_i32(config.key.tickSpacing), mark))
    }

    /// Get an on-chain position by its NFT token ID.
    ///
    /// Returns the raw contract position struct. Use [`crate::math::position`]
    /// functions to compute derived values (entry price, PnL, etc.).
    pub async fn get_position(&self, pos_id: U256) -> Result<PerpManager::Position> {
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let pos: PerpManager::Position = contract.positions(pos_id).call().await?;

        // Check if position exists (empty perpId = uninitialized)
        if pos.perpId == B256::ZERO {
            return Err(PerpCityError::PositionNotFound { pos_id });
        }

        Ok(pos)
    }

    /// Get all position IDs owned by an address.
    ///
    /// Iterates through all minted position NFTs (1..nextPosId) and returns
    /// those owned by `owner`. Burned or non-existent tokens are skipped.
    ///
    /// **Note:** This is O(n) in total positions ever minted. For high-throughput
    /// use cases, prefer the bot API's position endpoints instead.
    pub async fn get_positions_by_owner(&self, owner: Address) -> Result<Vec<U256>> {
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let next_pos_id: U256 = contract.nextPosId().call().await?;

        let total: u64 = next_pos_id
            .try_into()
            .map_err(|_| PerpCityError::Overflow {
                context: "nextPosId exceeds u64".into(),
            })?;
        if total <= 1 {
            return Ok(vec![]);
        }

        let mut owned = Vec::new();
        for id in 1..total {
            let pos_id = U256::from(id);
            // ownerOf reverts for burned/non-existent tokens — those
            // surface as contract errors, which we skip. Other transport
            // errors propagate so network failures aren't silently ignored.
            match contract.ownerOf(pos_id).call().await {
                Ok(addr) if addr == owner => owned.push(pos_id),
                Ok(_) => {}
                Err(e @ alloy::contract::Error::TransportError(_)) => return Err(e.into()),
                Err(_) => {} // burned or non-existent token
            }
        }

        Ok(owned)
    }

    /// Get the current mark price for a perp (TWAP with 1-second lookback).
    ///
    /// Uses the fast cache layer (2s TTL).
    pub async fn get_mark_price(&self, perp_id: B256) -> Result<f64> {
        let now_ts = now_secs();
        let perp_bytes: [u8; 32] = perp_id.into();

        // Check cache
        {
            let cache = self.state_cache.lock().unwrap();
            if let Some(price) = cache.get_mark_price(&perp_bytes, now_ts) {
                tracing::trace!(%perp_id, price, "mark price cache hit");
                return Ok(price);
            }
        }

        // Fetch from chain
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let sqrt_price_x96: U256 = contract
            .timeWeightedAvgSqrtPriceX96(perp_id, 1)
            .call()
            .await?;
        let price = crate::convert::sqrt_price_x96_to_price(sqrt_price_x96)?;

        tracing::debug!(%perp_id, price, "mark price fetched");

        // Update cache
        {
            let mut cache = self.state_cache.lock().unwrap();
            cache.put_mark_price(perp_bytes, price, now_ts);
        }

        Ok(price)
    }

    /// Get the oracle index price from a beacon contract.
    ///
    /// The beacon address is available from `PerpData.beacon` (returned by
    /// [`get_perp_config`](Self::get_perp_config)).
    pub async fn get_index_price(&self, beacon: Address) -> Result<f64> {
        let contract = IBeacon::new(beacon, &self.provider);
        let index_x96: U256 = contract.index().call().await?;

        if index_x96.is_zero() {
            return Err(PerpCityError::InvalidPrice {
                reason: "beacon returned zero index".into(),
            });
        }

        crate::convert::price_x96_to_f64(index_x96)
    }

    /// Simulate closing a position to get live PnL, funding, and liquidation status.
    ///
    /// This is a read-only call (no transaction sent).
    pub async fn get_live_details(&self, pos_id: U256) -> Result<LiveDetails> {
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let result = contract.quoteClosePosition(pos_id).call().await?;

        // Check for unexpected revert reason
        if !result.unexpectedReason.is_empty() {
            return Err(PerpCityError::TxReverted {
                reason: format!(
                    "quoteClosePosition reverted: 0x{}",
                    alloy::primitives::hex::encode(&result.unexpectedReason)
                ),
            });
        }

        let scale = SCALE_F64;
        Ok(LiveDetails {
            pnl: i128_from_i256(result.pnl) as f64 / scale,
            funding_payment: i128_from_i256(result.funding) as f64 / scale,
            effective_margin: i128_from_i256(result.netMargin) as f64 / scale,
            is_liquidatable: result.wasLiquidated,
        })
    }

    /// Get taker open interest for a perp market.
    pub async fn get_open_interest(&self, perp_id: B256) -> Result<OpenInterest> {
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let result = contract.takerOpenInterest(perp_id).call().await?;

        let scale = SCALE_F64;
        Ok(OpenInterest {
            long_oi: result.longOI as f64 / scale,
            short_oi: result.shortOI as f64 / scale,
        })
    }

    /// Simulate opening a taker position without sending a transaction.
    ///
    /// Returns the perp and USD deltas that would result from the trade.
    /// Useful for estimating price impact before committing capital.
    pub async fn quote_open_taker(
        &self,
        perp_id: B256,
        params: &OpenTakerParams,
    ) -> Result<OpenTakerQuote> {
        let margin_scaled = scale_to_6dec(params.margin)?;
        if margin_scaled <= 0 {
            return Err(PerpCityError::InvalidMargin {
                reason: format!("margin must be positive, got {}", params.margin),
            });
        }
        let margin_ratio = leverage_to_margin_ratio(params.leverage)?;

        let wire_params = PerpManager::OpenTakerPositionParams {
            holder: self.address,
            isLong: params.is_long,
            margin: margin_scaled as u128,
            marginRatio: u32_to_u24(margin_ratio),
            unspecifiedAmountLimit: params.unspecified_amount_limit,
        };

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let result = contract
            .quoteOpenTakerPosition(perp_id, wire_params)
            .call()
            .await?;

        if !result.unexpectedReason.is_empty() {
            return Err(PerpCityError::TxReverted {
                reason: format!(
                    "quoteOpenTakerPosition reverted: 0x{}",
                    alloy::primitives::hex::encode(&result.unexpectedReason)
                ),
            });
        }

        let scale = SCALE_F64;
        Ok(OpenTakerQuote {
            perp_delta: i128_from_i256(result.perpDelta) as f64 / scale,
            usd_delta: i128_from_i256(result.usdDelta) as f64 / scale,
        })
    }

    /// Simulate opening a maker (LP) position without sending a transaction.
    ///
    /// Returns the perp and USD deltas that would result from the position.
    pub async fn quote_open_maker(
        &self,
        perp_id: B256,
        params: &OpenMakerParams,
    ) -> Result<OpenMakerQuote> {
        let margin_scaled = scale_to_6dec(params.margin)?;
        if margin_scaled <= 0 {
            return Err(PerpCityError::InvalidMargin {
                reason: format!("margin must be positive, got {}", params.margin),
            });
        }

        let tick_lower = align_tick_down(
            price_to_tick(params.price_lower)?,
            crate::constants::TICK_SPACING,
        );
        let tick_upper = align_tick_up(
            price_to_tick(params.price_upper)?,
            crate::constants::TICK_SPACING,
        );

        let wire_params = PerpManager::OpenMakerPositionParams {
            holder: self.address,
            margin: margin_scaled as u128,
            tickLower: i32_to_i24(tick_lower),
            tickUpper: i32_to_i24(tick_upper),
            liquidity: alloy::primitives::Uint::<120, 2>::from(params.liquidity),
            maxAmt0In: params.max_amt0_in,
            maxAmt1In: params.max_amt1_in,
        };

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let result = contract
            .quoteOpenMakerPosition(perp_id, wire_params)
            .call()
            .await?;

        if !result.unexpectedReason.is_empty() {
            return Err(PerpCityError::TxReverted {
                reason: format!(
                    "quoteOpenMakerPosition reverted: 0x{}",
                    alloy::primitives::hex::encode(&result.unexpectedReason)
                ),
            });
        }

        let scale = SCALE_F64;
        Ok(OpenMakerQuote {
            perp_delta: i128_from_i256(result.perpDelta) as f64 / scale,
            usd_delta: i128_from_i256(result.usdDelta) as f64 / scale,
        })
    }

    /// Simulate a raw swap in a perp's Uniswap V4 pool without executing.
    ///
    /// This is the lowest-level quote — it simulates a single pool swap and
    /// returns the resulting token deltas. Use this to estimate price impact
    /// for a given trade size.
    ///
    /// # Arguments
    ///
    /// * `perp_id` — The perp market to quote against.
    /// * `zero_for_one` — Swap direction: `true` sells token0 for token1.
    /// * `is_exact_in` — `true` if `amount` is the exact input; `false` for exact output.
    /// * `amount` — The swap amount (scaled to 6 decimals).
    /// * `sqrt_price_limit_x96` — Price limit in sqrtPriceX96 format. Use `0` for no limit.
    pub async fn quote_swap(
        &self,
        perp_id: B256,
        zero_for_one: bool,
        is_exact_in: bool,
        amount: U256,
        sqrt_price_limit_x96: U256,
    ) -> Result<SwapQuote> {
        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let sqrt_limit = alloy::primitives::Uint::<160, 3>::from(sqrt_price_limit_x96);
        let result = contract
            .quoteSwap(perp_id, zero_for_one, is_exact_in, amount, sqrt_limit)
            .call()
            .await?;

        if !result.unexpectedReason.is_empty() {
            return Err(PerpCityError::TxReverted {
                reason: format!(
                    "quoteSwap reverted: 0x{}",
                    alloy::primitives::hex::encode(&result.unexpectedReason)
                ),
            });
        }

        let scale = SCALE_F64;
        Ok(SwapQuote {
            perp_delta: i128_from_i256(result.perpDelta) as f64 / scale,
            usd_delta: i128_from_i256(result.usdDelta) as f64 / scale,
        })
    }

    /// Get the funding rate per second for a perp, converted to a daily rate.
    ///
    /// Uses the fast cache layer (2s TTL).
    pub async fn get_funding_rate(&self, perp_id: B256) -> Result<f64> {
        let now_ts = now_secs();
        let perp_bytes: [u8; 32] = perp_id.into();

        // Check cache
        {
            let cache = self.state_cache.lock().unwrap();
            if let Some(rate) = cache.get_funding_rate(&perp_bytes, now_ts) {
                tracing::trace!(%perp_id, rate, "funding rate cache hit");
                return Ok(rate);
            }
        }

        let contract = PerpManager::new(self.deployments.perp_manager, &self.provider);
        let funding_x96: I256 = contract.fundingPerSecondX96(perp_id).call().await?;

        let daily_rate = funding_x96_to_daily(funding_x96);

        tracing::debug!(%perp_id, daily_rate, "funding rate fetched");

        // Update cache
        {
            let mut cache = self.state_cache.lock().unwrap();
            cache.put_funding_rate(perp_bytes, daily_rate, now_ts);
        }

        Ok(daily_rate)
    }

    /// Get the USDC balance of the signer's address.
    ///
    /// Uses the fast cache layer (2s TTL).
    pub async fn get_usdc_balance(&self) -> Result<f64> {
        let now_ts = now_secs();

        // Check cache
        {
            let cache = self.state_cache.lock().unwrap();
            if let Some(bal) = cache.get_usdc_balance(now_ts) {
                tracing::trace!(balance = bal, "USDC balance cache hit");
                return Ok(bal);
            }
        }

        let usdc = IERC20::new(self.deployments.usdc, &self.provider);
        let raw: U256 = usdc.balanceOf(self.address).call().await?;
        let raw_i128 = i128::try_from(raw).map_err(|_| PerpCityError::Overflow {
            context: format!("USDC balance {} exceeds i128::MAX", raw),
        })?;
        let balance = scale_from_6dec(raw_i128);

        tracing::debug!(balance, "USDC balance fetched");

        // Update cache
        {
            let mut cache = self.state_cache.lock().unwrap();
            cache.put_usdc_balance(balance, now_ts);
        }

        Ok(balance)
    }

    // ── Batch reads (via Multicall3) ──────────────────────────────────

    /// Get the USDC and ETH balances of an address in a single RPC call.
    ///
    /// Uses Multicall3 to bundle a `balanceOf` (USDC) and `getEthBalance`
    /// (native ETH) into one `eth_call`. The RPC provider charges 1 CU
    /// regardless of how many sub-calls the multicall executes.
    ///
    /// Returns `(usdc_balance, eth_balance)` where USDC is in human units
    /// (e.g. `100.0` = 100 USDC) and ETH is in wei.
    pub async fn get_balances(&self, address: Address) -> Result<(f64, U256)> {
        let results = self.get_balances_batch(&[address]).await?;
        Ok(results.into_iter().next().unwrap())
    }

    /// Get the USDC and ETH balances for multiple addresses in a single RPC call.
    ///
    /// Uses Multicall3 to bundle N × `balanceOf` + N × `getEthBalance` into
    /// one `eth_call`. For 10 addresses, this is 1 CU instead of 20.
    ///
    /// Returns a `Vec<(usdc_balance, eth_balance)>` in the same order as
    /// the input addresses.
    pub async fn get_balances_batch(&self, addresses: &[Address]) -> Result<Vec<(f64, U256)>> {
        if addresses.is_empty() {
            return Ok(Vec::new());
        }

        let usdc_addr = self.deployments.usdc;
        let n = addresses.len();

        // Build sub-calls: N × USDC balanceOf + N × ETH getEthBalance
        let mut calls = Vec::with_capacity(2 * n);

        for &addr in addresses {
            // USDC balanceOf(addr)
            let calldata = IERC20::balanceOfCall { account: addr }.abi_encode();
            calls.push(IMulticall3::Call3 {
                target: usdc_addr,
                allowFailure: false,
                callData: calldata.into(),
            });
        }

        for &addr in addresses {
            // getEthBalance(addr) — Multicall3 built-in
            let calldata = IMulticall3::getEthBalanceCall { addr }.abi_encode();
            calls.push(IMulticall3::Call3 {
                target: MULTICALL3,
                allowFailure: false,
                callData: calldata.into(),
            });
        }

        let multicall = IMulticall3::new(MULTICALL3, &self.provider);
        let results = multicall.aggregate3(calls).call().await?;

        if results.len() != 2 * n {
            return Err(PerpCityError::Overflow {
                context: format!(
                    "multicall returned {} results, expected {}",
                    results.len(),
                    2 * n
                ),
            });
        }

        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            // Decode USDC balance (first N results)
            let usdc_result = &results[i];
            if !usdc_result.success {
                return Err(PerpCityError::Overflow {
                    context: format!("USDC balanceOf failed for address {}", addresses[i]),
                });
            }
            let usdc_raw =
                U256::abi_decode(&usdc_result.returnData).map_err(|e| PerpCityError::Overflow {
                    context: format!("failed to decode USDC balance: {e}"),
                })?;
            let usdc_i128 = i128::try_from(usdc_raw).map_err(|_| PerpCityError::Overflow {
                context: format!("USDC balance {} exceeds i128::MAX", usdc_raw),
            })?;
            let usdc = scale_from_6dec(usdc_i128);

            // Decode ETH balance (last N results)
            let eth_result = &results[n + i];
            if !eth_result.success {
                return Err(PerpCityError::Overflow {
                    context: format!("getEthBalance failed for address {}", addresses[i]),
                });
            }
            let eth =
                U256::abi_decode(&eth_result.returnData).map_err(|e| PerpCityError::Overflow {
                    context: format!("failed to decode ETH balance: {e}"),
                })?;

            out.push((usdc, eth));
        }

        tracing::debug!(count = n, "batch balances fetched via multicall");
        Ok(out)
    }

    /// Get perp config and live market data in two multicalls (2 CUs total).
    ///
    /// Phase 1 multicalls `cfgs` + `timeWeightedAvgSqrtPriceX96` +
    /// `fundingPerSecondX96` + `takerOpenInterest` against PerpManager
    /// (4 reads → 1 CU). Phase 2 calls `index()` on the beacon returned
    /// by phase 1 (1 CU).
    ///
    /// Returns `(PerpData, PerpSnapshot)` — static config and live market
    /// data. Replaces the typical startup sequence of 5+ individual RPCs.
    pub async fn get_perp_snapshot(&self, perp_id: B256) -> Result<(PerpData, PerpSnapshot)> {
        let pm = self.deployments.perp_manager;

        // Phase 1: multicall cfgs + mark + funding + OI against PerpManager
        let calls = vec![
            IMulticall3::Call3 {
                target: pm,
                allowFailure: false,
                callData: PerpManager::cfgsCall { perpId: perp_id }
                    .abi_encode()
                    .into(),
            },
            IMulticall3::Call3 {
                target: pm,
                allowFailure: false,
                callData: PerpManager::timeWeightedAvgSqrtPriceX96Call {
                    perpId: perp_id,
                    lookbackWindow: 1,
                }
                .abi_encode()
                .into(),
            },
            IMulticall3::Call3 {
                target: pm,
                allowFailure: false,
                callData: PerpManager::fundingPerSecondX96Call { perpId: perp_id }
                    .abi_encode()
                    .into(),
            },
            IMulticall3::Call3 {
                target: pm,
                allowFailure: false,
                callData: PerpManager::takerOpenInterestCall { perpId: perp_id }
                    .abi_encode()
                    .into(),
            },
        ];

        let multicall = IMulticall3::new(MULTICALL3, &self.provider);
        let results = multicall.aggregate3(calls).call().await?;

        if results.len() != 4 {
            return Err(PerpCityError::Overflow {
                context: format!(
                    "perp snapshot multicall returned {} results, expected 4",
                    results.len()
                ),
            });
        }

        let call_names = [
            "cfgs",
            "timeWeightedAvgSqrtPriceX96",
            "fundingPerSecondX96",
            "takerOpenInterest",
        ];
        for (i, name) in call_names.iter().enumerate() {
            if !results[i].success {
                return Err(PerpCityError::Overflow {
                    context: format!("perp snapshot multicall: {name} call failed"),
                });
            }
        }

        // Decode cfgs
        let config = PerpManager::PerpConfig::abi_decode(&results[0].returnData).map_err(|e| {
            PerpCityError::Overflow {
                context: format!("failed to decode PerpConfig: {e}"),
            }
        })?;

        if config.beacon == Address::ZERO {
            return Err(PerpCityError::PerpNotFound { perp_id });
        }

        // Decode mark price
        let sqrt_price_x96 =
            U256::abi_decode(&results[1].returnData).map_err(|e| PerpCityError::Overflow {
                context: format!("failed to decode mark price: {e}"),
            })?;
        let mark = crate::convert::sqrt_price_x96_to_price(sqrt_price_x96)?;

        // Decode funding rate
        let funding_x96 =
            I256::abi_decode(&results[2].returnData).map_err(|e| PerpCityError::Overflow {
                context: format!("failed to decode funding rate: {e}"),
            })?;
        let funding_rate_daily = funding_x96_to_daily(funding_x96);

        // Decode OI — takerOpenInterest returns (uint128 longOI, uint128 shortOI)
        let (long_oi, short_oi) =
            <(u128, u128)>::abi_decode(&results[3].returnData).map_err(|e| {
                PerpCityError::Overflow {
                    context: format!("failed to decode open interest: {e}"),
                }
            })?;
        let open_interest = OpenInterest {
            long_oi: long_oi as f64 / SCALE_F64,
            short_oi: short_oi as f64 / SCALE_F64,
        };

        // Phase 2: fetch index price from beacon (1 CU)
        let index_price = self.get_index_price(config.beacon).await?;

        // Build PerpData (fetch fees/bounds from cache or chain)
        let fees = self.get_or_fetch_fees(&config).await?;
        let bounds = self.get_or_fetch_bounds(&config).await?;

        let perp_data = PerpData {
            id: perp_id,
            tick_spacing: i24_to_i32(config.key.tickSpacing),
            mark,
            beacon: config.beacon,
            bounds,
            fees,
        };

        let snapshot = PerpSnapshot {
            mark_price: mark,
            index_price,
            funding_rate_daily,
            open_interest,
        };

        tracing::debug!(%perp_id, "perp snapshot fetched via multicall");
        Ok((perp_data, snapshot))
    }

    // ── Accessors ────────────────────────────────────────────────────

    /// The signer's Ethereum address.
    pub fn address(&self) -> Address {
        self.address
    }

    /// The deployed contract addresses.
    pub fn deployments(&self) -> &Deployments {
        &self.deployments
    }

    /// The underlying Alloy provider (for advanced queries).
    pub fn provider(&self) -> &RootProvider<Ethereum> {
        &self.provider
    }

    /// The signing wallet (for building signed transactions outside the SDK).
    pub fn wallet(&self) -> &EthereumWallet {
        &self.wallet
    }

    /// The underlying HFT transport (for health diagnostics).
    pub fn transport(&self) -> &HftTransport {
        &self.transport
    }

    /// Invalidate the fast cache layer (prices, funding, balance).
    ///
    /// Call on new-block events to ensure fresh data.
    pub fn invalidate_fast_cache(&self) {
        let mut cache = self.state_cache.lock().unwrap();
        cache.invalidate_fast_layer();
    }

    /// Invalidate all cached state.
    pub fn invalidate_all_cache(&self) {
        let mut cache = self.state_cache.lock().unwrap();
        cache.invalidate_all();
    }

    /// Confirm a transaction as mined. Removes from in-flight tracking.
    pub fn confirm_tx(&self, tx_hash: &[u8; 32]) {
        let mut pipeline = self.pipeline.lock().unwrap();
        pipeline.confirm(tx_hash);
    }

    /// Mark a transaction as failed. Releases the nonce if possible.
    pub fn fail_tx(&self, tx_hash: &[u8; 32]) {
        let mut pipeline = self.pipeline.lock().unwrap();
        pipeline.fail(tx_hash);
    }

    /// Number of currently in-flight (unconfirmed) transactions.
    pub fn in_flight_count(&self) -> usize {
        let pipeline = self.pipeline.lock().unwrap();
        pipeline.in_flight_count()
    }

    // ── Internal helpers ─────────────────────────────────────────────

    // ── Transfer helpers ─────────────────────────────────────────────

    /// Transfer ETH to an address. Uses the transaction pipeline for
    /// correct nonce management.
    pub async fn transfer_eth(
        &self,
        to: Address,
        amount_wei: u128,
        urgency: Urgency,
    ) -> Result<B256> {
        tracing::info!(%to, amount_wei, ?urgency, "transferring ETH");
        let receipt = self
            .send_tx_with_value(
                to,
                Bytes::new(),
                amount_wei,
                Some(GasLimits::ETH_TRANSFER),
                urgency,
            )
            .await?;
        tracing::info!(tx_hash = %receipt.transaction_hash, "ETH transferred");
        Ok(receipt.transaction_hash)
    }

    /// Transfer USDC to an address. `amount` is in human units (e.g. 100.0 = 100 USDC).
    /// Uses the transaction pipeline for correct nonce management.
    pub async fn transfer_usdc(&self, to: Address, amount: f64, urgency: Urgency) -> Result<B256> {
        tracing::info!(%to, amount, ?urgency, "transferring USDC");
        let usdc = IERC20::new(self.deployments.usdc, &self.provider);
        let scaled = U256::from(scale_to_6dec(amount)? as u128);
        let calldata = usdc.transfer(to, scaled).calldata().clone();
        let receipt = self
            .send_tx(self.deployments.usdc, calldata, None, urgency)
            .await?;
        tracing::info!(tx_hash = %receipt.transaction_hash, "USDC transferred");
        Ok(receipt.transaction_hash)
    }

    // ── Internal helpers ─────────────────────────────────────────────

    /// Prepare, sign, send, and wait for a transaction receipt.
    ///
    /// If `gas_limit` is `None`, the gas limit is resolved from the
    /// estimate cache (keyed by 4-byte selector) or via `eth_estimateGas`.
    async fn send_tx(
        &self,
        to: Address,
        calldata: Bytes,
        gas_limit: Option<u64>,
        urgency: Urgency,
    ) -> Result<alloy::rpc::types::TransactionReceipt> {
        self.send_tx_with_value(to, calldata, 0, gas_limit, urgency)
            .await
    }

    /// Like `send_tx` but with an explicit ETH value to attach.
    async fn send_tx_with_value(
        &self,
        to: Address,
        calldata: Bytes,
        value: u128,
        gas_limit: Option<u64>,
        urgency: Urgency,
    ) -> Result<alloy::rpc::types::TransactionReceipt> {
        let now = now_ms();

        // Resolve gas limit: explicit override → cached estimate → eth_estimateGas
        let resolved_gas_limit = match gas_limit {
            Some(limit) => limit,
            None => self.resolve_gas_limit(to, &calldata, value, now).await?,
        };

        // Prepare via pipeline (zero RPC)
        let prepared = {
            let pipeline = self.pipeline.lock().unwrap();
            let fee_cache = self.fee_cache.lock().unwrap();
            pipeline.prepare(
                TxRequest {
                    to: to.into_array(),
                    calldata: calldata.to_vec(),
                    value,
                    gas_limit: resolved_gas_limit,
                    urgency,
                },
                &fee_cache,
                now,
            )?
        };

        tracing::debug!(
            nonce = prepared.nonce,
            gas_limit = prepared.gas_limit,
            max_fee = prepared.gas_fees.max_fee_per_gas,
            priority_fee = prepared.gas_fees.max_priority_fee_per_gas,
            %to,
            ?urgency,
            "tx prepared"
        );

        // Build EIP-1559 transaction
        let tx = TransactionRequest::default()
            .with_to(to)
            .with_input(calldata)
            .with_value(U256::from(prepared.request.value))
            .with_nonce(prepared.nonce)
            .with_gas_limit(prepared.gas_limit)
            .with_max_fee_per_gas(prepared.gas_fees.max_fee_per_gas as u128)
            .with_max_priority_fee_per_gas(prepared.gas_fees.max_priority_fee_per_gas as u128)
            .with_chain_id(self.chain_id);

        // Sign and send
        let tx_envelope = tx
            .build(&self.wallet)
            .await
            .map_err(|e| PerpCityError::TxReverted {
                reason: format!("failed to sign transaction: {e}"),
            })?;

        let pending = self.provider.send_tx_envelope(tx_envelope).await?;
        let tx_hash_b256 = *pending.tx_hash();
        let tx_hash_bytes: [u8; 32] = tx_hash_b256.into();

        tracing::info!(tx_hash = %tx_hash_b256, nonce = prepared.nonce, ?urgency, "tx broadcast");

        // Record in pipeline
        {
            let mut pipeline = self.pipeline.lock().unwrap();
            pipeline.record_submission(tx_hash_bytes, prepared, now);
        }

        // Wait for receipt
        let receipt = tokio::time::timeout(RECEIPT_TIMEOUT, pending.get_receipt())
            .await
            .map_err(|_| {
                tracing::warn!(tx_hash = %tx_hash_b256, timeout_secs = RECEIPT_TIMEOUT.as_secs(), "receipt timeout");
                PerpCityError::TxReverted {
                    reason: format!("receipt timeout after {}s", RECEIPT_TIMEOUT.as_secs()),
                }
            })?
            .map_err(|e| PerpCityError::TxReverted {
                reason: format!("failed to get receipt: {e}"),
            })?;

        // Confirm in pipeline
        {
            let mut pipeline = self.pipeline.lock().unwrap();
            pipeline.confirm(&tx_hash_bytes);
        }

        // Check if reverted
        if !receipt.status() {
            tracing::warn!(tx_hash = %tx_hash_b256, "tx reverted");
            return Err(PerpCityError::TxReverted {
                reason: format!("transaction {} reverted", tx_hash_b256),
            });
        }

        tracing::info!(
            tx_hash = %tx_hash_b256,
            block = ?receipt.block_number,
            gas_used = ?receipt.gas_used,
            "tx confirmed"
        );

        Ok(receipt)
    }

    /// Resolve gas limit from cache or via `eth_estimateGas`.
    ///
    /// Extracts the 4-byte function selector from calldata, checks the
    /// estimate cache, and falls back to an RPC call on cache miss.
    async fn resolve_gas_limit(
        &self,
        to: Address,
        calldata: &Bytes,
        value: u128,
        now: u64,
    ) -> Result<u64> {
        // Extract selector (first 4 bytes of calldata)
        if calldata.len() < 4 {
            return Err(PerpCityError::InvalidConfig {
                reason: "calldata too short to extract function selector".into(),
            });
        }
        let selector: [u8; 4] = calldata[..4].try_into().unwrap();

        // Check cache
        {
            let cache = self.gas_limit_cache.lock().unwrap();
            if let Some(limit) = cache.get(&selector, now) {
                tracing::trace!(selector = %alloy::primitives::hex::encode(selector), limit, "gas estimate cache hit");
                return Ok(limit);
            }
        }

        // Cache miss — call eth_estimateGas
        let tx = TransactionRequest::default()
            .with_from(self.address)
            .with_to(to)
            .with_input(calldata.clone())
            .with_value(U256::from(value));

        let raw_estimate = self.provider.estimate_gas(tx).await.map_err(|e| {
            PerpCityError::GasPriceUnavailable {
                reason: format!("eth_estimateGas failed: {e}"),
            }
        })?;

        // Cache with buffer
        {
            let mut cache = self.gas_limit_cache.lock().unwrap();
            cache.put(selector, raw_estimate, now);
        }

        let buffered = {
            let cache = self.gas_limit_cache.lock().unwrap();
            cache.get(&selector, now).unwrap()
        };

        tracing::debug!(
            selector = %alloy::primitives::hex::encode(selector),
            raw_estimate,
            buffered,
            "gas estimate cached"
        );

        Ok(buffered)
    }

    /// Get fees from cache or fetch from chain.
    async fn get_or_fetch_fees(&self, config: &PerpManager::PerpConfig) -> Result<Fees> {
        let now_ts = now_secs();
        let fees_addr: [u8; 20] = config.fees.into();

        let cached = {
            let cache = self.state_cache.lock().unwrap();
            cache.get_fees(&fees_addr, now_ts).cloned()
        };

        match cached {
            Some(cached) => Ok(Fees::from(cached)),
            None => {
                let fees = self.fetch_fees(config).await?;
                let mut cache = self.state_cache.lock().unwrap();
                cache.put_fees(fees_addr, CachedFees::from(fees), now_ts);
                Ok(fees)
            }
        }
    }

    /// Get bounds from cache or fetch from chain.
    async fn get_or_fetch_bounds(&self, config: &PerpManager::PerpConfig) -> Result<Bounds> {
        let now_ts = now_secs();
        let ratios_addr: [u8; 20] = config.marginRatios.into();

        let cached = {
            let cache = self.state_cache.lock().unwrap();
            cache.get_bounds(&ratios_addr, now_ts).cloned()
        };

        match cached {
            Some(cached) => Ok(Bounds::from(cached)),
            None => {
                let bounds = self.fetch_bounds(config).await?;
                let mut cache = self.state_cache.lock().unwrap();
                cache.put_bounds(ratios_addr, CachedBounds::from(bounds), now_ts);
                Ok(bounds)
            }
        }
    }

    /// Fetch fees from the IFees module contract.
    async fn fetch_fees(&self, config: &PerpManager::PerpConfig) -> Result<Fees> {
        if config.fees == Address::ZERO {
            return Err(PerpCityError::ModuleNotRegistered {
                module: "IFees".into(),
            });
        }

        let fees_contract = IFees::new(config.fees, &self.provider);

        let fee_result = fees_contract.fees(config.clone()).call().await?;
        let c_fee = u24_to_u32(fee_result.cFee);
        let ins_fee = u24_to_u32(fee_result.insFee);
        let lp_fee = u24_to_u32(fee_result.lpFee);

        let liq_result = fees_contract.liquidationFee(config.clone()).call().await?;
        let liq_fee = u24_to_u32(liq_result);

        let scale = SCALE_F64;
        Ok(Fees {
            creator_fee: c_fee as f64 / scale,
            insurance_fee: ins_fee as f64 / scale,
            lp_fee: lp_fee as f64 / scale,
            liquidation_fee: liq_fee as f64 / scale,
        })
    }

    /// Fetch margin ratio bounds from the IMarginRatios module contract.
    async fn fetch_bounds(&self, config: &PerpManager::PerpConfig) -> Result<Bounds> {
        if config.marginRatios == Address::ZERO {
            return Err(PerpCityError::ModuleNotRegistered {
                module: "IMarginRatios".into(),
            });
        }

        let ratios_contract = IMarginRatios::new(config.marginRatios, &self.provider);

        let ratios: IMarginRatios::MarginRatios = ratios_contract
            .marginRatios(config.clone(), false) // isMaker = false for taker bounds
            .call()
            .await?;

        let scale = SCALE_F64;
        Ok(Bounds {
            min_margin: scale_from_6dec(crate::constants::MIN_OPENING_MARGIN as i128),
            min_taker_leverage: margin_ratio_to_leverage(u24_to_u32(ratios.max))?,
            max_taker_leverage: margin_ratio_to_leverage(u24_to_u32(ratios.min))?,
            liquidation_taker_ratio: u24_to_u32(ratios.liq) as f64 / scale,
        })
    }
}

// ── Type conversion helpers for Alloy fixed-size types ───────────────

/// Convert a u32 margin ratio to Alloy's uint24 type.
#[inline]
fn u32_to_u24(v: u32) -> alloy::primitives::Uint<24, 1> {
    alloy::primitives::Uint::<24, 1>::from(v & 0xFF_FFFF)
}

/// Convert Alloy's uint24 to a u32.
#[inline]
fn u24_to_u32(v: alloy::primitives::Uint<24, 1>) -> u32 {
    v.to::<u32>()
}

/// Convert an i32 tick to Alloy's int24 type.
#[inline]
fn i32_to_i24(v: i32) -> alloy::primitives::Signed<24, 1> {
    alloy::primitives::Signed::<24, 1>::try_from(v as i64).unwrap_or(if v < 0 {
        alloy::primitives::Signed::<24, 1>::MIN
    } else {
        alloy::primitives::Signed::<24, 1>::MAX
    })
}

/// Convert Alloy's int24 to an i32.
#[inline]
fn i24_to_i32(v: alloy::primitives::Signed<24, 1>) -> i32 {
    // int24 always fits in i32
    v.as_i32()
}

// ── Utility functions ────────────────────────────────────────────────

/// Get current time in milliseconds.
fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Get current time in seconds (for state cache).
fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

/// Convert an I256 to i128 (clamping to i128::MIN/MAX on overflow).
#[inline]
fn i128_from_i256(v: I256) -> i128 {
    i128::try_from(v).unwrap_or_else(|_| {
        if v.is_negative() {
            i128::MIN
        } else {
            i128::MAX
        }
    })
}

/// Scale an unsigned `U256` from 6-decimal on-chain representation to `f64`.
fn u256_to_f64_6dec(v: U256) -> f64 {
    v.to::<u128>() as f64 / 1_000_000.0
}

/// Parse an [`OpenResult`] from a transaction receipt's `PositionOpened` event.
fn parse_open_result(receipt: &alloy::rpc::types::TransactionReceipt) -> Result<OpenResult> {
    for log in receipt.inner.logs() {
        if let Ok(event) = log.log_decode::<PerpManager::PositionOpened>() {
            let data = event.inner.data;
            let perp_delta = i128_from_i256(data.perpDelta);
            let usd_delta = i128_from_i256(data.usdDelta);
            return Ok(OpenResult {
                pos_id: data.posId,
                is_maker: data.isMaker,
                perp_delta: scale_from_6dec(perp_delta),
                usd_delta: scale_from_6dec(usd_delta),
                tick_lower: i24_to_i32(data.tickLower),
                tick_upper: i24_to_i32(data.tickUpper),
            });
        }
    }
    Err(PerpCityError::EventNotFound {
        event_name: "PositionOpened".into(),
    })
}

/// Parse an [`AdjustNotionalResult`] from a transaction receipt's `NotionalAdjusted` event.
fn parse_adjust_result(
    receipt: &alloy::rpc::types::TransactionReceipt,
) -> Result<AdjustNotionalResult> {
    for log in receipt.inner.logs() {
        if let Ok(event) = log.log_decode::<PerpManager::NotionalAdjusted>() {
            let data = event.inner.data;
            return Ok(AdjustNotionalResult {
                new_perp_delta: scale_from_6dec(i128_from_i256(data.newPerpDelta)),
                swap_perp_delta: scale_from_6dec(i128_from_i256(data.swapPerpDelta)),
                swap_usd_delta: scale_from_6dec(i128_from_i256(data.swapUsdDelta)),
                funding: scale_from_6dec(i128_from_i256(data.funding)),
                utilization_fee: u256_to_f64_6dec(data.utilizationFee),
                adl: u256_to_f64_6dec(data.adl),
                trading_fees: u256_to_f64_6dec(data.tradingFees),
            });
        }
    }
    Err(PerpCityError::EventNotFound {
        event_name: "NotionalAdjusted".into(),
    })
}

/// Parse an [`AdjustMarginResult`] from a transaction receipt's `MarginAdjusted` event.
fn parse_margin_result(
    receipt: &alloy::rpc::types::TransactionReceipt,
) -> Result<AdjustMarginResult> {
    for log in receipt.inner.logs() {
        if let Ok(event) = log.log_decode::<PerpManager::MarginAdjusted>() {
            return Ok(AdjustMarginResult {
                new_margin: u256_to_f64_6dec(event.inner.data.newMargin),
            });
        }
    }
    Err(PerpCityError::EventNotFound {
        event_name: "MarginAdjusted".into(),
    })
}

/// Parse a [`CloseResult`] from a transaction receipt's `PositionClosed` event.
fn parse_close_result(
    receipt: &alloy::rpc::types::TransactionReceipt,
    pos_id: U256,
) -> Result<CloseResult> {
    let tx_hash = receipt.transaction_hash;
    for log in receipt.inner.logs() {
        if let Ok(event) = log.log_decode::<PerpManager::PositionClosed>() {
            let data = event.inner.data;
            return Ok(CloseResult {
                tx_hash,
                was_maker: data.wasMaker,
                was_liquidated: data.wasLiquidated,
                remaining_position_id: if data.wasPartialClose {
                    Some(pos_id)
                } else {
                    None
                },
                exit_perp_delta: scale_from_6dec(i128_from_i256(data.exitPerpDelta)),
                exit_usd_delta: scale_from_6dec(i128_from_i256(data.exitUsdDelta)),
                net_usd_delta: scale_from_6dec(i128_from_i256(data.netUsdDelta)),
                funding: scale_from_6dec(i128_from_i256(data.funding)),
                utilization_fee: u256_to_f64_6dec(data.utilizationFee),
                adl: u256_to_f64_6dec(data.adl),
                liquidation_fee: u256_to_f64_6dec(data.liquidationFee),
                net_margin: scale_from_6dec(i128_from_i256(data.netMargin)),
            });
        }
    }
    Err(PerpCityError::EventNotFound {
        event_name: "PositionClosed".into(),
    })
}

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

    // ── i128_from_i256 tests ─────────────────────────────────────────

    #[test]
    fn i128_from_i256_small_values() {
        assert_eq!(i128_from_i256(I256::ZERO), 0);
        assert_eq!(i128_from_i256(I256::try_from(42i64).unwrap()), 42);
        assert_eq!(i128_from_i256(I256::try_from(-100i64).unwrap()), -100);
    }

    #[test]
    fn i128_from_i256_boundary_values() {
        let max_i128 = I256::try_from(i128::MAX).unwrap();
        assert_eq!(i128_from_i256(max_i128), i128::MAX);

        let min_i128 = I256::try_from(i128::MIN).unwrap();
        assert_eq!(i128_from_i256(min_i128), i128::MIN);
    }

    #[test]
    fn i128_from_i256_overflow_clamps() {
        assert_eq!(i128_from_i256(I256::MAX), i128::MAX);
        assert_eq!(i128_from_i256(I256::MIN), i128::MIN);
    }

    #[test]
    fn i128_from_i256_just_beyond_i128() {
        let beyond = I256::try_from(i128::MAX).unwrap() + I256::try_from(1i64).unwrap();
        assert_eq!(i128_from_i256(beyond), i128::MAX);

        let below = I256::try_from(i128::MIN).unwrap() - I256::try_from(1i64).unwrap();
        assert_eq!(i128_from_i256(below), i128::MIN);
    }

    // ── Type conversion helpers ──────────────────────────────────────

    #[test]
    fn u24_roundtrip() {
        for v in [0u32, 1, 100_000, 0xFF_FFFF] {
            let u24 = u32_to_u24(v);
            assert_eq!(u24_to_u32(u24), v);
        }
    }

    #[test]
    fn u24_truncates_overflow() {
        // Values > 0xFFFFFF get masked
        let u24 = u32_to_u24(0x1FF_FFFF);
        assert_eq!(u24_to_u32(u24), 0xFF_FFFF);
    }

    #[test]
    fn i24_roundtrip() {
        for v in [0i32, 1, -1, 30, -30, 69_090, -69_090] {
            let i24 = i32_to_i24(v);
            assert_eq!(i24_to_i32(i24), v);
        }
    }

    // ── Funding rate integration test ───────────────────────────────

    #[test]
    fn funding_rate_x96_conversion() {
        let q96 = 2.0_f64.powi(96);
        let rate_per_sec = 0.0001;
        let x96_value = (rate_per_sec * q96) as i128;
        let i256_val = I256::try_from(x96_value).unwrap();

        let recovered = i128_from_i256(i256_val) as f64 / q96;
        let daily = recovered * 86400.0;

        assert!((recovered - rate_per_sec).abs() < 1e-10);
        assert!((daily - 8.64).abs() < 0.001);
    }
}