maxt 0.3.3

One Rust API for Upbit, Bithumb, Binance, and Hyperliquid market data, accounts, and orders.
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
//! Hyperliquid spot and perpetual market adapter.

mod native;
mod parse;
mod rest;
mod sign;
mod stream;

use std::fmt;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};

use futures_core::Stream;
use futures_util::StreamExt;
use rust_decimal::Decimal;
use tokio::sync::{Mutex, OnceCell};

use crate::adapter::{Adapter, BoxFuture};
use crate::error::{Error, Result};
use crate::feature::Feature;
use crate::request::{
    CandleRequest, HistoryRequest, MarginRequest, OrderRequest, TransferHistoryRequest,
};
use crate::stream::{AccountStream, MarketStream, TypedStream};
use crate::transport::{HttpTransport, WsCommand, WsConnect, ws};
use crate::types::{
    AccountEvent, Balance, Candle, Cursor, Deposit, Exchange, FundingPayment, FundingRate,
    MarginSummary, Market, MarketEvent, MarketInfo, MarketKind, Order, OrderBook, Page, Position,
    StreamConfig, Subscription, Ticker, Timestamp, Trade, Withdrawal,
};

use parse::Universe;

#[allow(unused_imports)]
pub use native::{
    HyperliquidAccountEvent, HyperliquidAssetContext, HyperliquidAssetContextEvent,
    HyperliquidBookLevel, HyperliquidCandleEvent, HyperliquidCandleSnapshot,
    HyperliquidDailyVolume, HyperliquidEvmContract, HyperliquidFundingHistoryEntry,
    HyperliquidL2Book, HyperliquidLedgerEntry, HyperliquidLedgerKind, HyperliquidMarketEvent,
    HyperliquidOpenOrder, HyperliquidOrderBookEvent, HyperliquidOrderDetail, HyperliquidOrderInfo,
    HyperliquidOrderReference, HyperliquidOrderStatusResponse, HyperliquidOrderUpdate,
    HyperliquidPortfolioPeriod, HyperliquidPortfolioPoint, HyperliquidRecentTrade,
    HyperliquidReferral, HyperliquidReferrer, HyperliquidSpotAssetContext, HyperliquidSpotBalance,
    HyperliquidSpotClearinghouseState, HyperliquidSpotMeta, HyperliquidSpotMetaAndAssetContexts,
    HyperliquidSpotPair, HyperliquidSpotStateBalance, HyperliquidSpotStateEvent,
    HyperliquidSpotToken, HyperliquidSubAccount, HyperliquidTradeEvent, HyperliquidUserFees,
    HyperliquidUserFill, HyperliquidUserFunding, HyperliquidUserRateLimit, HyperliquidUserRole,
    HyperliquidVaultEquity,
};

/// Hyperliquid's current mid price for one market.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HyperliquidMidPrice {
    /// The market this mid price describes.
    pub market: Market,
    /// The current mid price in the market's quote asset.
    pub price: Decimal,
}

/// Hyperliquid's complete default-universe `allMids` response.
///
/// [`Self::mids`] contains markets modeled by this adapter. [`Self::raw_json`]
/// preserves the provider map, including entries outside the adapter's default
/// universe, without treating those entries as supported markets.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HyperliquidAllMids {
    /// Prices resolved to the adapter's supported markets.
    pub mids: Vec<HyperliquidMidPrice>,
    /// Complete provider response object encoded as JSON.
    pub raw_json: String,
}

/// A complete Hyperliquid provider response whose native shape has no stable
/// portable equivalent.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HyperliquidProviderResponse {
    /// Complete provider response encoded as JSON.
    pub raw_json: String,
}

/// A Hyperliquid order-action response with its portable order projection.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HyperliquidOrderActionResponse {
    /// Portable order projection returned from the action acknowledgement.
    pub common: Order,
    /// Complete provider response encoded as JSON.
    pub raw_json: String,
}

pub(crate) const MAINNET_REST_BASE_URL: &str = "https://api.hyperliquid.xyz";
pub(crate) const MAINNET_WEBSOCKET_URL: &str = "wss://api.hyperliquid.xyz/ws";
pub(crate) const TESTNET_REST_BASE_URL: &str = "https://api.hyperliquid-testnet.xyz";
pub(crate) const TESTNET_WEBSOCKET_URL: &str = "wss://api.hyperliquid-testnet.xyz/ws";

static LAST_NONCE: AtomicU64 = AtomicU64::new(0);
// ponytail: one process-wide lane prevents nonce reordering; split it into
// per-signer queues only if signed-action throughput becomes a bottleneck.
static SIGNED_ACTION_LANE: Mutex<()> = Mutex::const_new(());

/// Adapter for Hyperliquid spot and default perpetual markets.
///
/// Public market-data calls do not require configuration. Public account reads
/// use [`HyperliquidAdapter::with_query_address`]; signed actions use
/// [`HyperliquidAdapter::with_signer`]. [`HyperliquidAdapter::with_wallet`]
/// configures both for compatibility and convenience.
///
/// Markets are loaded from `meta` and `spotMeta`. HIP-3 DEXes and outcome
/// markets are not exposed by this adapter.
///
/// [`Client::trades`](crate::Client::trades) uses `recentTrades`, which exposes
/// at most ten recent executions and no historical range.
/// [`Feed::Trades`](crate::Feed::Trades) provides live updates but may have a
/// gap after reconnection.
///
/// [`Ticker::last_price`](crate::Ticker::last_price) uses `midPx`, falling back
/// to `markPx`; it is not the latest execution price. Use the trades API when
/// an execution price and trade time are required.
///
/// Provider-specific data is available through the account Info methods,
/// [`HyperliquidAdapter::non_funding_ledger`], and
/// [`HyperliquidAdapter::asset_context`].
#[derive(Debug, Clone)]
pub struct HyperliquidAdapter {
    network: HyperliquidNetwork,
    query_address: Option<String>,
    signer: Option<HyperliquidSigner>,
    connection: OnceCell<Connection>,
}

/// A full-fidelity Hyperliquid market subscription.
///
/// It yields [`HyperliquidMarketEvent`] values and uses the same connection,
/// reconnect, buffering, and close rules as [`MarketStream`]. Use
/// [`HyperliquidAdapter::subscribe_detailed`] to construct one.
pub struct HyperliquidMarketStream {
    inner: TypedStream<HyperliquidMarketEvent>,
}

impl HyperliquidMarketStream {
    fn new_with_close<F, Fut>(
        inner: impl Stream<Item = Result<HyperliquidMarketEvent>> + Send + 'static,
        close: F,
    ) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: std::future::Future<Output = Result<()>> + Send + 'static,
    {
        Self {
            inner: TypedStream::new_with_close(inner, close),
        }
    }

    /// Stops this subscription and waits for the WebSocket to close.
    pub async fn close(&mut self) -> Result<()> {
        self.inner.close().await
    }
}

impl Stream for HyperliquidMarketStream {
    type Item = Result<HyperliquidMarketEvent>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(cx)
    }
}

impl fmt::Debug for HyperliquidMarketStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HyperliquidMarketStream")
            .finish_non_exhaustive()
    }
}

/// A full-fidelity Hyperliquid account subscription.
///
/// It yields [`HyperliquidAccountEvent`] values and uses the same connection,
/// reconnect, buffering, and close rules as [`AccountStream`]. Use
/// [`HyperliquidAdapter::subscribe_detailed_account`] to construct one.
pub struct HyperliquidAccountStream {
    inner: TypedStream<HyperliquidAccountEvent>,
}

impl HyperliquidAccountStream {
    fn new_with_close<F, Fut>(
        inner: impl Stream<Item = Result<HyperliquidAccountEvent>> + Send + 'static,
        close: F,
    ) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: std::future::Future<Output = Result<()>> + Send + 'static,
    {
        Self {
            inner: TypedStream::new_with_close(inner, close),
        }
    }

    /// Stops this subscription and waits for the WebSocket to close.
    pub async fn close(&mut self) -> Result<()> {
        self.inner.close().await
    }
}

impl Stream for HyperliquidAccountStream {
    type Item = Result<HyperliquidAccountEvent>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(cx)
    }
}

impl fmt::Debug for HyperliquidAccountStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HyperliquidAccountStream")
            .finish_non_exhaustive()
    }
}

/// Lazily initialized HTTP transport and cached `meta`/`spotMeta` symbol table.
/// A new adapter is required to refresh listed markets.
#[derive(Debug, Clone)]
struct Connection {
    http: HttpTransport,
    universe: Universe,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) enum HyperliquidNetwork {
    #[default]
    Mainnet,
    Testnet,
}

#[derive(Clone)]
pub(crate) struct HyperliquidSigner {
    pub(crate) private_key: String,
}

// Keeps the signing key out of logs and panic messages.
impl std::fmt::Debug for HyperliquidSigner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HyperliquidSigner")
            .field("private_key", &"<redacted>")
            .finish()
    }
}

impl HyperliquidAdapter {
    /// An adapter for public mainnet market data.
    pub fn new() -> Self {
        Self::on(HyperliquidNetwork::Mainnet)
    }

    /// An adapter for public testnet market data.
    pub fn testnet() -> Self {
        Self::on(HyperliquidNetwork::Testnet)
    }

    fn on(network: HyperliquidNetwork) -> Self {
        Self {
            network,
            query_address: None,
            signer: None,
            connection: OnceCell::new(),
        }
    }

    /// Configures an account address for public account-data queries.
    ///
    /// Hyperliquid's Info API requires the public master or subaccount address,
    /// but no signature. The value is validated when an account read is made.
    #[must_use]
    pub fn with_query_address(mut self, address: impl Into<String>) -> Self {
        self.query_address = Some(address.into());
        self
    }

    /// Configures the local key used only for signed actions.
    ///
    /// This may be an approved API-wallet key and therefore does not identify
    /// the account queried by the Info API. The key is redacted from [`Debug`]
    /// output and validated before any network request is made. Use a separate
    /// API wallet for each process; Hyperliquid tracks nonces by signer.
    #[must_use]
    pub fn with_signer(mut self, private_key: impl Into<String>) -> Self {
        self.signer = Some(HyperliquidSigner {
            private_key: private_key.into(),
        });
        self
    }

    /// Configures the public query address and local signer together.
    ///
    /// `address` is the account acted on. `private_key` is either that account's
    /// key or an approved API wallet key. The key is used only for local signing
    /// and is redacted from [`Debug`] output.
    ///
    /// The address may be the master account while `private_key` belongs to an
    /// approved API wallet. This is equivalent to calling
    /// [`HyperliquidAdapter::with_query_address`] and
    /// [`HyperliquidAdapter::with_signer`].
    #[must_use]
    pub fn with_wallet(self, address: impl Into<String>, private_key: impl Into<String>) -> Self {
        self.with_query_address(address).with_signer(private_key)
    }

    /// Whether this adapter talks to testnet.
    pub fn is_testnet(&self) -> bool {
        self.network == HyperliquidNetwork::Testnet
    }

    pub(crate) fn has_query_address(&self) -> bool {
        self.query_address.is_some()
    }

    pub(crate) fn has_signer(&self) -> bool {
        self.signer.is_some()
    }

    fn next_nonce(&self, now: Timestamp) -> Result<u64> {
        let now = u64::try_from(now.as_millis())
            .map_err(|_| Error::adapter("hyperliquid nonce clock predates the Unix epoch"))?;
        let previous = LAST_NONCE
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |last| {
                last.checked_add(1).map(|next| now.max(next))
            })
            .map_err(|_| Error::adapter("hyperliquid nonce counter is exhausted"))?;
        Ok(now.max(previous + 1))
    }

    pub(crate) fn rest_base_url(&self) -> &'static str {
        match self.network {
            HyperliquidNetwork::Mainnet => MAINNET_REST_BASE_URL,
            HyperliquidNetwork::Testnet => TESTNET_REST_BASE_URL,
        }
    }

    pub(crate) fn websocket_url(&self) -> &'static str {
        match self.network {
            HyperliquidNetwork::Mainnet => MAINNET_WEBSOCKET_URL,
            HyperliquidNetwork::Testnet => TESTNET_WEBSOCKET_URL,
        }
    }

    /// Reads account-wide non-funding ledger entries.
    ///
    /// Entries include deposits, withdrawals, transfers, and liquidations. They
    /// are distinct from market-scoped [`FundingPayment`](crate::FundingPayment)
    /// records. See [`HyperliquidLedgerEntry`].
    ///
    /// Pass [`Page::next`] back as `cursor` until it is `None`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`](crate::Error::Auth) when no valid query address
    /// is configured. Invalid cursors, transport failures, exchange errors, and
    /// payload changes are also returned.
    pub async fn non_funding_ledger(
        &self,
        from: Option<Timestamp>,
        to: Option<Timestamp>,
        cursor: Option<&Cursor>,
        limit: Option<u32>,
    ) -> Result<Page<HyperliquidLedgerEntry>> {
        rest::validate_page_limit(limit)?;
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::ledger(&connection.http, &user, from, to, cursor, limit).await
    }

    /// Reads the configured account's current Info API request allowance.
    ///
    /// This is a public account read: it needs an address but no signature.
    pub async fn user_rate_limit(&self) -> Result<HyperliquidUserRateLimit> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::user_rate_limit(&connection.http, &user).await
    }

    /// Reads the configured account's Hyperliquid role.
    ///
    /// Unknown provider role names remain available as
    /// [`HyperliquidUserRole::Other`]. This is a public account read and does
    /// not use the local signer.
    pub async fn user_role(&self) -> Result<HyperliquidUserRole> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::user_role(&connection.http, &user).await
    }

    /// Reads the configured account's referral state.
    ///
    /// Stable balances are parsed exactly; provider-owned nested program state
    /// remains JSON so an added referral stage does not discard data.
    pub async fn referral(&self) -> Result<HyperliquidReferral> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::referral(&connection.http, &user).await
    }

    /// Reads the configured account's fee schedule and current fee rates.
    ///
    /// The full provider fee schedule is retained because Hyperliquid can add
    /// product tiers independently of the common order-fee model.
    pub async fn user_fees(&self) -> Result<HyperliquidUserFees> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::user_fees(&connection.http, &user).await
    }

    /// Reads the configured account's portfolio history by provider period.
    pub async fn portfolio(&self) -> Result<Vec<HyperliquidPortfolioPeriod>> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::portfolio(&connection.http, &user).await
    }

    /// Reads the configured account's subaccounts.
    ///
    /// Hyperliquid returns `null` when an account has none; this method returns
    /// an empty list for that documented absence.
    pub async fn sub_accounts(&self) -> Result<Vec<HyperliquidSubAccount>> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::sub_accounts(&connection.http, &user).await
    }

    /// Reads the configured account's current vault equity positions.
    pub async fn user_vault_equities(&self) -> Result<Vec<HyperliquidVaultEquity>> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::user_vault_equities(&connection.http, &user).await
    }

    /// Reads the configured account's most recent fills.
    ///
    /// Hyperliquid returns at most 2,000 fills. Set `aggregate_by_time` to
    /// combine eligible partial fills using Hyperliquid's documented rule.
    /// The provider-specific [`HyperliquidUserFill`] preserves execution,
    /// account-position, fee, and raw provider data without widening the
    /// common [`Trade`](crate::Trade) contract.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`](crate::Error::Auth) before any network request
    /// when no valid query address is configured.
    pub async fn user_fills(&self, aggregate_by_time: bool) -> Result<Vec<HyperliquidUserFill>> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::user_fills(&connection.http, &user, aggregate_by_time).await
    }

    /// Reads the configured account's fills in the inclusive provider time range.
    ///
    /// `from` maps to Hyperliquid's required `startTime`; `to`, when present,
    /// maps to its optional inclusive `endTime`. Hyperliquid returns at most
    /// 2,000 fills per response and retains only its 10,000 most recent fills.
    /// Set `aggregate_by_time` to use the provider's partial-fill aggregation.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`](crate::Error::Auth) before any network request
    /// when no valid query address is configured.
    pub async fn user_fills_by_time(
        &self,
        from: Timestamp,
        to: Option<Timestamp>,
        aggregate_by_time: bool,
    ) -> Result<Vec<HyperliquidUserFill>> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::user_fills_by_time(&connection.http, &user, from, to, aggregate_by_time).await
    }

    /// Reads the configured account's compact `openOrders` response.
    ///
    /// This provider-specific method is deliberately named `basic_open_orders`
    /// to distinguish it from the common open-order API, which uses the richer
    /// `frontendOpenOrders` response.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`](crate::Error::Auth) before any network request
    /// when no valid query address is configured.
    pub async fn basic_open_orders(&self) -> Result<Vec<HyperliquidOpenOrder>> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::basic_open_orders(&connection.http, &user).await
    }

    /// Queries one order by server order id or 16-byte client order id.
    ///
    /// Hyperliquid's documented `unknownOid` response is returned as
    /// [`HyperliquidOrderStatusResponse::UnknownOrder`], not as an error.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`](crate::Error::Auth) before any network request
    /// when no valid query address is configured. Malformed client order ids
    /// return [`Error::InvalidRequest`](crate::Error::InvalidRequest).
    pub async fn order_status(
        &self,
        reference: HyperliquidOrderReference,
    ) -> Result<HyperliquidOrderStatusResponse> {
        let user = self.query_address()?;
        rest::validate_order_reference(&reference)?;
        let connection = self.connect().await?;

        rest::order_status(&connection.http, &user, &reference).await
    }

    /// Reads up to Hyperliquid's 2,000 most recent historical orders.
    ///
    /// Status and order enum strings remain in their provider spelling, and
    /// each record retains the full response object as JSON.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`](crate::Error::Auth) before any network request
    /// when no valid query address is configured.
    pub async fn historical_orders(&self) -> Result<Vec<HyperliquidOrderInfo>> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::historical_orders(&connection.http, &user).await
    }

    /// Reads the current asset context for one market.
    ///
    /// The context includes mid, mark, and oracle prices; the current funding
    /// rate; open interest; and order precision. Historical market-rate
    /// observations use [`FundingRate`](crate::FundingRate), while actual
    /// account charges use [`FundingPayment`](crate::FundingPayment). See
    /// [`HyperliquidAssetContext`].
    ///
    /// # Errors
    ///
    /// Returns an error for an unlisted or non-Hyperliquid market, a transport
    /// or exchange failure, or an invalid response payload.
    pub async fn asset_context(&self, market: &Market) -> Result<HyperliquidAssetContext> {
        let connection = self.connect().await?;
        let raw = rest::context(&connection.http, &connection.universe, market).await?;
        let asset = connection.universe.asset(market)?;

        native::asset_context(&raw, asset)
    }

    /// Reads one raw candle snapshot window with Hyperliquid's trade count intact.
    ///
    /// `interval` must use Hyperliquid's documented spelling such as `"1m"`.
    /// `from` is required and maps to `startTime`; `to`, when supplied, maps
    /// to the provider's inclusive `endTime`.
    pub async fn candle_snapshot(
        &self,
        market: &Market,
        interval: &str,
        from: Timestamp,
        to: Option<Timestamp>,
    ) -> Result<Vec<HyperliquidCandleSnapshot>> {
        if to.is_some_and(|to| to < from) {
            return Err(Error::invalid_request(
                "to",
                "must not be earlier than `from`",
            ));
        }
        let connection = self.connect().await?;
        let native = connection.universe.native_symbol(market)?;

        rest::candle_snapshot(
            &connection.http,
            &connection.universe,
            native,
            interval,
            from.as_millis(),
            to.map(Timestamp::as_millis),
        )
        .await
    }

    /// Reads an L2 snapshot with Hyperliquid's order count for every level.
    pub async fn l2_book(&self, market: &Market) -> Result<HyperliquidL2Book> {
        let connection = self.connect().await?;

        rest::l2_book(&connection.http, &connection.universe, market).await
    }

    /// Reads the provider's recent trades without dropping hashes or account lists.
    ///
    /// Hyperliquid returns at most ten entries and accepts no count parameter.
    pub async fn recent_trades(&self, market: &Market) -> Result<Vec<HyperliquidRecentTrade>> {
        let connection = self.connect().await?;

        rest::recent_trades(&connection.http, &connection.universe, market).await
    }

    /// Reads historical funding observations with Hyperliquid's premium index.
    ///
    /// The supplied time bounds map directly to Hyperliquid's millisecond
    /// `startTime` and optional inclusive `endTime`.
    pub async fn funding_history(
        &self,
        market: &Market,
        from: Timestamp,
        to: Option<Timestamp>,
    ) -> Result<Vec<HyperliquidFundingHistoryEntry>> {
        if to.is_some_and(|to| to < from) {
            return Err(Error::invalid_request(
                "to",
                "must not be earlier than `from`",
            ));
        }
        let connection = self.connect().await?;

        rest::funding_history(&connection.http, &connection.universe, market, from, to).await
    }

    /// Reads account funding records with position size and sample count intact.
    ///
    /// This is a public account read and needs a configured query address, not
    /// a signing key.
    pub async fn user_funding(
        &self,
        from: Timestamp,
        to: Option<Timestamp>,
    ) -> Result<Vec<HyperliquidUserFunding>> {
        if to.is_some_and(|to| to < from) {
            return Err(Error::invalid_request(
                "to",
                "must not be earlier than `from`",
            ));
        }
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::user_funding(&connection.http, &connection.universe, &user, from, to).await
    }

    /// Reads the configured account's spot state with entry notional intact.
    pub async fn spot_clearinghouse_state(&self) -> Result<HyperliquidSpotClearinghouseState> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::spot_clearinghouse_state(&connection.http, &user).await
    }

    /// Reads all spot token and pair metadata without narrowing provider fields.
    pub async fn spot_meta(&self) -> Result<HyperliquidSpotMeta> {
        let connection = self.connect().await?;

        rest::spot_meta(&connection.http).await
    }

    /// Reads spot metadata and asset contexts without dropping supply fields.
    pub async fn spot_meta_and_asset_contexts(
        &self,
    ) -> Result<HyperliquidSpotMetaAndAssetContexts> {
        let connection = self.connect().await?;

        rest::spot_meta_and_asset_contexts(&connection.http).await
    }

    /// Reads the current mid price for every market in the default universe.
    ///
    /// Hyperliquid's `allMids` Info API uses the first perpetual DEX when no
    /// `dex` is supplied, and includes spot mids in that response. The
    /// returned price may fall back to the latest trade when a book is empty;
    /// the endpoint does not attach a timestamp.
    ///
    /// HIP-3 DEX markets are not included because this adapter's market table
    /// intentionally covers only the default perpetual and spot universes.
    pub async fn all_mids(&self) -> Result<Vec<HyperliquidMidPrice>> {
        self.all_mids_detail().await.map(|response| response.mids)
    }

    /// Reads current mids while preserving Hyperliquid's complete provider map.
    pub async fn all_mids_detail(&self) -> Result<HyperliquidAllMids> {
        let connection = self.connect().await?;

        rest::all_mids_detail(&connection.http, &connection.universe).await
    }

    /// Reads the complete perpetual `meta` response without narrowing it to
    /// the portable market-list contract.
    pub async fn perpetual_meta(&self) -> Result<HyperliquidProviderResponse> {
        let connection = self.connect().await?;

        rest::perpetual_meta(&connection.http).await
    }

    /// Reads the complete perpetual `metaAndAssetCtxs` response without
    /// narrowing it to portable ticker fields.
    pub async fn perpetual_meta_and_asset_contexts(&self) -> Result<HyperliquidProviderResponse> {
        let connection = self.connect().await?;

        rest::perpetual_meta_and_asset_contexts(&connection.http).await
    }

    /// Reads the complete perpetual clearinghouse state for the configured
    /// public query address.
    pub async fn clearinghouse_state_detail(&self) -> Result<HyperliquidProviderResponse> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::clearinghouse_state(&connection.http, &user).await
    }

    /// Reads the complete `frontendOpenOrders` response for the configured
    /// public query address.
    pub async fn frontend_open_orders_detail(&self) -> Result<HyperliquidProviderResponse> {
        let user = self.query_address()?;
        let connection = self.connect().await?;

        rest::frontend_open_orders(&connection.http, &user).await
    }

    /// Places an order while retaining the complete signed action response.
    pub async fn place_order_detail(
        &self,
        request: &OrderRequest,
    ) -> Result<HyperliquidOrderActionResponse> {
        let private_key = self.signing_key()?;
        let connection = self.connect().await?;
        let _lane = SIGNED_ACTION_LANE.lock().await;
        let nonce = self.next_nonce(Timestamp::now())?;

        rest::place_order_detail(
            &connection.http,
            &connection.universe,
            private_key,
            self.network,
            request,
            nonce,
        )
        .await
    }

    /// Cancels an order while retaining the complete signed action response.
    pub async fn cancel_order_detail(
        &self,
        market: &Market,
        order_id: &str,
    ) -> Result<HyperliquidProviderResponse> {
        let private_key = self.signing_key()?;
        let connection = self.connect().await?;
        let _lane = SIGNED_ACTION_LANE.lock().await;
        let nonce = self.next_nonce(Timestamp::now())?;

        rest::cancel_order_detail(
            &connection.http,
            &connection.universe,
            private_key,
            self.network,
            market,
            order_id,
            nonce,
        )
        .await
    }

    /// Opens a full-fidelity market subscription with default connection settings.
    ///
    /// The returned events retain the documented Hyperliquid fields that the
    /// portable [`MarketStream`] deliberately omits. Use
    /// [`Self::subscribe_detailed_with`] to set reconnect and buffering rules.
    pub async fn subscribe_detailed(
        &self,
        subscription: &Subscription,
    ) -> Result<HyperliquidMarketStream> {
        self.subscribe_detailed_with(subscription, &crate::client::default_stream_config())
            .await
    }

    /// Opens a full-fidelity market subscription with explicit connection settings.
    pub async fn subscribe_detailed_with(
        &self,
        subscription: &Subscription,
        config: &StreamConfig,
    ) -> Result<HyperliquidMarketStream> {
        let connection = self.connect().await?;
        let frames = stream::subscribe_frames(subscription, &connection.universe)?;
        let session = ws::connect(
            WsConnect {
                url: self.websocket_url().to_string(),
                headers: None,
                subscribe: WsConnect::fixed(frames),
                heartbeat: Some(stream::HEARTBEAT),
            },
            config,
        )
        .await?;
        let close = session.close_handle();
        let universe = connection.universe.clone();
        let mut decoder = stream::DetailedDecoder::default();

        Ok(HyperliquidMarketStream::new_with_close(
            session.flat_map(move |command| {
                futures_util::stream::iter(detailed_market_events(command, &universe, &mut decoder))
            }),
            move || async move { close.close().await },
        ))
    }

    /// Opens a full-fidelity account subscription with default connection settings.
    ///
    /// This public account read needs a configured query address, but no local
    /// signature. Use [`Self::subscribe_detailed_account_with`] to set
    /// reconnect and buffering rules.
    pub async fn subscribe_detailed_account(&self) -> Result<HyperliquidAccountStream> {
        self.subscribe_detailed_account_with(&crate::client::default_stream_config())
            .await
    }

    /// Opens a full-fidelity account subscription with explicit connection settings.
    pub async fn subscribe_detailed_account_with(
        &self,
        config: &StreamConfig,
    ) -> Result<HyperliquidAccountStream> {
        let user = self.query_address()?;
        let connection = self.connect().await?;
        let session = ws::connect(
            WsConnect {
                url: self.websocket_url().to_string(),
                headers: None,
                subscribe: WsConnect::fixed(stream::account_subscribe_frames(&user)),
                heartbeat: Some(stream::HEARTBEAT),
            },
            config,
        )
        .await?;
        let close = session.close_handle();
        let universe = connection.universe.clone();

        Ok(HyperliquidAccountStream::new_with_close(
            session.flat_map(move |command| {
                futures_util::stream::iter(detailed_account_events(command, &universe))
            }),
            move || async move { close.close().await },
        ))
    }

    /// Initializes the HTTP client and symbol table once.
    async fn connect(&self) -> Result<&Connection> {
        self.connection
            .get_or_try_init(|| async {
                let http = HttpTransport::new(self.rest_base_url())?;
                let universe = rest::universe(&http).await?;

                Ok(Connection { http, universe })
            })
            .await
    }

    /// Returns the normalized address used by public account reads.
    fn query_address(&self) -> Result<String> {
        let address = self
            .query_address
            .as_deref()
            .ok_or_else(sign::missing_query_address)?;

        sign::check_address(address)
    }

    fn signing_key(&self) -> Result<&str> {
        let private_key = self
            .signer
            .as_ref()
            .map(|signer| signer.private_key.as_str())
            .ok_or_else(sign::missing_signer)?;
        sign::signing_key(private_key)?;

        Ok(private_key)
    }
}

impl Default for HyperliquidAdapter {
    fn default() -> Self {
        Self::new()
    }
}

impl Adapter for HyperliquidAdapter {
    fn exchange(&self) -> Exchange {
        Exchange::Hyperliquid
    }

    fn supports(&self, feature: Feature) -> bool {
        match feature {
            Feature::AssetNetworks
            | Feature::DepositAddresses
            | Feature::DepositLookup
            | Feature::TravelRule
            | Feature::WithdrawalQuotes
            | Feature::Withdrawals
            | Feature::WithdrawalLookup
            | Feature::WithdrawalCancellation
            | Feature::OrderHistory => false,
            Feature::Balances
            | Feature::DepositHistory
            | Feature::WithdrawalHistory
            | Feature::OpenOrders
            | Feature::AccountStream
            | Feature::Positions
            | Feature::Margin
            | Feature::FundingPayments => self.has_query_address(),
            Feature::Trading | Feature::MarginConfig | Feature::ReduceOnlyOrders => {
                self.has_signer()
            }
            _ => true,
        }
    }

    fn trades(&self, market: &Market, limit: Option<u32>) -> BoxFuture<'_, Result<Vec<Trade>>> {
        let market = market.clone();
        Box::pin(async move {
            let connection = self.connect().await?;

            rest::trades(&connection.http, &connection.universe, &market, limit).await
        })
    }

    fn markets(&self, kind: MarketKind) -> BoxFuture<'_, Result<Vec<MarketInfo>>> {
        Box::pin(async move {
            let connection = self.connect().await?;

            Ok(rest::markets(&connection.universe, kind))
        })
    }

    fn order_book(&self, market: &Market, depth: Option<u32>) -> BoxFuture<'_, Result<OrderBook>> {
        let market = market.clone();
        Box::pin(async move {
            let connection = self.connect().await?;

            rest::order_book(&connection.http, &connection.universe, &market, depth).await
        })
    }

    fn ticker(&self, market: &Market) -> BoxFuture<'_, Result<Ticker>> {
        let market = market.clone();
        Box::pin(async move {
            let connection = self.connect().await?;

            rest::ticker(&connection.http, &connection.universe, &market).await
        })
    }

    fn candles(&self, request: &CandleRequest) -> BoxFuture<'_, Result<Vec<Candle>>> {
        let request = request.clone();
        Box::pin(async move {
            let connection = self.connect().await?;

            rest::candles(
                &connection.http,
                &connection.universe,
                &request,
                Timestamp::now(),
            )
            .await
        })
    }

    fn subscribe(
        &self,
        subscription: &Subscription,
        config: &StreamConfig,
    ) -> BoxFuture<'_, Result<MarketStream>> {
        let subscription = subscription.clone();
        let config = config.clone();
        let url = self.websocket_url();

        Box::pin(async move {
            let connection = self.connect().await?;
            let frames = stream::subscribe_frames(&subscription, &connection.universe)?;
            let session = ws::connect(
                WsConnect {
                    url: url.to_string(),
                    headers: None,
                    subscribe: WsConnect::fixed(frames),
                    heartbeat: Some(stream::HEARTBEAT),
                },
                &config,
            )
            .await?;
            let close = session.close_handle();

            let universe = connection.universe.clone();
            // Candle state is scoped to one connection and cleared on reconnect.
            let mut decoder = stream::Decoder::default();

            Ok(MarketStream::new_with_close(
                session.flat_map(move |command| {
                    futures_util::stream::iter(market_events(command, &universe, &mut decoder))
                }),
                move || async move { close.close().await },
            ))
        })
    }

    fn balances(&self) -> BoxFuture<'_, Result<Vec<Balance>>> {
        Box::pin(async move {
            let user = self.query_address()?;
            let connection = self.connect().await?;

            rest::balances(&connection.http, &user).await
        })
    }

    fn deposits(&self, request: &TransferHistoryRequest) -> BoxFuture<'_, Result<Page<Deposit>>> {
        let request = request.clone();
        Box::pin(async move {
            rest::validate_transfer_history(&request, Feature::DepositHistory)?;
            let user = self.query_address()?;
            let connection = self.connect().await?;

            rest::deposits(&connection.http, &user, &request).await
        })
    }

    fn withdrawals(
        &self,
        request: &TransferHistoryRequest,
    ) -> BoxFuture<'_, Result<Page<Withdrawal>>> {
        let request = request.clone();
        Box::pin(async move {
            rest::validate_transfer_history(&request, Feature::WithdrawalHistory)?;
            let user = self.query_address()?;
            let connection = self.connect().await?;

            rest::withdrawals(&connection.http, &user, &request).await
        })
    }

    fn open_orders(&self, market: Option<&Market>) -> BoxFuture<'_, Result<Vec<Order>>> {
        let market = market.cloned();
        Box::pin(async move {
            let user = self.query_address()?;
            let connection = self.connect().await?;

            rest::open_orders(
                &connection.http,
                &connection.universe,
                &user,
                market.as_ref(),
            )
            .await
        })
    }

    fn subscribe_account(&self, config: &StreamConfig) -> BoxFuture<'_, Result<AccountStream>> {
        let config = config.clone();
        let url = self.websocket_url();

        Box::pin(async move {
            let user = self.query_address()?;
            let connection = self.connect().await?;
            let session = ws::connect(
                WsConnect {
                    url: url.to_string(),
                    headers: None,
                    subscribe: WsConnect::fixed(stream::account_subscribe_frames(&user)),
                    heartbeat: Some(stream::HEARTBEAT),
                },
                &config,
            )
            .await?;
            let close = session.close_handle();

            let universe = connection.universe.clone();
            Ok(AccountStream::new_with_close(
                session.flat_map(move |command| {
                    futures_util::stream::iter(account_events(command, &universe))
                }),
                move || async move { close.close().await },
            ))
        })
    }

    fn place_order(&self, request: &OrderRequest) -> BoxFuture<'_, Result<Order>> {
        let request = request.clone();
        Box::pin(async move {
            let private_key = self.signing_key()?;
            let connection = self.connect().await?;
            let _lane = SIGNED_ACTION_LANE.lock().await;

            rest::place_order(
                &connection.http,
                &connection.universe,
                private_key,
                self.network,
                &request,
                self.next_nonce(Timestamp::now())?,
            )
            .await
        })
    }

    fn cancel_order(&self, market: &Market, order_id: &str) -> BoxFuture<'_, Result<()>> {
        let market = market.clone();
        let order_id = order_id.to_string();

        Box::pin(async move {
            let private_key = self.signing_key()?;
            let connection = self.connect().await?;
            let _lane = SIGNED_ACTION_LANE.lock().await;

            rest::cancel_order(
                &connection.http,
                &connection.universe,
                private_key,
                self.network,
                &market,
                &order_id,
                self.next_nonce(Timestamp::now())?,
            )
            .await
        })
    }

    fn positions(&self, market: Option<&Market>) -> BoxFuture<'_, Result<Vec<Position>>> {
        let market = market.cloned();
        Box::pin(async move {
            let user = self.query_address()?;
            let connection = self.connect().await?;

            rest::positions(
                &connection.http,
                &connection.universe,
                &user,
                market.as_ref(),
            )
            .await
        })
    }

    fn margin_summary(&self) -> BoxFuture<'_, Result<MarginSummary>> {
        Box::pin(async move {
            let user = self.query_address()?;
            let connection = self.connect().await?;

            rest::margin_summary(&connection.http, &user).await
        })
    }

    fn funding_rates(&self, request: &HistoryRequest) -> BoxFuture<'_, Result<Page<FundingRate>>> {
        let request = request.clone();
        Box::pin(async move {
            rest::validate_page_limit(request.limit)?;
            let connection = self.connect().await?;

            rest::funding_rates(&connection.http, &connection.universe, &request).await
        })
    }

    fn funding_payments(
        &self,
        request: &HistoryRequest,
    ) -> BoxFuture<'_, Result<Page<FundingPayment>>> {
        let request = request.clone();
        Box::pin(async move {
            rest::validate_page_limit(request.limit)?;
            let user = self.query_address()?;
            let connection = self.connect().await?;

            rest::funding_payments(&connection.http, &connection.universe, &user, &request).await
        })
    }

    fn set_margin(&self, request: &MarginRequest) -> BoxFuture<'_, Result<()>> {
        let request = request.clone();
        Box::pin(async move {
            let private_key = self.signing_key()?;
            let connection = self.connect().await?;
            let _lane = SIGNED_ACTION_LANE.lock().await;

            rest::set_margin(
                &connection.http,
                &connection.universe,
                private_key,
                self.network,
                &request,
                self.next_nonce(Timestamp::now())?,
            )
            .await
        })
    }
}

/// Decodes one connection event into zero or more market events.
///
/// The decoder preserves candle state between frames and clears it on
/// reconnect, because a gap prevents the prior window from being settled.
fn market_events(
    command: Result<WsCommand>,
    universe: &Universe,
    decoder: &mut stream::Decoder,
) -> Vec<Result<MarketEvent>> {
    let text = match command {
        Ok(WsCommand::Text(text)) => text,
        // Accept UTF-8 binary frames from intermediaries.
        Ok(WsCommand::Binary(bytes)) => match String::from_utf8(bytes) {
            Ok(text) => text,
            Err(err) => return vec![Err(Error::decode(format!("frame is not UTF-8: {err}")))],
        },
        Ok(WsCommand::Reconnected) => {
            decoder.reconnected();
            return vec![Ok(MarketEvent::Reconnected)];
        }
        Err(err) => return vec![Err(err)],
    };

    match decoder.decode(&text, universe, Timestamp::now()) {
        Ok(events) => events.into_iter().map(Ok).collect(),
        Err(err) => vec![Err(err)],
    }
}

/// Decodes one private connection event into zero or more account events.
fn account_events(command: Result<WsCommand>, universe: &Universe) -> Vec<Result<AccountEvent>> {
    let text = match command {
        Ok(WsCommand::Text(text)) => text,
        Ok(WsCommand::Binary(bytes)) => match String::from_utf8(bytes) {
            Ok(text) => text,
            Err(err) => return vec![Err(Error::decode(format!("frame is not UTF-8: {err}")))],
        },
        Ok(WsCommand::Reconnected) => return vec![Ok(AccountEvent::Reconnected)],
        Err(err) => return vec![Err(err)],
    };

    match stream::decode_account(&text, universe) {
        Ok(events) => events.into_iter().map(Ok).collect(),
        Err(err) => vec![Err(err)],
    }
}

/// Decodes one connection event into full-fidelity provider market events.
fn detailed_market_events(
    command: Result<WsCommand>,
    universe: &Universe,
    decoder: &mut stream::DetailedDecoder,
) -> Vec<Result<HyperliquidMarketEvent>> {
    let text = match command {
        Ok(WsCommand::Text(text)) => text,
        Ok(WsCommand::Binary(bytes)) => match String::from_utf8(bytes) {
            Ok(text) => text,
            Err(err) => return vec![Err(Error::decode(format!("frame is not UTF-8: {err}")))],
        },
        Ok(WsCommand::Reconnected) => {
            decoder.reconnected();
            return vec![Ok(HyperliquidMarketEvent::Reconnected)];
        }
        Err(err) => return vec![Err(err)],
    };

    match decoder.decode(&text, universe, Timestamp::now()) {
        Ok(events) => events.into_iter().map(Ok).collect(),
        Err(err) => vec![Err(err)],
    }
}

/// Decodes one private connection event into full-fidelity provider account events.
fn detailed_account_events(
    command: Result<WsCommand>,
    universe: &Universe,
) -> Vec<Result<HyperliquidAccountEvent>> {
    let text = match command {
        Ok(WsCommand::Text(text)) => text,
        Ok(WsCommand::Binary(bytes)) => match String::from_utf8(bytes) {
            Ok(text) => text,
            Err(err) => return vec![Err(Error::decode(format!("frame is not UTF-8: {err}")))],
        },
        Ok(WsCommand::Reconnected) => return vec![Ok(HyperliquidAccountEvent::Reconnected)],
        Err(err) => return vec![Err(err)],
    };

    match stream::decode_detailed_account(&text, universe) {
        Ok(events) => events.into_iter().map(Ok).collect(),
        Err(err) => vec![Err(err)],
    }
}

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

    /// Builds a one-minute BTC candle frame opening at `open_ms`.
    fn candle_frame(open_ms: i64) -> String {
        format!(
            r#"{{"channel":"candle","data":{{"T":{},"c":100,"h":100,"i":"1m","l":100,"n":12,"o":100,"s":"BTC","t":{},"v":1}}}}"#,
            open_ms + 59_999,
            open_ms
        )
    }

    #[test]
    fn a_reconnect_drops_the_held_window_instead_of_settling_it_across_the_gap() {
        // A pre-gap candle cannot be settled from a post-gap frame.
        const WINDOW_ONE_MS: i64 = 1_785_397_500_000;
        const WINDOW_TWO_MS: i64 = 1_785_397_560_000;

        let universe = universe();
        let mut decoder = stream::Decoder::default();
        let text = |frame: String| Ok(WsCommand::Text(frame));

        let events = market_events(text(candle_frame(WINDOW_ONE_MS)), &universe, &mut decoder);
        assert_eq!(events.len(), 1, "the first frame of a window is forming");

        let events = market_events(Ok(WsCommand::Reconnected), &universe, &mut decoder);
        assert!(matches!(events.as_slice(), [Ok(MarketEvent::Reconnected)]));

        // Reconnect cleared the held candle, so only the new forming one emits.
        let events = market_events(text(candle_frame(WINDOW_TWO_MS)), &universe, &mut decoder);
        assert_eq!(
            events.len(),
            1,
            "a window from before the gap is not settled by a frame after it: {events:?}"
        );
        let [Ok(MarketEvent::Candle(forming))] = events.as_slice() else {
            panic!("expected one forming candle: {events:?}");
        };
        assert!(!forming.closed);
        assert_eq!(forming.open_time, Timestamp::from_millis(WINDOW_TWO_MS));

        // Candle settlement resumes within the new connection.
        let events = market_events(
            text(candle_frame(WINDOW_TWO_MS + 60_000)),
            &universe,
            &mut decoder,
        );
        assert_eq!(events.len(), 2, "{events:?}");
        let [Ok(MarketEvent::Candle(settled)), _] = events.as_slice() else {
            panic!("expected a settled window: {events:?}");
        };
        assert!(settled.closed);
        assert_eq!(settled.open_time, Timestamp::from_millis(WINDOW_TWO_MS));
    }

    #[test]
    fn detailed_reconnect_clears_native_candle_state_and_reports_the_gap() {
        const WINDOW_ONE_MS: i64 = 1_785_397_500_000;
        const WINDOW_TWO_MS: i64 = 1_785_397_560_000;

        let universe = universe();
        let mut decoder = stream::DetailedDecoder::default();
        let text = |frame: String| Ok(WsCommand::Text(frame));

        let events =
            detailed_market_events(text(candle_frame(WINDOW_ONE_MS)), &universe, &mut decoder);
        assert_eq!(events.len(), 1);

        let events = detailed_market_events(Ok(WsCommand::Reconnected), &universe, &mut decoder);
        assert!(matches!(
            events.as_slice(),
            [Ok(HyperliquidMarketEvent::Reconnected)]
        ));

        let events =
            detailed_market_events(text(candle_frame(WINDOW_TWO_MS)), &universe, &mut decoder);
        let [Ok(HyperliquidMarketEvent::Candle(forming))] = events.as_slice() else {
            panic!("expected only the post-reconnect forming candle: {events:?}");
        };
        assert!(!forming.common.closed);
        assert_eq!(
            forming.common.open_time,
            Timestamp::from_millis(WINDOW_TWO_MS)
        );

        let events = detailed_account_events(Ok(WsCommand::Reconnected), &universe);
        assert!(matches!(
            events.as_slice(),
            [Ok(HyperliquidAccountEvent::Reconnected)]
        ));
    }

    #[test]
    fn trades_are_served_both_live_and_over_rest() {
        let adapter = HyperliquidAdapter::new();

        assert!(adapter.supports(Feature::TradeStream));
        assert!(adapter.supports(Feature::Trades));
    }

    #[test]
    fn one_adapter_serves_both_spot_and_perpetual_markets() {
        let adapter = HyperliquidAdapter::new().with_wallet("0xabc", "0xdef");

        for feature in [
            Feature::Positions,
            Feature::Margin,
            Feature::FundingRates,
            Feature::MarginConfig,
            Feature::Trading,
        ] {
            assert!(adapter.supports(feature), "{feature:?}");
        }
    }

    #[test]
    fn query_address_and_signer_unlock_only_the_operations_they_feed() {
        let public = HyperliquidAdapter::new();
        let address_only = HyperliquidAdapter::new()
            .with_query_address("0x14791697260e4c9a71f18484c9f997b308e59325");
        let signer_only = HyperliquidAdapter::new()
            .with_signer("0x0123456789012345678901234567890123456789012345678901234567890123");

        for feature in [
            Feature::Balances,
            Feature::DepositHistory,
            Feature::WithdrawalHistory,
            Feature::Positions,
        ] {
            assert!(!public.supports(feature), "{feature:?}");
            assert!(address_only.supports(feature), "{feature:?}");
            assert!(!signer_only.supports(feature), "{feature:?}");
        }
        for feature in [
            Feature::Trading,
            Feature::MarginConfig,
            Feature::ReduceOnlyOrders,
        ] {
            assert!(!public.supports(feature), "{feature:?}");
            assert!(!address_only.supports(feature), "{feature:?}");
            assert!(signer_only.supports(feature), "{feature:?}");
        }
        for feature in [
            Feature::AssetNetworks,
            Feature::DepositAddresses,
            Feature::WithdrawalQuotes,
            Feature::Withdrawals,
        ] {
            assert!(!address_only.supports(feature), "{feature:?}");
            assert!(!signer_only.supports(feature), "{feature:?}");
        }
    }

    #[test]
    fn the_signing_key_never_appears_in_debug_output() {
        let adapter = HyperliquidAdapter::new().with_wallet("0xabc", "0xdeadbeef");
        let rendered = format!("{adapter:?}");

        assert!(!rendered.contains("0xdeadbeef"));
        assert!(rendered.contains("<redacted>"));
        assert!(rendered.contains("0xabc"));
    }

    #[tokio::test]
    async fn a_private_call_without_a_wallet_says_so_before_it_reaches_the_network() {
        // Missing query address or signer fails before a connection is attempted.
        let public = HyperliquidAdapter::new();
        let market = Market::perpetual(Exchange::Hyperliquid, "BTC", "USDC");

        assert!(matches!(public.balances().await, Err(Error::Auth { .. })));
        assert!(matches!(
            public.positions(None).await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.margin_summary().await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.cancel_order(&market, "1").await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.non_funding_ledger(None, None, None, None).await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.user_rate_limit().await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(public.user_role().await, Err(Error::Auth { .. })));
        assert!(matches!(public.referral().await, Err(Error::Auth { .. })));
        assert!(matches!(public.user_fees().await, Err(Error::Auth { .. })));
        assert!(matches!(public.portfolio().await, Err(Error::Auth { .. })));
        assert!(matches!(
            public.sub_accounts().await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.user_vault_equities().await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.user_fills(false).await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public
                .user_fills_by_time(Timestamp::from_millis(0), None, false)
                .await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.user_funding(Timestamp::from_millis(0), None).await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.spot_clearinghouse_state().await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.basic_open_orders().await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public
                .order_status(HyperliquidOrderReference::order_id(1))
                .await,
            Err(Error::Auth { .. })
        ));
        assert!(matches!(
            public.historical_orders().await,
            Err(Error::Auth { .. })
        ));
    }

    #[tokio::test]
    async fn order_status_preflight_checks_address_then_reference_before_connecting() {
        let missing_address = HyperliquidAdapter::new();
        assert!(matches!(
            missing_address
                .order_status(HyperliquidOrderReference::client_order_id("not-a-cloid"))
                .await,
            Err(Error::Auth { .. })
        ));

        let configured = HyperliquidAdapter::new()
            .with_query_address("0x14791697260e4c9a71f18484c9f997b308e59325");
        let invalid = configured
            .order_status(HyperliquidOrderReference::client_order_id("not-a-cloid"))
            .await;
        assert!(
            matches!(&invalid, Err(Error::InvalidRequest { field, .. }) if *field == "client_order_id"),
            "{invalid:?}"
        );
    }

    #[tokio::test]
    async fn a_zero_funding_payment_limit_is_rejected_before_authentication() {
        let public = HyperliquidAdapter::new();
        let request =
            HistoryRequest::new(Market::perpetual(Exchange::Hyperliquid, "BTC", "USDC")).limit(0);

        let refused = public.funding_payments(&request).await;

        assert!(
            matches!(&refused, Err(Error::InvalidRequest { field, .. }) if *field == "limit"),
            "{refused:?}"
        );
    }

    #[tokio::test]
    async fn provider_history_ranges_are_checked_before_connecting() {
        let public = HyperliquidAdapter::new();
        let market = Market::perpetual(Exchange::Hyperliquid, "BTC", "USDC");
        let later = Timestamp::from_millis(2);
        let earlier = Timestamp::from_millis(1);

        assert!(matches!(
            public.candle_snapshot(&market, "1m", later, Some(earlier)).await,
            Err(Error::InvalidRequest { field, .. }) if field == "to"
        ));
        assert!(matches!(
            public.funding_history(&market, later, Some(earlier)).await,
            Err(Error::InvalidRequest { field, .. }) if field == "to"
        ));
        assert!(matches!(
            public.user_funding(later, Some(earlier)).await,
            Err(Error::InvalidRequest { field, .. }) if field == "to"
        ));
    }

    #[tokio::test]
    async fn a_zero_funding_rate_limit_is_rejected_on_the_first_poll() {
        let public = HyperliquidAdapter::new();
        let request =
            HistoryRequest::new(Market::perpetual(Exchange::Hyperliquid, "BTC", "USDC")).limit(0);
        let mut call = public.funding_rates(&request);
        let waker = futures_util::task::noop_waker();
        let mut context = std::task::Context::from_waker(&waker);

        let first_poll = std::future::Future::poll(call.as_mut(), &mut context);

        assert!(matches!(
            first_poll,
            std::task::Poll::Ready(Err(Error::InvalidRequest { field, .. })) if field == "limit"
        ));
    }

    #[tokio::test]
    async fn a_zero_ledger_limit_is_rejected_before_authentication() {
        let public = HyperliquidAdapter::new();

        let refused = public.non_funding_ledger(None, None, None, Some(0)).await;

        assert!(
            matches!(&refused, Err(Error::InvalidRequest { field, .. }) if *field == "limit"),
            "{refused:?}"
        );
    }

    #[tokio::test]
    async fn an_invalid_signer_is_rejected_before_the_network() {
        let broken = HyperliquidAdapter::new().with_signer("not-a-key");
        let market = Market::perpetual(Exchange::Hyperliquid, "BTC", "USDC");

        assert!(matches!(
            broken.cancel_order(&market, "1").await,
            Err(Error::Auth { .. })
        ));
    }

    #[test]
    fn independent_adapters_share_a_monotonic_nonce_allocator() {
        let first = HyperliquidAdapter::new();
        let second = HyperliquidAdapter::new();
        let now = Timestamp::from_millis(1_700_000_000_123);

        let first_nonce = first.next_nonce(now).unwrap();
        let second_nonce = second.next_nonce(now).unwrap();

        assert!(second_nonce > first_nonce);
    }

    #[tokio::test]
    async fn transfer_history_filters_that_the_ledger_cannot_prove_are_rejected_offline() {
        let request = TransferHistoryRequest::new().network(crate::types::Network::Arbitrum);
        let adapter = HyperliquidAdapter::new()
            .with_query_address("0x14791697260e4c9a71f18484c9f997b308e59325");

        assert!(matches!(
            adapter.deposits(&request).await,
            Err(Error::Unsupported {
                feature: Feature::DepositHistory,
                ..
            })
        ));
        assert!(matches!(
            adapter.withdrawals(&request).await,
            Err(Error::Unsupported {
                feature: Feature::WithdrawalHistory,
                ..
            })
        ));
    }

    #[tokio::test]
    async fn deposit_address_stays_unsupported_instead_of_guessing_a_bridge() {
        let adapter = HyperliquidAdapter::new()
            .with_query_address("0x14791697260e4c9a71f18484c9f997b308e59325");
        let request =
            crate::request::DepositAddressRequest::new("USDC", crate::types::Network::Arbitrum);

        assert!(matches!(
            adapter.deposit_address(&request).await,
            Err(Error::Unsupported {
                feature: Feature::DepositAddresses,
                ..
            })
        ));
    }

    #[test]
    fn testnet_and_mainnet_are_separate_hosts() {
        let mainnet = HyperliquidAdapter::new();
        let testnet = HyperliquidAdapter::testnet();

        assert!(!mainnet.is_testnet());
        assert!(testnet.is_testnet());
        assert_ne!(mainnet.rest_base_url(), testnet.rest_base_url());
        assert_ne!(mainnet.websocket_url(), testnet.websocket_url());
    }
}