hypersdk 0.2.8

Rust SDK for Hyperliquid
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
//! HyperCore L1 chain interactions.
//!
//! This module provides functionality for interacting with Hyperliquid's native L1 chain,
//! including trading operations, market data queries, and asset transfers.
//!
//! # Components
//!
//! - [`HttpClient`]: HTTP client for API interactions (orders, queries, transfers)
//! - [`WebSocket`]: Real-time WebSocket connection for market data and order updates
//! - Market types: [`PerpMarket`], [`SpotMarket`], [`SpotToken`]
//! - Order types and operations in the [`types`] module
//!
//! # Examples
//!
//! ## Query Markets
//!
//! ```no_run
//! use hypersdk::hypercore;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = hypercore::mainnet();
//!
//! // Get perpetual markets
//! let perps = client.perps().await?;
//! for market in perps {
//!     println!("{}: max leverage {}x", market.name, market.max_leverage);
//! }
//!
//! // Get spot markets
//! let spots = client.spot().await?;
//! for market in spots {
//!     println!("{}", market.symbol());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## WebSocket Market Data
//!
//! ```no_run
//! use hypersdk::hypercore::{self, types::*, ws::Event};
//! use futures::StreamExt;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let mut ws = hypercore::mainnet_ws();
//!
//! // Subscribe to trades and order book
//! ws.subscribe(Subscription::Trades { coin: "BTC".into() });
//! ws.subscribe(Subscription::L2Book { coin: "BTC".into() });
//!
//! while let Some(event) = ws.next().await {
//!     let Event::Message(msg) = event else { continue };
//!     match msg {
//!         Incoming::Trades(trades) => {
//!             for trade in trades {
//!                 println!("{} @ {} size {}", trade.side, trade.px, trade.sz);
//!             }
//!         }
//!         Incoming::L2Book(book) => {
//!             println!("Book update for {}", book.coin);
//!         }
//!         _ => {}
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Place Orders
//!
//! ```no_run
//! use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = hypercore::mainnet();
//! let signer: PrivateKeySigner = "your_private_key".parse()?;
//!
//! // Example order placement - requires dec!() macro and timestamp
//! // See the crate documentation for complete examples
//! # Ok(())
//! # }
//! ```

pub mod error;
pub mod http;
pub mod signing;
pub mod types;
mod utils;
pub mod ws;

use std::{
    fmt,
    hash::Hash,
    sync::atomic::{self, AtomicU64},
};

/// Reimport signers.
pub use alloy::signers::local::PrivateKeySigner;
use alloy::{
    dyn_abi::Eip712Domain,
    primitives::{B128, U256, address},
};
use anyhow::Context;
use chrono::Utc;
use either::Either;
/// Re-export error types.
pub use error::{ActionError, Error};
use reqwest::IntoUrl;
use rust_decimal::{Decimal, MathematicalOps, RoundingStrategy, prelude::ToPrimitive};
use serde::{Deserialize, Serialize};
/// Re-import types.
pub use types::*;
use url::Url;

use crate::{
    Address,
    hyperevm::{from_wei, to_wei},
};

/// Client order ID (cloid).
///
/// A 128-bit identifier that clients can assign to their orders for tracking purposes.
/// This allows you to reference orders by your own ID instead of the exchange-assigned order ID.
pub type Cloid = B128;

/// Order identifier that can be either an exchange-assigned order ID or a client order ID.
///
/// - `Left(u64)`: Exchange-assigned order ID (oid)
/// - `Right(Cloid)`: Client-assigned order ID (cloid)
pub type OidOrCloid = Either<u64, Cloid>;

/// Re-export of the HTTP client for HyperCore API interactions.
///
/// Use this client for placing orders, querying balances, and managing positions.
pub use http::Client as HttpClient;
/// Re-export of the WebSocket connection for real-time market data.
///
/// Use this for subscribing to trades, order books, and order updates.
pub use ws::Connection as WebSocket;

/// Thread-safe nonce generator for Hyperliquid transactions.
///
/// Hyperliquid requires each transaction to have a unique, monotonically increasing nonce
/// to prevent replay attacks. This handler generates nonces based on the current timestamp
/// in milliseconds, ensuring uniqueness even under high-frequency trading scenarios.
///
/// # Thread Safety
///
/// This struct uses atomic operations and is safe to share across threads. Multiple threads
/// can call `next()` concurrently without external synchronization.
///
/// # Nonce Generation Strategy
///
/// 1. Starts with the current timestamp in milliseconds
/// 2. Increments by 1 for each subsequent call
/// 3. If the nonce falls behind the current time by more than 300ms, jumps to current time
/// 4. This ensures nonces stay close to real time while maintaining uniqueness
///
/// # Example
///
/// ```
/// use hypersdk::hypercore::NonceHandler;
///
/// let handler = NonceHandler::default();
///
/// // Generate sequential nonces
/// let nonce1 = handler.next();
/// let nonce2 = handler.next();
/// assert!(nonce2 > nonce1);
///
/// // Nonces are always unique and increasing
/// for _ in 0..1000 {
///     let n = handler.next();
///     assert!(n > nonce1);
/// }
/// ```
///
/// # Use with HTTP Client
///
/// ```no_run
/// use hypersdk::hypercore::{self, NonceHandler};
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let nonce_handler = NonceHandler::default();
///
/// // Use for multiple transactions
/// let nonce1 = nonce_handler.next();
/// let nonce2 = nonce_handler.next();
/// # Ok(())
/// # }
/// ```
pub struct NonceHandler {
    nonce: AtomicU64,
}

impl Default for NonceHandler {
    fn default() -> Self {
        let now = Utc::now().timestamp_millis() as u64;
        Self {
            nonce: AtomicU64::new(now),
        }
    }
}

impl NonceHandler {
    /// Generates the next unique nonce for a transaction.
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    /// It guarantees that:
    /// - Each returned nonce is unique
    /// - Nonces are monotonically increasing
    /// - Nonces stay reasonably close to the current timestamp
    ///
    /// # Algorithm
    ///
    /// 1. Gets the current time in milliseconds
    /// 2. Atomically increments the internal nonce counter
    /// 3. If the counter has fallen behind current time by >300ms, resets to current time
    /// 4. Otherwise returns the incremented counter value
    ///
    /// # Returns
    ///
    /// A unique nonce suitable for use in Hyperliquid transactions.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use hypersdk::hypercore::NonceHandler;
    ///
    /// let handler = Arc::new(NonceHandler::default());
    /// let nonce = handler.next();
    /// println!("Transaction nonce: {}", nonce);
    /// ```
    pub fn next(&self) -> u64 {
        let now = Utc::now().timestamp_millis() as u64;

        let prev = self.nonce.load(atomic::Ordering::Relaxed);
        if prev + 300 < now {
            self.nonce.fetch_max(now, atomic::Ordering::Relaxed);
        }

        self.nonce.fetch_add(1, atomic::Ordering::Relaxed)
    }
}

/// Chain identifier for Hyperliquid operations.
///
/// This determines which network-specific constants to use for signatures and operations.
///
/// # Serialization
///
/// Serializes to PascalCase format: "Mainnet" or "Testnet".
/// This format is required by the Hyperliquid API.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    derive_more::Display,
    derive_more::FromStr,
    derive_more::IsVariant,
)]
#[serde(rename_all = "PascalCase")]
pub enum Chain {
    /// Mainnet chain
    #[display("Mainnet")]
    Mainnet,
    /// Testnet chain
    #[display("Testnet")]
    Testnet,
}

impl Chain {
    /// Returns the Arbitrum chain ID for EIP-712 signatures based on the chain.
    ///
    /// This method returns the appropriate Arbitrum chain ID to use in EIP-712 signature
    /// domains for actions like USDC transfers, spot sends, and asset transfers.
    ///
    /// # Returns
    ///
    /// - Mainnet: `"0xa4b1"` (Arbitrum One mainnet chain ID)
    /// - Testnet: `"0x66eee"` (Hyperliquid testnet chain ID)
    ///
    /// # Example
    ///
    /// ```rust
    /// use hypersdk::hypercore::Chain;
    ///
    /// let mainnet = Chain::Mainnet;
    /// assert_eq!(mainnet.arbitrum_id(), "0xa4b1");
    ///
    /// let testnet = Chain::Testnet;
    /// assert_eq!(testnet.arbitrum_id(), "0x66eee");
    /// ```
    pub fn arbitrum_id(&self) -> &'static str {
        if self.is_mainnet() {
            ARBITRUM_MAINNET_CHAIN_ID
        } else {
            ARBITRUM_TESTNET_CHAIN_ID
        }
    }

    /// Returns the EIP-712 domain for this chain.
    ///
    /// The domain is used for EIP-712 typed data signatures in cross-chain operations.
    /// Returns the appropriate domain based on whether this is mainnet or testnet.
    ///
    /// # Returns
    ///
    /// - [`ARBITRUM_MAINNET_EIP712_DOMAIN`] for mainnet chains
    /// - [`ARBITRUM_TESTNET_EIP712_DOMAIN`] for testnet chains
    ///
    /// # Example
    ///
    /// ```rust
    /// use hypersdk::hypercore::Chain;
    ///
    /// let mainnet_domain = Chain::Mainnet.domain();
    /// let testnet_domain = Chain::Testnet.domain();
    /// ```
    pub fn domain(&self) -> Eip712Domain {
        if self.is_mainnet() {
            ARBITRUM_MAINNET_EIP712_DOMAIN
        } else {
            ARBITRUM_TESTNET_EIP712_DOMAIN
        }
    }
}

/// Arbitrum One mainnet chain ID for EIP-712 signatures.
///
/// This chain ID is used in EIP-712 signature domains for cross-chain operations
/// involving Arbitrum, such as:
/// - USDC transfers between HyperCore and Arbitrum
/// - Spot token transfers
/// - Asset transfers to/from HyperEVM
///
/// # Value
///
/// `0xa4b1` - The standard Arbitrum One mainnet chain ID (decimal: 42161)
///
/// # Usage
///
/// This constant should be used as the `signature_chain_id` field when creating
/// actions like `UsdSend`, `SpotSend`, or `SendAsset` on mainnet.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{ARBITRUM_MAINNET_CHAIN_ID, types::UsdSend, Chain};
///
/// // Example UsdSend construction - requires dec!() macro
/// // let usd_send = UsdSend { ... };
/// ```
///
/// # See Also
///
/// - [`ARBITRUM_TESTNET_CHAIN_ID`]: For testnet operations
/// - [`Chain::arbitrum_id()`]: Helper method to get the correct ID based on chain
pub const ARBITRUM_MAINNET_CHAIN_ID: &str = "0xa4b1";

/// Hyperliquid testnet chain ID for EIP-712 signatures.
///
/// This chain ID is used in EIP-712 signature domains for testnet operations
/// involving asset transfers and cross-chain operations on Hyperliquid testnet.
///
/// # Value
///
/// `0x66eee` - The Hyperliquid testnet chain ID (decimal: 421614)
///
/// # Important Notes
///
/// - This is **not** the Arbitrum testnet chain ID
/// - This is Hyperliquid's custom chain ID for testnet operations
/// - Also used for multisig operations on both mainnet and testnet
///
/// # Usage
///
/// This constant should be used as the `signature_chain_id` field when creating
/// actions like `UsdSend`, `SpotSend`, or `SendAsset` on testnet.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{ARBITRUM_TESTNET_CHAIN_ID, types::UsdSend, Chain};
///
/// // Example UsdSend construction - requires dec!() macro
/// // let usd_send = UsdSend { ... };
/// ```
///
/// # See Also
///
/// - [`ARBITRUM_MAINNET_CHAIN_ID`]: For mainnet operations
/// - [`Chain::arbitrum_id()`]: Helper method to get the correct ID based on chain
pub const ARBITRUM_TESTNET_CHAIN_ID: &str = "0x66eee";

/// USDC contract address on HyperEVM.
///
/// Note: This address differs from the one linked in HyperCore documentation.
/// Use this address when interacting with USDC on HyperEVM.
pub const USDC_CONTRACT_IN_EVM: Address = address!("0xb88339CB7199b77E23DB6E890353E22632Ba630f");

/// Creates a mainnet HTTP client for HyperCore.
///
/// This is a convenience function that creates a client pointing to the default mainnet API.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore;
///
/// let client = hypercore::mainnet();
/// ```
#[inline(always)]
pub fn mainnet() -> HttpClient {
    HttpClient::new(Chain::Mainnet)
}

/// Creates a testnet HTTP client for HyperCore.
///
/// This is a convenience function that creates a client pointing to the default testnet API.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore;
///
/// let client = hypercore::testnet();
/// ```
#[inline(always)]
pub fn testnet() -> HttpClient {
    HttpClient::new(Chain::Testnet)
}

/// Creates a mainnet WebSocket connection for HyperCore.
///
/// This is a convenience function that creates a WebSocket connection to the mainnet API.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore;
/// use futures::StreamExt;
///
/// # async fn example() {
/// let mut ws = hypercore::mainnet_ws();
/// // Subscribe to market data
/// # }
/// ```
#[inline(always)]
pub fn mainnet_ws() -> WebSocket {
    WebSocket::new(mainnet_websocket_url())
}

/// Returns the default mainnet HTTP API URL.
///
/// URL: `https://api.hyperliquid.xyz`
#[inline(always)]
pub fn mainnet_url() -> Url {
    "https://api.hyperliquid.xyz".parse().unwrap()
}

/// Returns the default mainnet WebSocket URL.
///
/// URL: `wss://api.hyperliquid.xyz/ws`
#[inline(always)]
pub fn mainnet_websocket_url() -> Url {
    "wss://api.hyperliquid.xyz/ws".parse().unwrap()
}

/// Returns the default testnet HTTP API URL.
///
/// URL: `https://api.hyperliquid-testnet.xyz`
#[inline(always)]
pub fn testnet_url() -> Url {
    "https://api.hyperliquid-testnet.xyz".parse().unwrap()
}

/// Returns the default testnet WebSocket URL.
///
/// URL: `wss://api.hyperliquid-testnet.xyz/ws`
#[inline(always)]
pub fn testnet_websocket_url() -> Url {
    "wss://api.hyperliquid-testnet.xyz/ws".parse().unwrap()
}

/// Creates a testnet WebSocket connection for HyperCore.
///
/// This is a convenience function that creates a WebSocket connection to the testnet API.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore;
/// use futures::StreamExt;
///
/// # async fn example() {
/// let mut ws = hypercore::testnet_ws();
/// // Subscribe to market data
/// # }
/// ```
#[inline(always)]
pub fn testnet_ws() -> WebSocket {
    WebSocket::new(testnet_websocket_url())
}

/// Price tick configuration for determining valid price increments.
///
/// Hyperliquid enforces different tick size constraints for spot and perpetual markets.
/// This struct provides O(1) tick size calculation using a unified significant figures algorithm.
///
/// # Algorithm
///
/// The tick size is calculated to maintain **5 significant figures** while respecting
/// market-specific decimal constraints:
///
/// ```text
/// sig_figs = floor(log10(price)) + 1        // Number of integer digits
/// decimals = 5 - sig_figs                    // Decimal places needed for 5 sig figs
/// max_decimals = clamp(decimals, 0, max_decimals)
/// tick = 10^(-max_decimals)
/// ```
///
/// # Market Types
///
/// ## Spot Markets
/// - **Max decimals**: 8 (max_decimals = 8 - sz_decimals)
/// - Higher `max_decimals` allows finer tick sizes for low-priced assets
/// - Example: PURR/USDC with sz_decimals=0 → max_decimals=8 → tick can be as fine as 10^-8
///
/// ## Perpetual Markets
/// - **Max decimals**: 6 (max_decimals = 6 - sz_decimals)
/// - BTC (sz_decimals=5): max_decimals=1, allows up to 1 decimal place
/// - SOL (sz_decimals=2): max_decimals=4, allows up to 4 decimal places
///
/// # Examples
///
/// ```text
/// BTC perpetual (sz_decimals=5, max_decimals=1):
/// - Price 93231 (5 digits): decimals = 5-5 = 0, clamp(0,0,1) = 0 → tick = 10^0 = 1
/// - Price 93231.23 rounds to 93231
///
/// SOL perpetual (sz_decimals=2, max_decimals=4):
/// - Price 137 (3 digits): decimals = 5-3 = 2, clamp(2,0,4) = 2 → tick = 10^-2 = 0.01
/// - Price 137.23025 rounds to 137.23
///
/// - Price 99 (2 digits): decimals = 5-2 = 3, clamp(3,0,4) = 3 → tick = 10^-3 = 0.001
/// - Price 99.98241 rounds to 99.982
/// ```
///
/// See: <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size>
#[derive(Debug, Clone, Copy)]
pub struct PriceTick {
    /// Maximum decimal places allowed for this market.
    /// - Spot: max_decimals = 8 - sz_decimals
    /// - Perp: max_decimals = 6 - sz_decimals
    max_decimals: i64,
}

impl PriceTick {
    /// Creates a price tick configuration for a spot market.
    ///
    /// For spot markets, max decimal places is 8.
    /// Uses: max_decimals = 8 - sz_decimals
    ///
    /// See: <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size>
    pub fn for_spot(sz_decimals: i64) -> Self {
        Self {
            max_decimals: 8 - sz_decimals,
        }
    }

    /// Creates a price tick configuration for a perpetual market.
    ///
    /// For perps, the max significant figures is 5 and max decimal places is 6.
    /// Uses: max_decimals = 6 - sz_decimals
    ///
    /// See: <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size>
    pub fn for_perp(sz_decimals: i64) -> Self {
        Self {
            max_decimals: 6 - sz_decimals,
        }
    }

    /// Returns the valid tick size for a given price.
    ///
    /// The tick size determines the minimum price increment for orders at this price level.
    /// This implementation maintains 5 significant figures while respecting market-specific
    /// decimal constraints.
    ///
    /// Returns `None` if the price is invalid (zero, negative, or causes calculation overflow).
    ///
    /// # Algorithm
    ///
    /// 1. Calculate number of integer digits: `sig_figs = floor(log10(price)) + 1`
    /// 2. Calculate decimals needed for 5 sig figs: `decimals = 5 - sig_figs`
    /// 3. Clamp to market limits: `max_decimals = clamp(decimals, 0, max_decimals)`
    /// 4. Return tick size: `tick = 10^(-max_decimals)`
    ///
    /// # Examples
    ///
    /// Example: tick_for() calculates tick size based on price.
    /// See the PriceTick documentation for calculation details.
    pub fn tick_for(&self, price: Decimal) -> Option<Decimal> {
        let sig_figs = price.log10();
        let sig_figs_n = sig_figs.ceil().to_i32()? as i64;
        let decimals = 5_i64 - sig_figs_n;
        let max_decimals = decimals.clamp(0, self.max_decimals);
        Some(Decimal::TEN.powi(-max_decimals))
    }

    /// Rounds a price to the nearest valid tick.
    ///
    /// Returns `None` if the price is invalid or cannot be rounded.
    ///
    /// # Example
    ///
    /// Example: round() rounds price to nearest valid tick.
    /// See the PriceTick documentation for rounding details.
    pub fn round(&self, price: Decimal) -> Option<Decimal> {
        let tick = self.tick_for(price)?;
        // Use MidpointTowardZero strategy (round half dow)
        let rounded =
            (price / tick).round_dp_with_strategy(0, RoundingStrategy::MidpointTowardZero) * tick;
        Some(rounded)
    }

    /// Rounds a price to the nearest valid tick based on order side and aggressiveness.
    ///
    /// This method provides directional rounding control to optimize order placement strategy.
    /// Unlike the neutral [`round`](Self::round) method, this allows you to specify whether
    /// you want conservative (safer) or aggressive (more likely to fill) pricing.
    ///
    /// # Parameters
    ///
    /// - `side`: The order side ([`Side::Bid`] for buy orders, [`Side::Ask`] for sell orders)
    /// - `price`: The price to round to a valid tick
    /// - `conservative`: Rounding strategy flag
    ///   - `true`: Conservative rounding (safer for maker, less likely to fill immediately)
    ///   - `false`: Aggressive rounding (favors taker, more likely to fill immediately)
    ///
    /// # Rounding Behavior
    ///
    /// The rounding direction depends on both the order side and the conservative flag:
    ///
    /// | Side | Conservative | Direction | Rationale |
    /// |------|-------------|-----------|-----------|
    /// | Ask (Sell) | `true` | **UP** | Higher sell price → safer for seller, less likely to fill |
    /// | Ask (Sell) | `false` | **DOWN** | Lower sell price → more competitive, more likely to fill |
    /// | Bid (Buy) | `true` | **DOWN** | Lower buy price → safer for buyer, less likely to fill |
    /// | Bid (Buy) | `false` | **UP** | Higher buy price → more competitive, more likely to fill |
    ///
    /// # Use Cases
    ///
    /// **Conservative (Maker Strategy)**
    /// - Use when placing limit orders away from the market price
    /// - Prioritizes better execution price over fill likelihood
    /// - Suitable for market making or accumulating positions over time
    ///
    /// **Aggressive (Taker Strategy)**
    /// - Use when you want orders to fill quickly
    /// - Prioritizes execution certainty over price optimization
    /// - Suitable for closing positions urgently or market taking
    ///
    /// # Returns
    ///
    /// - `Some(Decimal)`: The rounded price at a valid tick
    /// - `None`: If the price is invalid (zero, negative, or causes overflow)
    ///
    /// # Examples
    ///
    /// Example: round_by_side() provides directional rounding.
    /// Conservative rounding favors better price, aggressive favors faster fill.
    /// See the PriceTick documentation for rounding strategy details.
    ///
    /// # See Also
    ///
    /// - [`round`](Self::round): Neutral rounding (midpoint toward zero)
    /// - [`tick_for`](Self::tick_for): Get the tick size for a given price
    pub fn round_by_side(&self, side: Side, price: Decimal, conservative: bool) -> Option<Decimal> {
        let tick = self.tick_for(price)?;
        let strategy = match (side, conservative) {
            (Side::Ask, true) | (Side::Bid, false) => {
                // Round up: higher price for asks (safer), higher price for bids (aggressive)
                RoundingStrategy::ToPositiveInfinity
            }
            (Side::Ask, false) | (Side::Bid, true) => {
                // Round down: lower price for asks (aggressive), lower price for bids (safer)
                RoundingStrategy::ToNegativeInfinity
            }
        };
        let rounded = price.round_dp_with_strategy(tick.scale(), strategy);
        Some(rounded)
    }
}

/// Perpetual futures contract market.
///
/// Represents a perpetual (non-expiring) futures contract on Hyperliquid.
/// Perpetual contracts allow traders to speculate on price movements with leverage.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let perps = client.perps().await?;
///
/// for market in perps {
///     println!("{}: {}x leverage, {} collateral",
///         market.name, market.max_leverage, market.collateral.name);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct PerpMarket {
    /// Market name (e.g., "BTC", "ETH", "xyz:EURC")
    pub name: String,
    /// Market index used in API calls
    pub index: usize,
    /// Number of decimal places supported for sizes
    pub sz_decimals: i64,
    /// Collateral token used for this market (typically USDC)
    pub collateral: SpotToken,
    /// Maximum allowed leverage for this market
    pub max_leverage: u64,
    /// Whether margin is isolated
    pub isolated_margin: bool,
    /// Margin mode for this market
    pub margin_mode: Option<MarginMode>,
    /// Whether growth mode is enabled for this market
    pub growth_mode: bool,
    /// Whether the quote token is aligned for this market
    pub aligned_quote_token: bool,
    /// Price tick configuration for valid price increments
    pub table: PriceTick,
}

impl PerpMarket {
    /// Returns the market symbol (same as name for perps).
    #[must_use]
    pub fn symbol(&self) -> &str {
        &self.name
    }

    /// Returns the price tick configuration for this market.
    #[must_use]
    pub fn tick_table(&self) -> &PriceTick {
        &self.table
    }

    /// Returns the tick size for a given price in this market.
    ///
    /// See [`PriceTick::tick_for`] for details on the calculation.
    pub fn tick_for(&self, price: Decimal) -> Option<Decimal> {
        self.table.tick_for(price)
    }

    /// Rounds a price to the nearest valid tick for this market.
    ///
    /// Uses midpoint-toward-zero rounding strategy (round half down).
    ///
    /// Returns `None` if the price is invalid.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use hypersdk::hypercore::PerpMarket;
    /// # let market: PerpMarket = unimplemented!();
    /// // Example: round_price() rounds to nearest valid tick
    /// // let rounded = market.round_price(price);
    /// ```
    pub fn round_price(&self, price: Decimal) -> Option<Decimal> {
        self.table.round(price)
    }

    /// Rounds a price based on order side and trading strategy.
    ///
    /// This method provides directional rounding to optimize order placement. Use conservative
    /// rounding for limit orders (better price, less likely to fill) or aggressive rounding
    /// for market-taking orders (worse price, more likely to fill).
    ///
    /// # Parameters
    ///
    /// - `side`: Order side ([`Side::Bid`] for buy, [`Side::Ask`] for sell)
    /// - `price`: The price to round
    /// - `conservative`: Rounding strategy
    ///   - `true`: Conservative (maker strategy, better price)
    ///   - `false`: Aggressive (taker strategy, faster fill)
    ///
    /// # Rounding Direction
    ///
    /// | Side | Conservative | Direction | Use Case |
    /// |------|-------------|-----------|----------|
    /// | Ask | `true` | UP | Limit sell away from market |
    /// | Ask | `false` | DOWN | Aggressive sell / market take |
    /// | Bid | `true` | DOWN | Limit buy away from market |
    /// | Bid | `false` | UP | Aggressive buy / market take |
    ///
    /// # Returns
    ///
    /// - `Some(Decimal)`: Rounded price at a valid tick
    /// - `None`: If price is invalid
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use hypersdk::hypercore::{PerpMarket, types::Side};
    /// # let market: PerpMarket = unimplemented!();
    /// // Example: round_by_side() provides directional rounding
    /// // let ask = market.round_by_side(Side::Ask, price, true);
    /// // let bid = market.round_by_side(Side::Bid, price, false);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`PriceTick::round_by_side`]: Detailed explanation of rounding logic
    /// - [`round_price`](Self::round_price): Neutral rounding
    pub fn round_by_side(&self, side: Side, price: Decimal, conservative: bool) -> Option<Decimal> {
        self.table.round_by_side(side, price, conservative)
    }
}

/// Spot market trading pair.
///
/// Represents a spot market where two tokens can be directly exchanged.
/// Each market consists of a base token and a quote token.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let spots = client.spot().await?;
///
/// for market in spots {
///     println!("{}: {} / {}",
///         market.name, market.tokens[0].name, market.tokens[1].name);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct SpotMarket {
    /// Market name (e.g., "PURR/USDC", "@123")
    pub name: String,
    /// Market index used in API calls (10_000 + spot index)
    pub index: usize,
    /// Base token (first element) and quote token (second element)
    pub tokens: [SpotToken; 2],
    /// Price tick configuration for valid price increments
    pub table: PriceTick,
}

impl SpotMarket {
    /// Returns the trading symbol in "BASE/QUOTE" format.
    #[must_use]
    pub fn symbol(&self) -> String {
        format!("{}/{}", self.tokens[0].name, self.tokens[1].name)
    }

    /// Returns the base token (first token in the pair).
    #[must_use]
    pub fn base(&self) -> &SpotToken {
        &self.tokens[0]
    }

    /// Returns the quote token (second token in the pair).
    #[must_use]
    pub fn quote(&self) -> &SpotToken {
        &self.tokens[1]
    }

    /// Returns the price tick configuration for this market.
    #[must_use]
    pub fn tick_table(&self) -> &PriceTick {
        &self.table
    }

    /// Returns the tick size for a given price in this market.
    ///
    /// See [`PriceTick::tick_for`] for details on the calculation.
    pub fn tick_for(&self, price: Decimal) -> Option<Decimal> {
        self.table.tick_for(price)
    }

    /// Rounds a price to the nearest valid tick for this market.
    ///
    /// Uses midpoint-toward-zero rounding strategy (round half down).
    ///
    /// Returns `None` if the price is invalid.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use hypersdk::hypercore::SpotMarket;
    /// # let market: SpotMarket = unimplemented!();
    /// // Example: round_price() rounds to nearest valid tick
    /// // let rounded = market.round_price(price);
    /// ```
    pub fn round_price(&self, price: Decimal) -> Option<Decimal> {
        self.table.round(price)
    }

    /// Rounds a price based on order side and trading strategy.
    ///
    /// This method provides directional rounding to optimize order placement. Use conservative
    /// rounding for limit orders (better price, less likely to fill) or aggressive rounding
    /// for market-taking orders (worse price, more likely to fill).
    ///
    /// # Parameters
    ///
    /// - `side`: Order side ([`Side::Bid`] for buy, [`Side::Ask`] for sell)
    /// - `price`: The price to round
    /// - `conservative`: Rounding strategy
    ///   - `true`: Conservative (maker strategy, better price)
    ///   - `false`: Aggressive (taker strategy, faster fill)
    ///
    /// # Rounding Direction
    ///
    /// | Side | Conservative | Direction | Use Case |
    /// |------|-------------|-----------|----------|
    /// | Ask | `true` | UP | Limit sell away from market |
    /// | Ask | `false` | DOWN | Aggressive sell / market take |
    /// | Bid | `true` | DOWN | Limit buy away from market |
    /// | Bid | `false` | UP | Aggressive buy / market take |
    ///
    /// # Returns
    ///
    /// - `Some(Decimal)`: Rounded price at a valid tick
    /// - `None`: If price is invalid
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use hypersdk::hypercore::{SpotMarket, types::Side};
    /// # let market: SpotMarket = unimplemented!();
    /// // Example: round_by_side() provides directional rounding
    /// // let ask = market.round_by_side(Side::Ask, price, true);
    /// // let bid = market.round_by_side(Side::Bid, price, false);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`PriceTick::round_by_side`]: Detailed explanation of rounding logic
    /// - [`round_price`](Self::round_price): Neutral rounding
    pub fn round_by_side(&self, side: Side, price: Decimal, conservative: bool) -> Option<Decimal> {
        self.table.round_by_side(side, price, conservative)
    }
}

impl PartialEq for SpotMarket {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl Eq for SpotMarket {}

#[cfg(test)]
mod tick_tests {
    use rust_decimal::dec;

    use super::*;

    #[test]
    fn test_perp() {
        let prices = vec![
            (5, dec!(93231.23), dec!(1), dec!(93231)),
            (5, dec!(108_234.23), dec!(1), dec!(108_234)),
            (2, dec!(137.23025), dec!(0.01), dec!(137.23)),
            (2, dec!(99.98241), dec!(0.001), dec!(99.982)),
            (0, dec!(0.001234), dec!(0.000001), dec!(0.001234)),
            (0, dec!(0.051618), dec!(0.000001), dec!(0.051618)),
            (0, dec!(0.000829), dec!(0.000001), dec!(0.000829)),
        ];

        for (sz_decimals, price, expected_tick, expected_price) in prices {
            let table = PriceTick::for_perp(sz_decimals);
            let tick = table.tick_for(price);
            assert_eq!(
                tick,
                Some(expected_tick),
                "${}: expected tick {}, got {:?}",
                price,
                expected_tick,
                tick
            );

            let output_price = table.round(price).unwrap();
            assert_eq!(
                expected_price, output_price,
                "${}: expected price {}, got {}",
                price, expected_price, output_price
            );
        }
    }

    #[test]
    fn test_spot() {
        let prices = vec![
            (5, dec!(93231.23), dec!(1), dec!(93231)),
            (5, dec!(108_234.23), dec!(1), dec!(108_234)),
            (2, dec!(137.23025), dec!(0.01), dec!(137.23)),
            (2, dec!(99.98241), dec!(0.001), dec!(99.982)),
            (0, dec!(0.0000003315), dec!(0.00000001), dec!(0.00000033)),
            (2, dec!(0.00001501), dec!(0.000001), dec!(0.000015)),
            (0, dec!(0.9543309), dec!(0.00001), dec!(0.95433)),
            (2, dec!(15.9715981), dec!(0.001), dec!(15.972)),
        ];

        for (sz_decimals, price, expected_tick, expected_price) in prices {
            let table = PriceTick::for_spot(sz_decimals);
            let tick = table.tick_for(price);
            assert_eq!(
                tick,
                Some(expected_tick),
                "${}: expected tick {}, got {:?}",
                price,
                expected_tick,
                tick
            );

            let output_price = table.round(price).unwrap();
            assert_eq!(
                expected_price, output_price,
                "${}: expected price {}, got {}",
                price, expected_price, output_price
            );
        }
    }
}

/// Spot token on HyperCore.
///
/// Represents a token that can be traded on Hyperliquid's spot markets.
/// Tokens may be bridgeable to HyperEVM if they have an EVM contract address.
///
/// # EVM Bridging
///
/// Tokens with `evm_contract` set can be transferred between HyperCore and HyperEVM:
/// - Use `cross_chain_address` as the destination when transferring to EVM
/// - Use the HTTP client's `transfer_to_evm` and `transfer_from_evm` methods
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let tokens = client.spot_tokens().await?;
///
/// for token in tokens {
///     if token.is_evm_linked() {
///         println!("{} is bridgeable to EVM at {:?}", token.name, token.evm_contract);
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpotToken {
    /// Token name (e.g., "USDC", "BTC", "PURR")
    pub name: String,
    /// Token index in the spot token array
    pub index: u32,
    /// Unique token identifier in HyperCore
    pub token_id: B128,
    /// EVM contract address if the token is bridgeable
    ///
    /// `None` means the token only exists on HyperCore.
    pub evm_contract: Option<Address>,
    /// Cross-chain transfer address for bridging between HyperCore and HyperEVM.
    ///
    /// Use this address as the destination when transferring from Core to EVM.
    ///
    /// **Special case:** HYPE token has no `evm_contract` but has this field set.
    pub cross_chain_address: Option<Address>,
    /// Number of decimal places for sizes in HyperCore
    pub sz_decimals: i64,
    /// Number of decimal places used for wei representation
    pub wei_decimals: i64,
    /// Additional decimal places when represented on EVM.
    ///
    /// Total EVM decimals = `sz_decimals` + `evm_extra_decimals`.
    pub evm_extra_decimals: i64,
}

impl SpotToken {
    /// Converts a decimal amount to wei representation.
    ///
    /// Uses the token's total decimals (wei_decimals + evm_extra_decimals).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use hypersdk::hypercore::SpotToken;
    /// # let token: SpotToken = unimplemented!();
    /// // Example: to_wei() converts decimal to wei representation
    /// // let wei = token.to_wei(amount);
    /// ```
    #[must_use]
    pub fn to_wei(&self, size: Decimal) -> U256 {
        to_wei(size, (self.wei_decimals + self.evm_extra_decimals) as u32)
    }

    /// Converts wei representation to a decimal amount.
    ///
    /// Uses the token's total decimals (wei_decimals + evm_extra_decimals).
    ///
    /// # Example
    ///
    /// ```
    /// # use hypersdk::hypercore::SpotToken;
    /// # use hypersdk::{Address, Decimal, U256};
    /// # let token = SpotToken {
    /// #     name: "USDC".into(), index: 0, token_id: Default::default(),
    /// #     evm_contract: None, cross_chain_address: None,
    /// #     sz_decimals: 6, wei_decimals: 6, evm_extra_decimals: 12
    /// # };
    /// let wei = U256::from(100_500_000_000_000_000_000u128);
    /// let amount = token.from_wei(wei);
    /// ```
    #[must_use]
    pub fn from_wei(&self, size: U256) -> Decimal {
        from_wei(size, (self.wei_decimals + self.evm_extra_decimals) as u32)
    }

    /// Returns whether the token can be bridged to HyperEVM.
    ///
    /// Returns `true` if the token has an EVM contract address.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use hypersdk::hypercore;
    /// # async fn example() -> anyhow::Result<()> {
    /// # let client = hypercore::mainnet();
    /// let tokens = client.spot_tokens().await?;
    /// let evm_tokens: Vec<_> = tokens.into_iter()
    ///     .filter(|t| t.is_evm_linked())
    ///     .collect();
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline(always)]
    pub fn is_evm_linked(&self) -> bool {
        self.evm_contract.is_some()
    }

    /// Returns the total decimals for EVM representation.
    ///
    /// This is the sum of `sz_decimals` and `evm_extra_decimals`.
    #[must_use]
    #[inline(always)]
    pub fn total_evm_decimals(&self) -> i64 {
        self.sz_decimals + self.evm_extra_decimals
    }

    /// Returns the bridge address for cross-chain transfers.
    ///
    /// Returns `None` if the token cannot be bridged.
    #[must_use]
    #[inline(always)]
    pub fn bridge_address(&self) -> Option<Address> {
        self.cross_chain_address
    }
}

impl Hash for SpotToken {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.token_id.hash(state);
    }
}

impl PartialEq for SpotToken {
    fn eq(&self, other: &Self) -> bool {
        self.token_id == other.token_id
    }
}

impl Eq for SpotToken {}

impl fmt::Display for SpotToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

/// One side of an outcome market.
#[derive(Debug, Clone)]
pub struct OutcomeSideSpec {
    /// Side name (e.g., "Yes", "No")
    pub name: String,
}

/// Outcome market.
#[derive(Debug, Clone)]
pub struct OutcomeInfo {
    /// Outcome ID
    pub outcome: u32,
    /// Market name (e.g., "Recurring")
    pub name: String,
    /// Market description or structured parameters
    pub description: String,
    /// The two sides of this outcome
    pub side_specs: Vec<OutcomeSideSpec>,
}

/// Groups multiple outcomes into a question.
#[derive(Debug, Clone)]
pub struct OutcomeQuestion {
    /// Question ID
    pub question: u32,
    /// Question name
    pub name: String,
    /// Question description
    pub description: String,
    /// Fallback outcome if no named outcome wins
    pub fallback_outcome: Option<u32>,
    /// Outcome IDs in this question
    pub named_outcomes: Vec<u32>,
    /// Already settled outcome IDs
    pub settled_named_outcomes: Vec<u32>,
}

/// Outcome market metadata from the `outcomeMeta` info endpoint.
#[derive(Debug, Clone)]
pub struct OutcomeMeta {
    pub outcomes: Vec<OutcomeInfo>,
    pub questions: Vec<OutcomeQuestion>,
}

async fn raw_spot_markets(
    core_url: impl IntoUrl,
    client: reqwest::Client,
) -> anyhow::Result<SpotTokens> {
    let mut url = core_url.into_url()?;
    url.set_path("/info");
    let resp = client.post(url).json(&InfoRequest::SpotMeta).send().await?;
    Ok(resp.json().await?)
}

/// Fetches all available spot tokens from HyperCore.
///
/// Returns a list of all tokens that can be traded on spot markets.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let url = hypercore::mainnet_url();
/// let client = reqwest::Client::new();
/// let tokens = hypercore::spot_tokens(url, client).await?;
///
/// for token in tokens {
///     println!("{}: {} decimals", token.name, token.sz_decimals);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn spot_tokens(
    core_url: impl IntoUrl,
    client: reqwest::Client,
) -> anyhow::Result<Vec<SpotToken>> {
    let data = raw_spot_markets(core_url, client).await?;

    let spot_tokens: Vec<_> = data.tokens.iter().cloned().map(SpotToken::from).collect();
    Ok(spot_tokens)
}

/// Fetches all available spot trading markets from HyperCore.
///
/// Returns a list of all spot trading pairs with their associated tokens and price tick tables.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let url = hypercore::mainnet_url();
/// let client = reqwest::Client::new();
/// let markets = hypercore::spot_markets(url, client).await?;
///
/// for market in markets {
///     println!("{}: {} / {}", market.name, market.tokens[0].name, market.tokens[1].name);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn spot_markets(
    core_url: impl IntoUrl,
    client: reqwest::Client,
) -> anyhow::Result<Vec<SpotMarket>> {
    let data = raw_spot_markets(core_url, client).await?;
    let mut markets = Vec::with_capacity(data.universe.len());

    let spot_tokens: Vec<_> = data.tokens.iter().cloned().map(SpotToken::from).collect();

    for item in data.universe {
        let (_, base) = spot_tokens
            .iter()
            .enumerate()
            .find(|(index, _)| *index as u32 == item.tokens[0])
            .context("base token index not found")?;
        let (_, quote) = spot_tokens
            .iter()
            .enumerate()
            .find(|(index, _)| *index as u32 == item.tokens[1])
            .context("quote token index not found")?;

        markets.push(SpotMarket {
            name: item.name,
            index: 10_000 + item.index,
            tokens: [base.clone(), quote.clone()],
            table: PriceTick::for_spot(base.sz_decimals),
        });
    }

    Ok(markets)
}

/// Fetches all available perpetual futures DEXes from HyperCore.
///
/// Returns a list of all DEXes that offer perpetual futures trading.
/// This is a standalone function that can be used without creating a client instance.
///
/// # Parameters
///
/// - `core_url`: The HyperCore API URL (use [`mainnet_url()`] or [`testnet_url()`])
/// - `client`: The HTTP client to use for the request
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let url = hypercore::mainnet_url();
/// let client = reqwest::Client::new();
/// let dexes = hypercore::perp_dexs(url, client).await?;
///
/// for dex in dexes {
///     println!("DEX: {}", dex.name());
/// }
/// # Ok(())
/// # }
/// ```
pub async fn perp_dexs(
    core_url: impl IntoUrl,
    client: reqwest::Client,
) -> anyhow::Result<Vec<Dex>> {
    let mut url = core_url.into_url()?;
    url.set_path("/info");

    let resp = client
        .post(url)
        .json(&InfoRequest::PerpDexs)
        .send()
        .await
        .context("info")?;

    let dexes: Vec<Option<PerpDex>> = resp.json().await?;
    let dex_list = dexes
        .into_iter()
        .enumerate()
        .filter_map(|(index, dex)| {
            dex.map(|dex| Dex {
                name: dex.name,
                index,
                deployer_fee_scale: dex.deployer_fee_scale,
            })
        })
        .collect();

    Ok(dex_list)
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PerpDex {
    name: String,
    #[serde(default, with = "rust_decimal::serde::str_option")]
    deployer_fee_scale: Option<Decimal>,
}

/// Fetches all available perpetual futures markets from HyperCore.
///
/// Returns a list of all perpetual contracts with leverage, collateral, and margin information.
pub async fn perp_markets(
    core_url: impl IntoUrl,
    client: reqwest::Client,
    dex: Option<Dex>,
) -> anyhow::Result<Vec<PerpMarket>> {
    let mut url = core_url.into_url()?;
    url.set_path("/info");

    // get it to gather the collateral token
    let spot = raw_spot_markets(url.clone(), client.clone()).await?;
    let resp = client
        .post(url)
        .json(&InfoRequest::Meta {
            dex: dex.as_ref().map(|dex| dex.name.clone()),
        })
        .send()
        .await
        .context("meta")?;
    let data: PerpTokens = resp.json().await?;
    let collateral = spot
        .tokens
        .get(data.collateral_token)
        .context("collateral token index out of bounds")?;
    let collateral = SpotToken::from(collateral.clone());
    let dex_index = dex.as_ref().map(|dex| dex.index).unwrap_or_default();

    let perps = data
        .universe
        .into_iter()
        .enumerate()
        .map(|(index, perp)| {
            // https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/asset-ids
            let index = 100_000 * usize::from(dex.is_some()) + dex_index * 10_000 + index;
            PerpMarket {
                name: perp.name,
                index,
                max_leverage: perp.max_leverage,
                sz_decimals: perp.sz_decimals,
                collateral: collateral.clone(),
                isolated_margin: perp.only_isolated,
                margin_mode: perp.margin_mode,
                growth_mode: perp.growth_mode,
                aligned_quote_token: perp.aligned_quote_token,
                table: PriceTick::for_perp(perp.sz_decimals),
            }
        })
        .collect();

    Ok(perps)
}

/// Fetches outcome market metadata from HyperCore.
pub async fn outcome_meta(
    core_url: impl IntoUrl,
    client: reqwest::Client,
) -> anyhow::Result<OutcomeMeta> {
    let mut url = core_url.into_url()?;
    url.set_path("/info");

    let resp = client
        .post(url)
        .json(&InfoRequest::OutcomeMeta)
        .send()
        .await
        .context("info")?;

    let raw: RawOutcomeMeta = resp.json().await?;

    Ok(OutcomeMeta {
        outcomes: raw
            .outcomes
            .into_iter()
            .map(|o| OutcomeInfo {
                outcome: o.outcome,
                name: o.name,
                description: o.description,
                side_specs: o
                    .side_specs
                    .into_iter()
                    .map(|s| OutcomeSideSpec { name: s.name })
                    .collect(),
            })
            .collect(),
        questions: raw
            .questions
            .into_iter()
            .map(|q| OutcomeQuestion {
                question: q.question,
                name: q.name,
                description: q.description,
                fallback_outcome: q.fallback_outcome,
                named_outcomes: q.named_outcomes,
                settled_named_outcomes: q.settled_named_outcomes,
            })
            .collect(),
    })
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawOutcomeMeta {
    #[serde(default)]
    outcomes: Vec<RawOutcomeInfo>,
    #[serde(default)]
    questions: Vec<RawOutcomeQuestion>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawOutcomeInfo {
    outcome: u32,
    name: String,
    description: String,
    side_specs: Vec<RawOutcomeSideSpec>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawOutcomeSideSpec {
    name: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawOutcomeQuestion {
    question: u32,
    name: String,
    description: String,
    fallback_outcome: Option<u32>,
    #[serde(default)]
    named_outcomes: Vec<u32>,
    #[serde(default)]
    settled_named_outcomes: Vec<u32>,
}

/// Generates an EVM transfer address for cross-chain transfers.
///
/// Creates addresses in the format `0x20000000000000000000000000000000000000XX`
/// where XX is the token index, used for transferring tokens from HyperCore to HyperEVM.
fn generate_evm_transfer_address(index: usize) -> Address {
    // Base address: 0x2000000000000000000000000000000000000000
    // The 0x20 prefix identifies these as cross-chain transfer addresses
    let base = U256::from(0x20) << 152; // Shift 0x20 to the first byte (19 bytes * 8 bits = 152)
    let addr: U256 = base + U256::from(index);
    let bytes = addr.to_be_bytes::<32>();
    Address::from_slice(&bytes[12..]) // Take last 20 bytes for Address
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PerpTokens {
    universe: Vec<PerpUniverseItem>,
    collateral_token: usize,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PerpUniverseItem {
    name: String,
    max_leverage: u64,
    #[serde(default)]
    only_isolated: bool,
    margin_mode: Option<MarginMode>,
    sz_decimals: i64,
    #[serde(default, deserialize_with = "deserialize_growth_mode")]
    growth_mode: bool,
    #[serde(default, alias = "isAlignedQuoteToken", alias = "isQuoteTokenAligned")]
    aligned_quote_token: bool,
    // margin_table_id: u64,
}

fn deserialize_growth_mode<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    match s.as_str() {
        "enabled" => Ok(true),
        "disabled" => Ok(false),
        _ => Err(serde::de::Error::custom(format!(
            "invalid growth_mode value: {}",
            s
        ))),
    }
}

#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MarginMode {
    StrictIsolated,
    NoCross,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SpotTokens {
    universe: Vec<SpotUniverseItem>,
    tokens: Vec<Token>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SpotUniverseItem {
    // base and quote
    tokens: [u32; 2],
    name: String,
    index: usize,
}

#[derive(Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Token {
    name: String,
    index: usize,
    token_id: B128,
    sz_decimals: i64,
    wei_decimals: i64,
    evm_contract: Option<EvmContract>,
}

impl From<Token> for SpotToken {
    fn from(token: Token) -> Self {
        let (evm_contract, cross_chain_address, evm_extra_decimals) =
            if let Some(contract) = token.evm_contract {
                (
                    Some(if token.name == "USDC" {
                        // map it to the contract in EVM
                        USDC_CONTRACT_IN_EVM
                    } else {
                        contract.address
                    }),
                    Some(generate_evm_transfer_address(token.index)),
                    contract.evm_extra_wei_decimals,
                )
            } else if token.name == "HYPE" {
                // map it to WHYPE
                (
                    Some(Address::repeat_byte(85)),
                    Some(Address::repeat_byte(34)),
                    10,
                )
            } else {
                (None, None, 0)
            };

        Self {
            name: token.name.clone(),
            token_id: token.token_id,
            index: token.index as u32,
            evm_contract,
            evm_extra_decimals,
            wei_decimals: token.wei_decimals,
            cross_chain_address: if token.name == "HYPE" {
                Some(Address::repeat_byte(34))
            } else {
                cross_chain_address
            },
            sz_decimals: token.sz_decimals,
        }
    }
}

#[derive(Clone, Deserialize)]
#[serde(rename_all = "snake_case")]
struct EvmContract {
    address: Address,
    evm_extra_wei_decimals: i64,
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, sync::Arc, thread};

    use alloy::primitives::address;

    use super::*;
    use crate::hypercore;

    #[tokio::test]
    async fn test_spot_markets() {
        let client = reqwest::Client::new();
        let markets = spot_markets("https://api.hyperliquid.xyz", client)
            .await
            .unwrap();
        assert!(!markets.is_empty());
    }

    #[tokio::test]
    async fn test_evm_send_addresses() {
        let expected_addresses = HashMap::from([
            // PURR
            (
                "PURR/USDC",
                address!("0x2000000000000000000000000000000000000001"),
            ),
            // HFUN
            ("@1", address!("0x2000000000000000000000000000000000000002")),
            // USDT0
            (
                "@166",
                address!("0x200000000000000000000000000000000000010C"),
            ),
            // JEFF
            ("@4", address!("0x2000000000000000000000000000000000000005")),
            // HYPE
            (
                "@107",
                address!("0x2222222222222222222222222222222222222222"),
            ),
            // kHYPE
            (
                "@250",
                address!("0x2000000000000000000000000000000000000079"),
            ),
            // UBTC
            (
                "@142",
                address!("0x20000000000000000000000000000000000000c5"),
            ),
        ]);
        let spot = hypercore::spot_markets(mainnet_url(), reqwest::Client::new())
            .await
            .unwrap();
        for (key, value) in expected_addresses {
            let market = spot.iter().find(|market| market.name == key).unwrap();
            let address = market.tokens[0].cross_chain_address.unwrap();
            assert_eq!(address, value, "unexpected {address} <> {value}");
        }
    }

    #[tokio::test]
    async fn test_http_clearinghouse_state() {
        let client = hypercore::mainnet();
        // Use a known address with positions (Hyperliquid vault)
        let user = address!("0x162cc7c861ebd0c06b3d72319201150482518185");
        let state = client.clearinghouse_state(user, None).await.unwrap();

        // Verify structure is returned correctly
        assert!(state.time > 0);
        // Account should have some value
        assert!(state.margin_summary.account_value >= rust_decimal::Decimal::ZERO);
    }

    #[tokio::test]
    async fn test_http_user_balances() {
        let client = hypercore::mainnet();
        let user = address!("0xdfc24b077bc1425ad1dea75bcb6f8158e10df303");
        // Should return a list (possibly empty) without error
        let _balances = client.user_balances(user).await.unwrap();
    }

    #[tokio::test]
    async fn test_http_user_fees() {
        let client = hypercore::mainnet();
        let user = address!("0xdfc24b077bc1425ad1dea75bcb6f8158e10df303");
        // Smoke test: endpoint should deserialize successfully.
        let _fees = client.user_fees(user).await.unwrap();
    }

    #[tokio::test]
    async fn test_http_all_mids() {
        let client = hypercore::mainnet();
        let mids = client.all_mids(None).await.unwrap();

        // Should have prices for major markets
        assert!(mids.contains_key("BTC"));
        assert!(mids.contains_key("ETH"));
        assert!(*mids.get("BTC").unwrap() > rust_decimal::Decimal::ZERO);
    }

    #[tokio::test]
    async fn test_http_open_orders() {
        let client = hypercore::mainnet();
        let user = address!("0xdfc24b077bc1425ad1dea75bcb6f8158e10df303");
        // Should return a list (possibly empty) without error
        let _orders = client.open_orders(user, None).await.unwrap();
    }

    #[tokio::test]
    async fn test_http_perps() {
        let client = hypercore::mainnet();
        let perps = client.perps().await.unwrap();

        // Should have major markets
        assert!(!perps.is_empty());
        assert!(perps.iter().any(|m| m.name == "BTC"));
        assert!(perps.iter().any(|m| m.name == "ETH"));
    }

    #[tokio::test]
    async fn test_http_spot() {
        let client = hypercore::mainnet();
        let spots = client.spot().await.unwrap();

        // Should have spot markets
        assert!(!spots.is_empty());
    }

    #[test]
    fn test_nonce_handler_uniqueness_single_thread() {
        let handler = NonceHandler::default();
        let mut nonces = std::collections::HashSet::new();

        for _ in 0..10_000 {
            let nonce = handler.next();
            assert!(nonces.insert(nonce), "Duplicate nonce detected: {nonce}");
        }
    }

    #[test]
    fn test_nonce_handler_uniqueness_concurrent() {
        let handler = Arc::new(NonceHandler::default());
        let num_threads = 32;
        let nonces_per_thread = 1_000_000;

        let barrier = Arc::new(std::sync::Barrier::new(num_threads));

        let handles: Vec<_> = (0..num_threads)
            .map(|_| {
                let handler = Arc::clone(&handler);
                let barrier = Arc::clone(&barrier);
                thread::spawn(move || {
                    barrier.wait();
                    let mut nonces = Vec::with_capacity(nonces_per_thread);
                    for _ in 0..nonces_per_thread {
                        nonces.push(handler.next());
                    }
                    nonces
                })
            })
            .collect();

        let mut all_nonces = std::collections::HashSet::new();
        for handle in handles {
            let nonces = handle.join().unwrap();
            for nonce in nonces {
                assert!(
                    all_nonces.insert(nonce),
                    "Duplicate nonce detected in concurrent test: {nonce}"
                );
            }
        }

        assert_eq!(all_nonces.len(), num_threads * nonces_per_thread);
    }

    #[test]
    fn test_nonce_handler_stale_nonce_race_condition() {
        // This test specifically targets the race condition when nonce falls behind.
        // We simulate this by creating a handler with an artificially old nonce.
        use std::sync::atomic::Ordering;

        let handler = Arc::new(NonceHandler::default());

        // Set nonce to a value far in the past to trigger the reset branch
        let old_nonce = 1000u64;
        handler.nonce.store(old_nonce, Ordering::SeqCst);

        let num_threads = 16;
        let nonces_per_thread = 1000;

        // Use a barrier to ensure all threads start at roughly the same time
        let barrier = Arc::new(std::sync::Barrier::new(num_threads));

        let handles: Vec<_> = (0..num_threads)
            .map(|_| {
                let handler = Arc::clone(&handler);
                let barrier = Arc::clone(&barrier);
                thread::spawn(move || {
                    barrier.wait();
                    let mut nonces = Vec::with_capacity(nonces_per_thread);
                    for _ in 0..nonces_per_thread {
                        nonces.push(handler.next());
                    }
                    nonces
                })
            })
            .collect();

        let mut all_nonces = std::collections::HashSet::new();
        let mut duplicates = Vec::new();

        for handle in handles {
            let nonces = handle.join().unwrap();
            for nonce in nonces {
                if !all_nonces.insert(nonce) {
                    duplicates.push(nonce);
                }
            }
        }

        assert!(
            duplicates.is_empty(),
            "Found {} duplicate nonces when triggering stale nonce reset: {:?}",
            duplicates.len(),
            &duplicates[..duplicates.len().min(10)]
        );
    }

    #[tokio::test]
    async fn test_http_outcome_meta_mainnet() {
        let client = hypercore::mainnet();
        let meta = client.outcome_meta().await.unwrap();
        // Mainnet may have empty outcomes — just verify the call succeeds
        let _ = meta.outcomes.len();
    }

    #[tokio::test]
    async fn test_http_outcome_meta_testnet() {
        let client = hypercore::testnet();
        let meta = client.outcome_meta().await.unwrap();
        // Testnet should have outcome markets
        assert!(!meta.outcomes.is_empty());
        // Each outcome should have exactly 2 sides
        for o in &meta.outcomes {
            assert_eq!(o.side_specs.len(), 2, "outcome {} should have 2 sides", o.outcome);
        }
    }

    #[test]
    fn outcome_meta_deserialize() {
        let json = r#"{
            "outcomes": [
                {
                    "outcome": 1273,
                    "name": "Recurring",
                    "description": "class:priceBinary|underlying:BTC|expiry:20260317-0300|targetPrice:74212|period:1d",
                    "sideSpecs": [{"name": "Yes"}, {"name": "No"}]
                },
                {
                    "outcome": 9,
                    "name": "Who will win the HL 100 meter dash?",
                    "description": "This race is yet to be scheduled.",
                    "sideSpecs": [{"name": "Hypurr"}, {"name": "Usain Bolt"}]
                }
            ],
            "questions": [
                {
                    "question": 1,
                    "name": "What will Hypurr eat?",
                    "description": "Food journal.",
                    "fallbackOutcome": 13,
                    "namedOutcomes": [10, 11, 12],
                    "settledNamedOutcomes": []
                }
            ]
        }"#;
        let meta: RawOutcomeMeta = serde_json::from_str(json).unwrap();
        assert_eq!(meta.outcomes.len(), 2);
        assert_eq!(meta.outcomes[0].outcome, 1273);
        assert_eq!(meta.outcomes[0].name, "Recurring");
        assert_eq!(meta.outcomes[0].side_specs.len(), 2);
        assert_eq!(meta.outcomes[0].side_specs[0].name, "Yes");
        assert_eq!(meta.outcomes[1].side_specs[1].name, "Usain Bolt");
        assert_eq!(meta.questions.len(), 1);
        assert_eq!(meta.questions[0].question, 1);
        assert_eq!(meta.questions[0].fallback_outcome, Some(13));
        assert_eq!(meta.questions[0].named_outcomes, vec![10, 11, 12]);
    }

    #[test]
    fn outcome_meta_empty() {
        let json = r#"{"outcomes": [], "questions": []}"#;
        let meta: RawOutcomeMeta = serde_json::from_str(json).unwrap();
        assert!(meta.outcomes.is_empty());
        assert!(meta.questions.is_empty());
    }
}