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
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
//! HTTP client for HyperCore API interactions.
//!
//! This module provides the HTTP client for placing orders, querying balances,
//! managing positions, and performing asset transfers on Hyperliquid.
//!
//! # Examples
//!
//! ## Query User Balances
//!
//! ```no_run
//! use hypersdk::hypercore;
//! use hypersdk::Address;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = hypercore::mainnet();
//! let user: Address = "0x...".parse()?;
//! let balances = client.user_balances(user).await?;
//!
//! for balance in balances {
//!     println!("{}: {}", balance.coin, balance.total);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Place Orders
//!
//! ```no_run
//! use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = hypercore::mainnet();
//! let signer: PrivateKeySigner = "your_key".parse()?;
//!
//! // Note: This example shows the structure but cannot run without
//! // the rust_decimal_macros::dec!() macro and chrono clock feature.
//! // In real usage, replace with actual decimal values and timestamp.
//! # Ok(())
//! # }
//! ```

use std::{
    collections::{HashMap, VecDeque},
    time::Duration,
};

use alloy::{
    primitives::Address,
    signers::{Signer, SignerSync},
};
use anyhow::{Result, anyhow};
use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use serde::Deserialize;
use url::Url;

use super::{AssetTarget, signing::*};
use crate::hypercore::{
    ActionError, ApiAgent, CandleInterval, Chain, Cloid, Dex, MultiSigConfig, OidOrCloid,
    OutcomeMeta, PerpMarket, Signature, SpotMarket, SpotToken,
    api::{
        Action, ActionRequest, ApproveAgent, ConvertToMultiSigUser, OkResponse, Response,
        SignersConfig, VaultTransfer,
    },
    mainnet_url, testnet_url,
    types::{
        BasicOrder, BatchCancel, BatchCancelCloid, BatchModify, BatchOrder, ClearinghouseState,
        Fill, FundingRate, InfoRequest, OrderResponseStatus, OrderUpdate, ScheduleCancel,
        SendAsset, SendToken, SpotSend, SubAccount, UsdSend, UserBalance, UserFees, UserRole,
        UserVaultEquity, VaultDetails,
    },
};

/// HTTP client for HyperCore API.
///
/// Provides methods for trading, querying market data, managing positions,
/// and performing asset transfers.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore;
///
/// let client = hypercore::mainnet();
/// // Use client for API calls
/// ```
pub struct Client {
    http_client: reqwest::Client,
    base_url: Url,
    chain: Chain,
}

impl Client {
    /// Creates a new HTTP client for the specified chain.
    ///
    /// The base URL is automatically determined based on the chain:
    /// - `Chain::Mainnet`: `https://api.hyperliquid.xyz`
    /// - `Chain::Testnet`: `https://api.hyperliquid-testnet.xyz`
    ///
    /// All actions signed by this client will use chain-specific values:
    /// - Agent source field: `"a"` for mainnet, `"b"` for testnet
    /// - Multisig chain ID: `"0x66eee"` for mainnet, `"0x66eef"` for testnet
    ///
    /// # Example
    ///
    /// ```
    /// use hypersdk::hypercore::{HttpClient, Chain};
    ///
    /// // Create a mainnet client
    /// let mainnet_client = HttpClient::new(Chain::Mainnet);
    ///
    /// // Create a testnet client
    /// let testnet_client = HttpClient::new(Chain::Testnet);
    /// ```
    pub fn new(chain: Chain) -> Self {
        let base_url = if chain.is_mainnet() {
            mainnet_url()
        } else {
            testnet_url()
        };

        let http_client = reqwest::Client::builder()
            .timeout(Duration::from_secs(10))
            .tcp_nodelay(true)
            .build()
            .unwrap();

        Self {
            http_client,
            base_url,
            chain,
        }
    }

    /// Sets a custom base URL for this client.
    ///
    /// This is useful when connecting to a custom Hyperliquid node or proxy.
    /// The chain configuration is preserved.
    ///
    /// # Example
    ///
    /// ```
    /// use hypersdk::hypercore::{HttpClient, Chain};
    /// use url::Url;
    ///
    /// let custom_url: Url = "https://my-custom-node.example.com".parse().unwrap();
    /// let client = HttpClient::new(Chain::Mainnet)
    ///     .with_url(custom_url);
    /// ```
    pub fn with_url(self, base_url: Url) -> Self {
        Self { base_url, ..self }
    }

    #[must_use]
    pub fn with_http_client(self, http_client: reqwest::Client) -> Self {
        Self { http_client, ..self }
    }

    /// Returns the chain this client is configured for.
    #[must_use]
    pub const fn chain(&self) -> Chain {
        self.chain
    }

    /// Creates a WebSocket connection using the same base URL as this HTTP client.
    ///
    /// # Example
    ///
    /// ```
    /// use hypersdk::hypercore;
    /// use futures::StreamExt;
    ///
    /// # async fn example() {
    /// let client = hypercore::mainnet();
    /// let mut ws = client.websocket();
    /// // Subscribe and process messages
    /// # }
    /// ```
    pub fn websocket(&self) -> super::WebSocket {
        let mut url = self.base_url.clone();
        let _ = url.set_scheme("wss");
        url.set_path("/ws");
        super::WebSocket::new(url)
    }

    /// Creates a WebSocket connection without TLS (uses `ws://` instead of `wss://`).
    ///
    /// Useful for testing or local development.
    pub fn websocket_no_tls(&self) -> super::WebSocket {
        let mut url = self.base_url.clone();
        let _ = url.set_scheme("ws");
        url.set_path("/ws");
        super::WebSocket::new(url)
    }

    /// Fetches all available perpetual futures markets.
    ///
    /// # 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", market.name, market.max_leverage);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn perps(&self) -> Result<Vec<PerpMarket>> {
        super::perp_markets(self.base_url.clone(), self.http_client.clone(), None).await
    }

    /// Fetches perpetual markets from a specific DEX.
    ///
    /// Returns a list of perpetual futures markets available on the specified DEX.
    /// Use this when you want to query markets from a specific exchange rather than
    /// the default Hyperliquid DEX.
    ///
    /// # Parameters
    ///
    /// - `dex`: The DEX to query markets from
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use hypersdk::hypercore;
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    ///
    /// // Get available DEXes
    /// let dexes = client.perp_dexs().await?;
    ///
    /// // Query markets from a specific DEX
    /// if let Some(dex) = dexes.first() {
    ///     let markets = client.perps_from(dex.clone()).await?;
    ///     for market in markets {
    ///         println!("{}: {}x leverage", market.name, market.max_leverage);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn perps_from(&self, dex: Dex) -> Result<Vec<PerpMarket>> {
        super::perp_markets(self.base_url.clone(), self.http_client.clone(), Some(dex)).await
    }

    /// Fetches all available perpetual futures DEXes.
    ///
    /// Returns a list of all DEXes that offer perpetual futures trading on Hyperliquid.
    /// Each DEX has a unique name and index.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use hypersdk::hypercore;
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let dexes = client.perp_dexs().await?;
    ///
    /// for dex in dexes {
    ///     println!("DEX: {}", dex.name());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn perp_dexs(&self) -> Result<Vec<Dex>> {
        super::perp_dexs(self.base_url.clone(), self.http_client.clone()).await
    }

    /// Fetches all available spot markets.
    ///
    /// # 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.symbol());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn spot(&self) -> Result<Vec<SpotMarket>> {
        super::spot_markets(self.base_url.clone(), self.http_client.clone()).await
    }

    /// Fetches all available spot tokens.
    ///
    /// # 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 {
    ///     println!("{}: {} decimals", token.name, token.sz_decimals);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn spot_tokens(&self) -> Result<Vec<SpotToken>> {
        super::spot_tokens(self.base_url.clone(), self.http_client.clone()).await
    }

    /// Fetches outcome market metadata.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::testnet();
    /// let meta = client.outcome_meta().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub async fn outcome_meta(&self) -> Result<OutcomeMeta> {
        super::outcome_meta(self.base_url.clone(), self.http_client.clone()).await
    }

    /// Returns all open orders for a user.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let user: Address = "0x...".parse()?;
    /// let orders = client.open_orders(user, None).await?;
    ///
    /// for order in orders {
    ///     println!("{} {} @ {}", order.side, order.sz, order.limit_px);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn open_orders(
        &self,
        user: Address,
        dex_name: Option<String>,
    ) -> Result<Vec<BasicOrder>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::FrontendOpenOrders {
                user,
                dex: dex_name,
            })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Returns mid prices for all perpetual markets.
    ///
    /// Returns a map of market name to mid price.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let mids = client.all_mids(None).await?;
    ///
    /// for (market, price) in mids {
    ///     println!("{}: {}", market, price);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn all_mids(&self, dex_name: Option<String>) -> Result<HashMap<String, Decimal>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::AllMids { dex: dex_name })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Returns the user's historical orders.
    pub async fn historical_orders(&self, user: Address) -> Result<Vec<BasicOrder>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::HistoricalOrders { user })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Returns the user's fills.
    pub async fn user_fills(&self, user: Address) -> Result<Vec<Fill>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::UserFills { user })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Returns the user's fills by time.
    pub async fn user_fills_by_time(
        &self,
        user: Address,
        start_time: u64,
        end_time: Option<u64>,
    ) -> Result<Vec<Fill>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::UserFillsByTime {
                user,
                start_time,
                end_time,
            })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Returns the status of an order.
    pub async fn order_status(
        &self,
        user: Address,
        oid: OidOrCloid,
    ) -> Result<Option<OrderUpdate<BasicOrder>>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        #[serde(tag = "status")]
        enum Response {
            Order { order: OrderUpdate<BasicOrder> },
            UnknownOid,
        }

        let data: Response = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::OrderStatus { user, oid })
            .send()
            .await?
            .json()
            .await?;

        Ok(match data {
            Response::Order { order } => Some(order),
            Response::UnknownOid => None,
        })
    }

    /// Returns historical candlestick data for a market.
    ///
    /// Retrieves OHLCV (Open, High, Low, Close, Volume) candlestick data for the specified
    /// market and time range. Only the most recent 5000 candles are available.
    ///
    /// # Parameters
    ///
    /// - `coin`: Market symbol (e.g., "BTC", "ETH"). For HIP-3 assets, prefix with dex name (e.g., "xyz:XYZ100")
    /// - `interval`: Candle interval (e.g., "1m", "15m", "1h", "1d")
    /// - `start_time`: Start time in milliseconds
    /// - `end_time`: End time in milliseconds
    ///
    /// # Available Intervals
    ///
    /// - Minutes: 1m, 3m, 5m, 15m, 30m
    /// - Hours: 1h, 2h, 4h, 8h, 12h
    /// - Days: 1d, 3d, 1w, 1M
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore::{self, CandleInterval};
    /// use chrono::{Utc, Duration};
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    ///
    /// // Get last 100 15-minute candles
    /// let end_time = Utc::now().timestamp_millis() as u64;
    /// let start_time = (Utc::now() - Duration::hours(25)).timestamp_millis() as u64;
    ///
    /// let candles = client
    ///     .candle_snapshot("BTC", CandleInterval::FifteenMinutes, start_time, end_time)
    ///     .await?;
    ///
    /// for candle in candles {
    ///     println!("BTC: O:{} H:{} L:{} C:{} V:{}",
    ///         candle.open, candle.high, candle.low, candle.close, candle.volume);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn candle_snapshot(
        &self,
        coin: impl Into<String>,
        interval: CandleInterval,
        start_time: u64,
        end_time: u64,
    ) -> Result<Vec<super::types::Candle>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let req = super::types::CandleSnapshotRequest {
            coin: coin.into(),
            interval,
            start_time,
            end_time,
        };

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::CandleSnapshot { req })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Retrieves spot token balances for a user.
    ///
    /// Returns all tokens the user holds on the spot market, including held (locked) and total amounts.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let user: Address = "0x...".parse()?;
    /// let balances = client.user_balances(user).await?;
    ///
    /// for balance in balances {
    ///     println!("{}: total={}, held={}", balance.coin, balance.total, balance.hold);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn user_balances(&self, user: Address) -> Result<Vec<UserBalance>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        #[derive(Deserialize)]
        struct Balances {
            balances: Vec<UserBalance>,
        }

        let data: Balances = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::SpotClearinghouseState { user })
            .send()
            .await?
            .json()
            .await?;

        Ok(data.balances)
    }

    /// Retrieves user-specific fee rates.
    ///
    /// Returns effective maker and taker rates plus the active referral discount.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let user: Address = "0x...".parse()?;
    /// let fees = client.user_fees(user).await?;
    ///
    /// println!("maker={} taker={} referral_discount={}",
    ///     fees.maker_rate,
    ///     fees.taker_rate,
    ///     fees.referral_discount
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub async fn user_fees(&self, user: Address) -> Result<UserFees> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::UserFees { user })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Retrieves the clearinghouse state for a user's perpetual positions.
    ///
    /// Returns the complete state of a user's perpetual trading account, including
    /// margin summaries, withdrawable amounts, and all open positions.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let user: Address = "0x...".parse()?;
    /// let state = client.clearinghouse_state(user, None).await?;
    ///
    /// // Check account value and withdrawable amount
    /// println!("Account value: {}", state.margin_summary.account_value);
    /// println!("Withdrawable: {}", state.withdrawable);
    ///
    /// // Check margin utilization
    /// let utilization = state.margin_summary.margin_utilization();
    /// println!("Margin utilization: {}%", utilization);
    ///
    /// // Iterate through positions
    /// for asset_position in &state.asset_positions {
    ///     let pos = &asset_position.position;
    ///     println!("{} {}: {} @ {:?} (PnL: {})",
    ///         pos.side(),
    ///         pos.coin,
    ///         pos.szi,
    ///         pos.entry_px,
    ///         pos.unrealized_pnl
    ///     );
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn clearinghouse_state(
        &self,
        user: Address,
        dex_name: Option<String>,
    ) -> Result<ClearinghouseState> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::ClearinghouseState {
                user,
                dex: dex_name,
            })
            .send()
            .await?
            .json()
            .await?;
        Ok(data)
    }

    /// Retrieves historical funding rates for a perpetual market.
    ///
    /// Returns funding rate snapshots for the specified coin within the given time range.
    /// Hyperliquid pays funding every hour.
    ///
    /// # Parameters
    ///
    /// - `coin`: Market symbol (e.g., "BTC", "ETH")
    /// - `start_time`: Start time in milliseconds (inclusive)
    /// - `end_time`: Optional end time in milliseconds (inclusive). Defaults to current time.
    ///
    /// # Notes
    ///
    /// - Only the most recent 500 records are returned per request
    /// - To paginate, use the last returned timestamp as the next `start_time`
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    ///
    /// // Get BTC funding rates from the last 24 hours
    /// let end_time = chrono::Utc::now().timestamp_millis() as u64;
    /// let start_time = end_time - 24 * 60 * 60 * 1000; // 24 hours ago
    ///
    /// let rates = client.funding_history("BTC", start_time, Some(end_time)).await?;
    ///
    /// for rate in rates {
    ///     println!("Funding rate at {}: {} (premium: {})",
    ///         rate.time, rate.funding_rate, rate.premium);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn funding_history(
        &self,
        coin: impl Into<String>,
        start_time: u64,
        end_time: Option<u64>,
    ) -> Result<Vec<FundingRate>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let data = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::FundingHistory {
                coin: coin.into(),
                start_time,
                end_time,
            })
            .send()
            .await?
            .json()
            .await?;

        Ok(data)
    }

    /// Retrieves the multi-signature wallet configuration for a user.
    ///
    /// Returns the list of authorized signers and the signature threshold required
    /// for executing transactions on behalf of a multisig account.
    ///
    /// # Arguments
    ///
    /// * `user` - The address of the multisig account to query
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let multisig_addr = "0x1234567890abcdef1234567890abcdef12345678".parse()?;
    ///
    /// // Get multisig configuration
    /// let config = client.multi_sig_config(multisig_addr).await?;
    ///
    /// println!("Multisig requires {} of {} signatures",
    ///     config.threshold,
    ///     config.authorized_users.len()
    /// );
    ///
    /// for (i, signer) in config.authorized_users.iter().enumerate() {
    ///     println!("Authorized signer {}: {:?}", i + 1, signer);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn multi_sig_config(&self, user: Address) -> Result<MultiSigConfig> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let resp = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::UserToMultiSigSigners { user })
            .send()
            .await?
            .json()
            .await?;
        Ok(resp)
    }

    /// Get API agents for a user.
    ///
    /// Returns a list of additional agents authorized to act on behalf of the specified user.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use alloy::primitives::address;
    /// async fn example() -> anyhow::Result<()> {
    ///     let client = hypercore::mainnet();
    ///     let user = address!("0000000000000000000000000000000000000000");
    ///     let agents = client.api_agents(user).await?;
    ///
    ///     for agent in agents {
    ///         println!("Agent {}: {:?}, valid until: {:?}", agent.name, agent.address, agent.valid_until);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn api_agents(&self, user: Address) -> Result<Vec<ApiAgent>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let resp = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::ExtraAgents { user })
            .send()
            .await?
            .json()
            .await?;
        Ok(resp)
    }

    /// Retrieve details for a vault.
    ///
    /// Returns comprehensive information about a vault including performance metrics,
    /// follower information, and configuration.
    ///
    /// # Parameters
    ///
    /// - `vault_address`: The address of the vault to query
    /// - `user`: Optional user address to include follower state for that user
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let vault: Address = "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303".parse()?;
    ///
    /// // Get vault details without user-specific follower state
    /// let details = client.vault_details(vault, None).await?;
    /// println!("Vault: {} (APR: {}%)", details.name, details.apr);
    ///
    /// // Get vault details with user-specific follower state
    /// let user: Address = "0x...".parse()?;
    /// let details_with_state = client.vault_details(vault, Some(user)).await?;
    /// if let Some(state) = details_with_state.follower_state {
    ///     println!("Your equity: {}", state.vault_equity);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-details-for-a-vault>
    pub async fn vault_details(
        &self,
        vault_address: Address,
        user: Option<Address>,
    ) -> Result<VaultDetails> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let resp = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::VaultDetails {
                vault_address,
                user,
            })
            .send()
            .await?
            .json()
            .await?;
        Ok(resp)
    }

    /// Retrieve a user's vault deposits.
    ///
    /// Returns all vaults that a user has deposited into, along with their
    /// current equity in each vault.
    ///
    /// # Parameters
    ///
    /// - `user`: The address of the user to query vault deposits for
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let user: Address = "0x...".parse()?;
    ///
    /// let equities = client.user_vault_equities(user).await?;
    /// for equity in equities {
    ///     println!("Vault {:?}: equity = {}", equity.vault_address, equity.equity);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-vault-deposits>
    pub async fn user_vault_equities(&self, user: Address) -> Result<Vec<UserVaultEquity>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let resp = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::UserVaultEquities { user })
            .send()
            .await?
            .json()
            .await?;
        Ok(resp)
    }

    /// Query a user's role.
    ///
    /// Returns the role of an address in the Hyperliquid system. This can be used
    /// to determine if an address is a regular user, vault, agent, or subaccount.
    ///
    /// # Parameters
    ///
    /// - `user`: The address to query the role for
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let addr: Address = "0x...".parse()?;
    ///
    /// let role = client.user_role(addr).await?;
    /// match role {
    ///     hypersdk::hypercore::types::UserRole::User => println!("Regular user"),
    ///     hypersdk::hypercore::types::UserRole::Vault => println!("Vault account"),
    ///     hypersdk::hypercore::types::UserRole::Agent { user } => {
    ///         println!("Agent wallet for {}", user);
    ///     }
    ///     hypersdk::hypercore::types::UserRole::SubAccount { master } => println!("Subaccount {master}"),
    ///     hypersdk::hypercore::types::UserRole::Missing => println!("Not found"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-a-users-role>
    pub async fn user_role(&self, user: Address) -> Result<UserRole> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let resp = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::UserRole { user })
            .send()
            .await?
            .json()
            .await?;
        Ok(resp)
    }

    /// Retrieve a user's subaccounts.
    ///
    /// Returns all subaccounts associated with a master account, including their
    /// clearinghouse state (perpetuals) and spot balances.
    ///
    /// # Parameters
    ///
    /// - `user`: The address of the master account
    ///
    /// # Notes
    ///
    /// Subaccounts do not have private keys. To perform actions on behalf of a
    /// subaccount, signing should be done by the master account with the
    /// `vault_address` parameter set to the subaccount's address.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let master: Address = "0x...".parse()?;
    ///
    /// let subaccounts = client.subaccounts(master).await?;
    /// for sub in subaccounts {
    ///     println!("Subaccount '{}': {:?}", sub.name, sub.sub_account_user);
    ///     println!("  Account value: {}", sub.clearinghouse_state.margin_summary.account_value);
    ///     println!("  Withdrawable: {}", sub.clearinghouse_state.withdrawable);
    ///
    ///     // Check spot balances
    ///     for balance in &sub.spot_state.balances {
    ///         println!("  {}: {}", balance.coin, balance.total);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-subaccounts>
    pub async fn subaccounts(&self, user: Address) -> Result<Vec<SubAccount>> {
        let mut api_url = self.base_url.clone();
        api_url.set_path("/info");

        let resp = self
            .http_client
            .post(api_url)
            .json(&InfoRequest::SubAccounts { user })
            .send()
            .await?
            .json()
            .await?;
        Ok(resp)
    }

    /// Schedule cancellation.
    pub async fn schedule_cancel<S: SignerSync>(
        &self,
        signer: &S,
        nonce: u64,
        when: DateTime<Utc>,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> Result<()> {
        let resp = self
            .sign_and_send_sync(
                signer,
                ScheduleCancel {
                    time: Some(when.timestamp_millis() as u64),
                },
                nonce,
                vault_address,
                expires_after,
            )
            .await?;

        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => {
                anyhow::bail!("schedule_cancel: {err}")
            }
            _ => anyhow::bail!("schedule_cancel: unexpected response type: {resp:?}"),
        }
    }

    /// Places a batch of orders.
    ///
    /// Submits one or more orders to the exchange. Each order must be signed with your private key.
    ///
    /// # Parameters
    ///
    /// - `signer`: Private key signer for EIP-712 signatures
    /// - `batch`: Batch of orders to place
    /// - `nonce`: Unique nonce (typically current timestamp in milliseconds)
    /// - `vault_address`: Optional vault address if trading on behalf of a vault
    /// - `expires_after`: Optional expiration timestamp for the request
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    /// let signer: PrivateKeySigner = "your_key".parse()?;
    ///
    /// // Example order placement - requires dec!() macro and timestamp
    /// // let order = BatchOrder { ... };
    /// // let nonce = chrono::Utc::now().timestamp_millis() as u64;
    /// // let statuses = client.place(&signer, order, nonce, None, None).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn place<S: SignerSync>(
        &self,
        signer: &S,
        batch: BatchOrder,
        nonce: u64,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<Cloid>>> + Send + 'static
    {
        let cloids: Vec<_> = batch.orders.iter().map(|req| req.cloid).collect();

        let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);
        async move {
            let resp = future.await.map_err(|err| ActionError {
                ids: cloids.clone(),
                err: err.to_string(),
            })?;

            match resp {
                Response::Ok(OkResponse::Order { statuses }) => Ok(statuses),
                Response::Err(err) => Err(ActionError { ids: cloids, err }),
                _ => Err(ActionError {
                    ids: cloids,
                    err: format!("unexpected response type: {resp:?}"),
                }),
            }
        }
    }

    /// Cancel a batch of orders.
    pub fn cancel<S: SignerSync>(
        &self,
        signer: &S,
        batch: BatchCancel,
        nonce: u64,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<u64>>> + Send + 'static
    {
        let oids: Vec<_> = batch.cancels.iter().map(|req| req.oid).collect();

        let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);

        async move {
            let resp = future.await.map_err(|err| ActionError {
                ids: oids.clone(),
                err: err.to_string(),
            })?;

            match resp {
                Response::Ok(OkResponse::Cancel { statuses }) => Ok(statuses),
                Response::Err(err) => Err(ActionError { ids: oids, err }),
                _ => Err(ActionError {
                    ids: oids,
                    err: format!("unexpected response type: {resp:?}"),
                }),
            }
        }
    }

    /// Cancel a batch of orders by cloid.
    pub fn cancel_by_cloid<S: SignerSync>(
        &self,
        signer: &S,
        batch: BatchCancelCloid,
        nonce: u64,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<Cloid>>> + Send + 'static
    {
        let cloids: Vec<_> = batch.cancels.iter().map(|req| req.cloid).collect();

        let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);

        async move {
            let resp = future.await.map_err(|err| ActionError {
                ids: cloids.clone(),
                err: err.to_string(),
            })?;

            match resp {
                Response::Ok(OkResponse::Cancel { statuses }) => Ok(statuses),
                Response::Err(err) => Err(ActionError { ids: cloids, err }),
                _ => Err(ActionError {
                    ids: cloids,
                    err: format!("unexpected response type: {resp:?}"),
                }),
            }
        }
    }

    /// Modify a batch of orders.
    pub fn modify<S: SignerSync>(
        &self,
        signer: &S,
        batch: BatchModify,
        nonce: u64,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<OidOrCloid>>> + Send + 'static
    {
        let cloids: Vec<_> = batch.modifies.iter().map(|req| req.oid).collect();

        let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);

        async move {
            let resp = future.await.map_err(|err| ActionError {
                ids: cloids.clone(),
                err: err.to_string(),
            })?;

            match resp {
                Response::Ok(OkResponse::Order { statuses }) => Ok(statuses),
                Response::Err(err) => Err(ActionError { ids: cloids, err }),
                _ => Err(ActionError {
                    ids: cloids,
                    err: format!("unexpected response type: {resp:?}"),
                }),
            }
        }
    }

    /// Approve a new agent.
    ///
    /// Approves an agent to act on behalf of the signer's account. An account can have:
    /// - 1 unnamed approved wallet
    /// - Up to 3 named agents
    /// - 2 named agents per subaccount
    ///
    /// # Parameters
    ///
    /// - `signer`: The wallet signing the approval
    /// - `agent`: The address of the agent to approve
    /// - `name`: The name for the agent (or empty string for unnamed)
    /// - `nonce`: The nonce for this action
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use alloy::primitives::address;
    /// use alloy::signers::local::PrivateKeySigner;
    ///
    /// async fn example() -> anyhow::Result<()> {
    ///     let client = hypercore::mainnet();
    ///     let signer = PrivateKeySigner::random();
    ///     let agent = address!("0x97271b6b7f3b23a2f4700ae671b05515ae5c3319");
    ///     let name = "my_agent".to_string();
    ///     let nonce = 123456789;
    ///
    ///     client.approve_agent(&signer, agent, name, nonce).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn approve_agent<S: Signer + Send + Sync>(
        &self,
        signer: &S,
        agent: Address,
        name: String,
        nonce: u64,
    ) -> Result<()> {
        let signature_chain_id = self.chain.arbitrum_id().to_owned();

        let approve_agent = ApproveAgent {
            signature_chain_id,
            hyperliquid_chain: self.chain,
            agent_address: agent,
            agent_name: if name.is_empty() { None } else { Some(name) },
            nonce,
        };

        let resp = self
            .sign_and_send(signer, approve_agent, nonce, None, None)
            .await?;
        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => {
                anyhow::bail!("approve_agent: {err}")
            }
            _ => anyhow::bail!("approve_agent: unexpected response type: {resp:?}"),
        }
    }

    /// Convert account to multi-signature user.
    ///
    /// Converts a regular account to a multisig account by specifying authorized signers
    /// and the required signature threshold. After conversion, the account will require
    /// multiple signatures to execute transactions.
    ///
    /// # Parameters
    ///
    /// - `signer`: The wallet signing the conversion (must be the account owner)
    /// - `authorized_users`: List of addresses authorized to sign for the multisig
    /// - `threshold`: Minimum number of signatures required (e.g., 2 for 2-of-3)
    /// - `nonce`: The nonce for this action
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore;
    /// use alloy::primitives::address;
    /// use alloy::signers::local::PrivateKeySigner;
    ///
    /// async fn example() -> anyhow::Result<()> {
    ///     let client = hypercore::mainnet();
    ///     let signer = PrivateKeySigner::random();
    ///     let authorized_users = vec![
    ///         address!("0x1111111111111111111111111111111111111111"),
    ///         address!("0x2222222222222222222222222222222222222222"),
    ///         address!("0x3333333333333333333333333333333333333333"),
    ///     ];
    ///     let threshold = 2; // 2-of-3 multisig
    ///     let nonce = 123456789;
    ///
    ///     client.convert_to_multisig(&signer, authorized_users, threshold, nonce).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn convert_to_multisig<S: Signer + Send + Sync>(
        &self,
        signer: &S,
        authorized_users: Vec<Address>,
        threshold: usize,
        nonce: u64,
    ) -> Result<()> {
        let chain = self.chain;
        let signature_chain_id = chain.arbitrum_id().to_owned();

        let convert = ConvertToMultiSigUser {
            signature_chain_id,
            hyperliquid_chain: chain,
            signers: SignersConfig {
                authorized_users,
                threshold,
            },
            nonce,
        };

        let resp = self
            .sign_and_send(signer, convert, nonce, None, None)
            .await?;
        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => {
                anyhow::bail!("convert_to_multisig: {err}")
            }
            _ => anyhow::bail!("convert_to_multisig: unexpected response type: {resp:?}"),
        }
    }

    /// Helper function to transfer from spot core to EVM.
    pub async fn transfer_to_evm<S: Send + SignerSync>(
        &self,
        signer: &S,
        token: SpotToken,
        amount: Decimal,
        nonce: u64,
    ) -> Result<()> {
        let destination = token
            .cross_chain_address
            .ok_or_else(|| anyhow::anyhow!("token {token} doesn't have a cross chain address"))?;

        self.spot_send(
            &signer,
            SpotSend {
                destination,
                token: SendToken(token),
                amount,
                time: nonce,
            },
            nonce,
        )
        .await
    }

    /// Helper function to transfer from perps to spot.
    ///
    /// Only USDC is accepted as `token`.
    pub async fn transfer_to_spot<S: Signer + SignerSync>(
        &self,
        signer: &S,
        token: SpotToken,
        amount: Decimal,
        nonce: u64,
    ) -> Result<()> {
        if token.name != "USDC" {
            return Err(anyhow::anyhow!(
                "only USDC is accepted, tried to transfer {}",
                token.name
            ));
        }

        self.send_asset(
            signer,
            SendAsset {
                destination: signer.address(),
                source_dex: AssetTarget::Perp,
                destination_dex: AssetTarget::Spot,
                token: SendToken(token),
                from_sub_account: "".into(),
                amount,
                nonce,
            },
            nonce,
        )
        .await
    }

    /// Helper function to transfer from spot to perps.
    ///
    /// Only USDC is accepted as `token`.
    pub async fn transfer_to_perps<S: Signer + SignerSync>(
        &self,
        signer: &S,
        token: SpotToken,
        amount: Decimal,
        nonce: u64,
    ) -> Result<()> {
        if token.name != "USDC" {
            return Err(anyhow::anyhow!(
                "only USDC is accepted, tried to transfer {}",
                token.name
            ));
        }

        self.send_asset(
            signer,
            SendAsset {
                destination: signer.address(),
                source_dex: AssetTarget::Spot,
                destination_dex: AssetTarget::Perp,
                token: SendToken(token),
                from_sub_account: "".into(),
                amount,
                nonce,
            },
            nonce,
        )
        .await
    }

    /// Send USDC to another address.
    ///
    /// Perp <> Perp transfers.
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#core-usdc-transfer>
    pub async fn send_usdc<S: SignerSync>(
        &self,
        signer: &S,
        send: UsdSend,
        nonce: u64,
    ) -> Result<()> {
        let resp = self
            .sign_and_send_sync(signer, send.into_action(self.chain), nonce, None, None)
            .await?;
        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => {
                anyhow::bail!("send_usdc: {err}")
            }
            _ => anyhow::bail!("send_usdc: unexpected response type: {resp:?}"),
        }
    }

    /// Deposit or withdraw USDC from a vault.
    ///
    /// # Parameters
    ///
    /// - `signer`: The signer for signing the action
    /// - `vault_address`: The vault to deposit into or withdraw from
    /// - `usd`: Amount of USDC (e.g. `dec!(100.5)` for $100.50; converted internally to micro-units)
    /// - `nonce`: Unique nonce (typically current timestamp in milliseconds)
    /// - `is_deposit`: `true` to deposit, `false` to withdraw
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#vault-transfer>
    pub async fn vault_transfer<S: SignerSync>(
        &self,
        signer: &S,
        vault_address: Address,
        usd: Decimal,
        nonce: u64,
        is_deposit: bool,
    ) -> Result<()> {
        let usd_raw = (usd * rust_decimal::Decimal::from(1_000_000))
            .to_u64()
            .ok_or_else(|| anyhow::anyhow!("vault_transfer: usd amount out of range: {usd}"))?;
        let action = VaultTransfer { vault_address, is_deposit, usd: usd_raw };
        let resp = self
            .sign_and_send_sync(signer, action, nonce, None, None)
            .await?;
        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => anyhow::bail!("vault_transfer: {err}"),
            _ => anyhow::bail!("vault_transfer: unexpected response type: {resp:?}"),
        }
    }

    /// Send USDC to another address.
    ///
    /// Spot <> DEX or Subaccount.
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#send-asset>
    pub fn send_asset<S: SignerSync>(
        &self,
        signer: &S,
        send: SendAsset,
        nonce: u64,
    ) -> impl Future<Output = Result<()>> + Send + 'static {
        let future =
            self.sign_and_send_sync(signer, send.into_action(self.chain), nonce, None, None);

        async move {
            let resp = future.await?;
            match resp {
                Response::Ok(OkResponse::Default) => Ok(()),
                Response::Err(err) => {
                    anyhow::bail!("send_asset: {err}")
                }
                _ => anyhow::bail!("send_asset: unexpected response type: {resp:?}"),
            }
        }
    }

    /// Spot transfer.
    ///
    /// Spot <> Spot.
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#core-spot-transfer>
    pub fn spot_send<S: SignerSync>(
        &self,
        signer: &S,
        send: SpotSend,
        nonce: u64,
    ) -> impl Future<Output = Result<()>> + Send + 'static {
        let future =
            self.sign_and_send_sync(signer, send.into_action(self.chain), nonce, None, None);

        async move {
            let resp = future.await?;
            match resp {
                Response::Ok(OkResponse::Default) => Ok(()),
                Response::Err(err) => {
                    anyhow::bail!("spot send: {err}")
                }
                _ => anyhow::bail!("spot_send: unexpected response type: {resp:?}"),
            }
        }
    }

    /// Toggle big blocks or not idk.
    pub async fn evm_user_modify<S: SignerSync>(
        &self,
        signer: &S,
        toggle: bool,
        nonce: u64,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> Result<()> {
        let resp = self
            .sign_and_send_sync(
                signer,
                Action::EvmUserModify {
                    using_big_blocks: toggle,
                },
                nonce,
                vault_address,
                expires_after,
            )
            .await?;

        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => {
                anyhow::bail!("evm_user_modify: {err}")
            }
            _ => anyhow::bail!("evm_user_modify: unexpected response type: {resp:?}"),
        }
    }

    /// Invalidate a nonce.
    pub async fn noop<S: SignerSync>(
        &self,
        signer: &S,
        nonce: u64,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> Result<()> {
        let resp = self
            .sign_and_send_sync(signer, Action::Noop, nonce, vault_address, expires_after)
            .await?;

        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => {
                anyhow::bail!("noop: {err}")
            }
            _ => anyhow::bail!("noop: unexpected response type: {resp:?}"),
        }
    }

    /// Executes a multisig action on Hyperliquid.
    ///
    /// This method allows multiple signers to authorize a single action (such as placing orders,
    /// canceling orders, or transferring funds) from a multisig wallet. All provided signers must
    /// be authorized on the multisig wallet configuration.
    ///
    /// # Parameters
    ///
    /// - `lead`: The lead signer who submits the transaction to the exchange
    /// - `multi_sig_user`: The multisig wallet address that will execute the action
    /// - `signers`: Iterator of all signers whose signatures are required (typically includes the lead)
    /// - `action`: The action to execute (Order, Cancel, Transfer, etc.)
    /// - `nonce`: Unique nonce for this transaction (typically current timestamp in milliseconds)
    ///
    /// # Multisig Process
    ///
    /// 1. The action is hashed with the multisig address and lead signer
    /// 2. Each signer signs the action hash using their private key
    /// 3. All signatures are collected into a multisig payload
    /// 4. The lead signer signs the entire multisig payload
    /// 5. The signed multisig transaction is submitted to the exchange
    /// 6. The exchange verifies all signatures match the multisig wallet's authorized signers
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = hypercore::mainnet();
    ///
    /// // Parse the signers for the multisig wallet
    /// let signer1: PrivateKeySigner = "key1".parse()?;
    /// let signer2: PrivateKeySigner = "key2".parse()?;
    ///
    /// // The multisig wallet address
    /// let multisig_addr: hypersdk::Address = "0x...".parse()?;
    ///
    /// // Execute multisig operations - requires dec!() macro and timestamp
    /// // let nonce = chrono::Utc::now().timestamp_millis() as u64;
    /// // let response = client.multi_sig(&signer1, multisig_addr, nonce)
    /// //     .signer(&signer2)
    /// //     .place(order, None, None)
    /// //     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn multi_sig<'a, S: Signer + Send + Sync>(
        &'a self,
        lead: &'a S,
        multi_sig_user: Address,
        nonce: u64,
    ) -> MultiSig<'a, S> {
        MultiSig {
            lead,
            multi_sig_user,
            signers: VecDeque::new(),
            signatures: VecDeque::new(),
            client: self,
            nonce,
        }
    }

    /// Send a signed action hashing.
    fn sign_and_send_sync<S: SignerSync, A: Into<Action>>(
        &self,
        signer: &S,
        action: A,
        nonce: u64,
        maybe_vault_address: Option<Address>,
        maybe_expires_after: Option<DateTime<Utc>>,
    ) -> impl Future<Output = Result<Response>> + Send + 'static {
        let action: Action = action.into();
        let res = action.sign_sync(
            signer,
            nonce,
            maybe_vault_address,
            maybe_expires_after,
            self.chain,
        );

        let http_client = self.http_client.clone();
        let mut url = self.base_url.clone();
        url.set_path("/exchange");

        async move {
            let req = res?;
            let res = http_client.post(url).json(&req).send().await?;

            let status = res.status();
            let text = res.text().await?;

            if !status.is_success() {
                return Err(anyhow!("HTTP {status} body={text}"));
            }

            let parsed = serde_json::from_str(&text)
                .map_err(|e| anyhow!("decode failed: {e}; body={text}"))?;

            Ok(parsed)
        }
    }

    /// Send a signed action hashing.
    async fn sign_and_send<S: Signer + Send + Sync, A: Into<Action>>(
        &self,
        signer: &S,
        action: A,
        nonce: u64,
        maybe_vault_address: Option<Address>,
        maybe_expires_after: Option<DateTime<Utc>>,
    ) -> Result<Response> {
        let action: Action = action.into();
        let req = action
            .sign(
                signer,
                nonce,
                maybe_vault_address,
                maybe_expires_after,
                self.chain,
            )
            .await?;

        self.send(req).await
    }

    #[doc(hidden)]
    pub async fn send(&self, req: ActionRequest) -> Result<Response> {
        let http_client = self.http_client.clone();
        let mut url = self.base_url.clone();
        url.set_path("/exchange");

        let res = http_client
            .post(url)
            .timeout(Duration::from_secs(5))
            // .header(header::CONTENT_TYPE, "application/json")
            // .body(text)
            .json(&req)
            .send()
            .await?
            .json()
            .await?;
        Ok(res)
    }

    // TODO: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-subaccounts
}

/// Builder for constructing and executing multisig transactions on Hyperliquid.
///
/// The `MultiSig` struct provides a fluent API for building multisig transactions that require
/// multiple signers to authorize actions. It collects signatures from all required signers and
/// submits the complete multisig transaction to the exchange.
///
/// # Multisig Flow
///
/// 1. Create a `MultiSig` instance via `Client::multi_sig()`
/// 2. Add signers using `signer()` or `signers()`
/// 3. Execute an action (e.g., `place()`, `send_usdc()`)
/// 4. The builder collects signatures from all signers
/// 5. The lead signer submits the transaction
///
/// # Type Parameters
///
/// - `'a`: Lifetime of the client and signer references
/// - `S`: The signer type implementing `SignerSync + Signer`
///
/// # Example
///
/// ```rust,ignore
/// use hypersdk::hypercore::Client;
/// use alloy::signers::local::PrivateKeySigner;
///
/// let client = Client::mainnet();
/// let lead_signer: PrivateKeySigner = "0x...".parse()?;
/// let signer2: PrivateKeySigner = "0x...".parse()?;
/// let signer3: PrivateKeySigner = "0x...".parse()?;
/// let multisig_address = "0x...".parse()?;
/// let nonce = chrono::Utc::now().timestamp_millis() as u64;
///
/// // Execute a multisig order
/// let response = client
///     .multi_sig(&lead_signer, multisig_address, nonce)
///     .signer(&signer2)
///     .signer(&signer3)
///     .place(order, None, None)
///     .await?;
/// ```
///
/// # Notes
///
/// - The lead signer is the one who submits the transaction but also signs it
/// - All signers (including lead) must be authorized on the multisig wallet
/// - The order of signers should match the wallet's configuration
/// - Nonce must be unique for each transaction (typically millisecond timestamp)
pub struct MultiSig<'a, S: Signer + Send + Sync> {
    lead: &'a S,
    multi_sig_user: Address,
    signers: VecDeque<&'a S>,
    signatures: VecDeque<Signature>,
    nonce: u64,
    client: &'a Client,
}

impl<'a, S> MultiSig<'a, S>
where
    S: Signer + Send + Sync,
{
    /// Add a single signer to the multisig transaction.
    ///
    /// This method adds one signer to the list of signers who will authorize the transaction.
    /// You can chain multiple calls to add multiple signers.
    ///
    /// # Parameters
    ///
    /// - `signer`: A reference to the signer to add
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// client
    ///     .multi_sig(&lead, multisig_addr, nonce)
    ///     .signer(&signer1)
    ///     .signer(&signer2)
    ///     .signer(&signer3)
    ///     .place(order, None, None)
    ///     .await?;
    /// ```
    pub fn signer(mut self, signer: &'a S) -> Self {
        self.signers.push_back(signer);
        self
    }

    /// Add multiple signers to the multisig transaction.
    ///
    /// This method adds a collection of signers at once. More convenient than calling
    /// `signer()` multiple times when you have signers in a collection.
    ///
    /// # Parameters
    ///
    /// - `signers`: An iterable collection of signer references
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let signers = vec![&signer1, &signer2, &signer3];
    ///
    /// client
    ///     .multi_sig(&lead, multisig_addr, nonce)
    ///     .signers(signers)
    ///     .place(order, None, None)
    ///     .await?;
    /// ```
    pub fn signers(mut self, signers: impl IntoIterator<Item = &'a S>) -> Self {
        self.signers.extend(signers);
        self
    }

    /// Append pre-existing signatures to the multisig transaction.
    ///
    /// This method allows you to include signatures that were already collected separately,
    /// rather than generating them from signers. This is useful when:
    /// - Signatures were collected offline or asynchronously
    /// - You're aggregating signatures from multiple sources
    /// - You have a partial multisig that needs additional signatures
    ///
    /// The signatures should be in the same order and format as expected by the multisig
    /// wallet configuration.
    ///
    /// # Parameters
    ///
    /// - `signatures`: An iterable collection of pre-existing signatures
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use hypersdk::hypercore::types::Signature;
    ///
    /// // Signatures collected from external sources
    /// let existing_sigs: Vec<Signature> = vec![
    ///     sig1, sig2, sig3
    /// ];
    ///
    /// client
    ///     .multi_sig(&lead, multisig_addr, nonce)
    ///     .signatures(existing_sigs)
    ///     .signer(&additional_signer)  // Can still add more signers
    ///     .place(order, None, None)
    ///     .await?;
    /// ```
    ///
    /// # Notes
    ///
    /// - Signatures are appended in order to the signature list
    /// - You can mix pre-existing signatures with new signers
    /// - Ensure signatures match the action being signed and the multisig configuration
    /// - The total number of signatures must match the multisig threshold
    pub fn signatures(mut self, signatures: impl IntoIterator<Item = Signature>) -> Self {
        self.signatures.extend(signatures);
        self
    }

    /// Place orders using the multisig account.
    ///
    /// This method collects signatures from all signers for a batch order placement using
    /// RMP (MessagePack) hashing, then submits the multisig transaction to the exchange.
    ///
    /// # Process
    ///
    /// 1. Creates an RMP hash of the order action
    /// 2. Each signer signs the hash using EIP-712
    /// 3. Collects all signatures into a `MultiSigAction`
    /// 4. Lead signer submits the complete transaction
    ///
    /// # Parameters
    ///
    /// - `batch`: The batch order to place
    /// - `vault_address`: Optional vault address if trading on behalf of a vault
    /// - `expires_after`: Optional expiration time for the request
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use hypersdk::hypercore::types::{BatchOrder, OrderRequest, OrderTypePlacement, TimeInForce};
    /// use rust_decimal::dec;
    ///
    /// let order = OrderRequest {
    ///     asset: 0,
    ///     is_buy: true,
    ///     limit_px: dec!(50000),
    ///     sz: dec!(0.1),
    ///     reduce_only: false,
    ///     order_type: OrderTypePlacement::Limit {
    ///         tif: TimeInForce::Gtc,
    ///     },
    ///     cloid: [0u8; 16].into(),
    /// };
    ///
    /// let batch = BatchOrder {
    ///     orders: vec![order],
    ///     grouping: OrderGrouping::Na,
    /// };
    ///
    /// let statuses = client
    ///     .multi_sig(&lead, multisig_addr, nonce)
    ///     .signers(&signers)
    ///     .place(batch, None, None)
    ///     .await?;
    ///
    /// for status in statuses {
    ///     match status {
    ///         OrderResponseStatus::Resting { oid, .. } => {
    ///             println!("Order {} placed", oid);
    ///         }
    ///         OrderResponseStatus::Error(err) => {
    ///             eprintln!("Order failed: {}", err);
    ///         }
    ///         _ => {}
    ///     }
    /// }
    /// ```
    pub async fn place(
        &self,
        batch: BatchOrder,
        vault_address: Option<Address>,
        expires_after: Option<DateTime<Utc>>,
    ) -> Result<Vec<OrderResponseStatus>, ActionError<Cloid>> {
        let cloids: Vec<_> = batch.orders.iter().map(|req| req.cloid).collect();

        let action = multisig_collect_signatures(
            self.lead.address(),
            self.multi_sig_user,
            self.signers.iter().copied(),
            self.signatures.iter().copied(),
            Action::Order(batch),
            self.nonce,
            self.client.chain,
        )
        .await
        .map_err(|err| ActionError {
            ids: cloids.clone(),
            err: err.to_string(),
        })?;

        let resp = self
            .client
            .sign_and_send(self.lead, action, self.nonce, vault_address, expires_after)
            .await
            .map_err(|err| ActionError {
                ids: cloids.clone(),
                err: err.to_string(),
            })?;

        match resp {
            Response::Ok(OkResponse::Order { statuses }) => Ok(statuses),
            Response::Err(err) => Err(ActionError { ids: cloids, err }),
            _ => Err(ActionError {
                ids: cloids,
                err: format!("unexpected response type: {resp:?}"),
            }),
        }
    }

    /// Send USDC from the multisig account.
    ///
    /// This method collects signatures from all signers for a USDC transfer using EIP-712
    /// typed data, then submits the multisig transaction to the exchange.
    ///
    /// # Process
    ///
    /// 1. Creates EIP-712 typed data from the UsdSend action
    /// 2. Each signer signs the typed data directly using EIP-712
    /// 3. Collects all signatures into a `MultiSigAction`
    /// 4. Lead signer submits the complete transaction
    ///
    /// # Parameters
    ///
    /// - `send`: The UsdSend parameters (destination, amount, time, chain, etc.)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use hypersdk::hypercore::types::{UsdSend, Chain};
    /// use hypersdk::hypercore::ARBITRUM_SIGNATURE_CHAIN_ID;
    /// use rust_decimal::dec;
    ///
    /// let send = UsdSend {
    ///     hyperliquid_chain: Chain::Mainnet,
    ///     signature_chain_id: ARBITRUM_SIGNATURE_CHAIN_ID,
    ///     destination: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb".parse()?,
    ///     amount: dec!(100),
    ///     time: chrono::Utc::now().timestamp_millis() as u64,
    /// };
    ///
    /// client
    ///     .multi_sig(&lead_signer, multisig_address, nonce)
    ///     .signers(&signers)
    ///     .send_usdc(send)
    ///     .await?;
    ///
    /// println!("Successfully sent 100 USDC from multisig account");
    /// ```
    ///
    /// # Notes
    ///
    /// - Uses EIP-712 typed data signatures (different from order placement which uses RMP)
    /// - Time should typically be the current timestamp in milliseconds
    /// - Destination can be any valid Ethereum address
    /// - Amount is in USDC (6 decimals on-chain, but use regular decimal representation)
    pub async fn send_usdc(&self, send: UsdSend) -> Result<()> {
        let nonce = send.time;
        let action = multisig_collect_signatures(
            self.lead.address(),
            self.multi_sig_user,
            self.signers.iter().copied(),
            self.signatures.iter().copied(),
            send.into_action(self.client.chain()).into(),
            nonce,
            self.client.chain,
        )
        .await?;

        let resp = self
            .client
            .sign_and_send(self.lead, action, self.nonce, None, None)
            .await?;

        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => anyhow::bail!("send_usdc: {err}"),
            _ => anyhow::bail!("send_usdc: unexpected response type: {resp:?}"),
        }
    }

    /// Send assets from the multisig account.
    ///
    /// This method collects signatures from all signers for an asset transfer using EIP-712
    /// typed data, then submits the multisig transaction to the exchange. This can be used
    /// to transfer assets between different destinations (accounts, DEXes, subaccounts).
    ///
    /// # Process
    ///
    /// 1. Creates EIP-712 typed data from the SendAsset action
    /// 2. Each signer signs the typed data directly using EIP-712
    /// 3. Collects all signatures into a `MultiSigAction`
    /// 4. Lead signer submits the complete transaction
    ///
    /// # Parameters
    ///
    /// - `send`: The SendAsset parameters (destination, token, amount, source/dest DEX, etc.)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use hypersdk::hypercore::types::{SendAsset, SendToken};
    /// use hypersdk::hypercore::ARBITRUM_MAINNET_CHAIN_ID;
    /// use rust_decimal::dec;
    ///
    /// // Get the token info first
    /// let tokens = client.spot_meta().await?;
    /// let usdc = tokens.iter().find(|t| t.name == "USDC").unwrap();
    ///
    /// let send = SendAsset {
    ///     hyperliquid_chain: Chain::Mainnet,
    ///     signature_chain_id: ARBITRUM_MAINNET_CHAIN_ID,
    ///     destination: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb".parse()?,
    ///     source_dex: "".to_string(),      // Empty for perp balance
    ///     destination_dex: "".to_string(), // Empty for recipient's perp balance
    ///     token: SendToken(usdc.clone()),
    ///     from_sub_account: "".to_string(), // Empty for main account
    ///     amount: dec!(100),
    ///     nonce: chrono::Utc::now().timestamp_millis() as u64,
    /// };
    ///
    /// client
    ///     .multi_sig(&lead_signer, multisig_address, nonce)
    ///     .signers(&signers)
    ///     .send_asset(send)
    ///     .await?;
    ///
    /// println!("Successfully sent 100 USDC from multisig account");
    /// ```
    ///
    /// # Notes
    ///
    /// - Uses EIP-712 typed data signatures (different from order placement which uses RMP)
    /// - Source/destination DEX can be: "" (perp balance), "spot", or other DEX identifiers
    /// - Token must be obtained from `spot_meta()` API call
    /// - Nonce should be unique for each transaction (typically current timestamp in ms)
    pub async fn send_asset(&self, send: SendAsset) -> Result<()> {
        let nonce = send.nonce;
        let action = multisig_collect_signatures(
            self.lead.address(),
            self.multi_sig_user,
            self.signers.iter().copied(),
            self.signatures.iter().copied(),
            send.into_action(self.client.chain()).into(),
            nonce,
            self.client.chain,
        )
        .await?;

        let resp = self
            .client
            .sign_and_send(self.lead, action, self.nonce, None, None)
            .await?;

        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => anyhow::bail!("send_asset: {err}"),
            _ => anyhow::bail!("send_asset: unexpected response type: {resp:?}"),
        }
    }

    /// Approve a new agent for the multisig account.
    ///
    /// Approves an agent to act on behalf of the multisig account. An account can have:
    /// - 1 unnamed approved wallet
    /// - Up to 3 named agents
    /// - 2 named agents per subaccount
    ///
    /// # Parameters
    ///
    /// - `agent`: The address of the agent to approve
    /// - `name`: The name for the agent (or empty string for unnamed)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let agent = address!("0x97271b6b7f3b23a2f4700ae671b05515ae5c3319");
    /// let name = "my_agent".to_string();
    ///
    /// client
    ///     .multi_sig(&lead, multisig_addr, nonce)
    ///     .signer(&signer1)
    ///     .signer(&signer2)
    ///     .approve_agent(agent, name)
    ///     .await?;
    /// ```
    pub async fn approve_agent(&self, agent: Address, name: String) -> Result<()> {
        let chain = self.client.chain;
        let signature_chain_id = chain.arbitrum_id().to_owned();

        let approve_agent = ApproveAgent {
            signature_chain_id,
            hyperliquid_chain: chain,
            agent_address: agent,
            agent_name: if name.is_empty() { None } else { Some(name) },
            nonce: self.nonce,
        };

        let action = multisig_collect_signatures(
            self.lead.address(),
            self.multi_sig_user,
            self.signers.iter().copied(),
            self.signatures.iter().copied(),
            Action::ApproveAgent(approve_agent),
            self.nonce,
            self.client.chain,
        )
        .await?;

        let resp = self
            .client
            .sign_and_send(self.lead, action, self.nonce, None, None)
            .await?;

        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => anyhow::bail!("approve_agent: {err}"),
            _ => anyhow::bail!("approve_agent: unexpected response type: {resp:?}"),
        }
    }

    /// Convert multisig account back to normal user.
    ///
    /// Converts the multisig account back to a regular single-signer account by setting
    /// the signers to null. After conversion, the account will only require a single
    /// signature to execute transactions.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// client
    ///     .multi_sig(&lead, multisig_addr, nonce)
    ///     .signer(&signer1)
    ///     .signer(&signer2)
    ///     .convert_to_normal_user()
    ///     .await?;
    /// ```
    pub async fn convert_to_normal_user(&self) -> Result<()> {
        let chain = self.client.chain;

        let convert = ConvertToMultiSigUser {
            signature_chain_id: chain.arbitrum_id().to_owned(),
            hyperliquid_chain: chain,
            signers: SignersConfig {
                authorized_users: vec![], // Empty vec serializes to "null"
                threshold: 0,
            },
            nonce: self.nonce,
        };

        let action = multisig_collect_signatures(
            self.lead.address(),
            self.multi_sig_user,
            self.signers.iter().copied(),
            self.signatures.iter().copied(),
            Action::ConvertToMultiSigUser(convert),
            self.nonce,
            self.client.chain,
        )
        .await?;

        let resp = self
            .client
            .sign_and_send(self.lead, action, self.nonce, None, None)
            .await?;

        match resp {
            Response::Ok(OkResponse::Default) => Ok(()),
            Response::Err(err) => anyhow::bail!("convert_to_normal_user: {err}"),
            _ => anyhow::bail!("convert_to_normal_user: unexpected response type: {resp:?}"),
        }
    }
}