quicknode-hyperliquid-sdk 0.1.8

Hyperliquid SDK for Rust - Simple, performant trading client. HyperCore, HyperEVM, WebSocket and gRPC streams.
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
//! Core types for the Hyperliquid SDK.
//!
//! These types mirror the Hyperliquid API exactly for byte-identical serialization.

use alloy::primitives::{Address, B128, U256};
use alloy::sol_types::{eip712_domain, Eip712Domain};
use either::Either;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

// ══════════════════════════════════════════════════════════════════════════════
// Type Aliases
// ══════════════════════════════════════════════════════════════════════════════

/// Client Order ID - 128-bit unique identifier
pub type Cloid = B128;

/// Either an order ID (u64) or a client order ID (Cloid)
pub type OidOrCloid = Either<u64, Cloid>;

// ══════════════════════════════════════════════════════════════════════════════
// Chain
// ══════════════════════════════════════════════════════════════════════════════

/// Hyperliquid chain (Mainnet or Testnet)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum Chain {
    #[default]
    Mainnet,
    Testnet,
}

impl Chain {
    /// Returns true if this is mainnet
    pub fn is_mainnet(&self) -> bool {
        matches!(self, Chain::Mainnet)
    }

    /// Returns the chain as a string ("Mainnet" or "Testnet")
    pub fn as_str(&self) -> &'static str {
        match self {
            Chain::Mainnet => "Mainnet",
            Chain::Testnet => "Testnet",
        }
    }

    /// Returns the signature chain ID for EIP-712 signing
    pub fn signature_chain_id(&self) -> &'static str {
        match self {
            Chain::Mainnet => "0xa4b1", // Arbitrum One
            Chain::Testnet => "0x66eee", // Arbitrum Sepolia
        }
    }

    /// Returns the EVM chain ID
    pub fn evm_chain_id(&self) -> u64 {
        match self {
            Chain::Mainnet => 999,
            Chain::Testnet => 998,
        }
    }
}

impl fmt::Display for Chain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Chain::Mainnet => write!(f, "Mainnet"),
            Chain::Testnet => write!(f, "Testnet"),
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Side
// ══════════════════════════════════════════════════════════════════════════════

/// Order side
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Side {
    Buy,
    Sell,
}

impl Side {
    /// Returns true if this is a buy side
    pub fn is_buy(&self) -> bool {
        matches!(self, Side::Buy)
    }

    /// Converts to bool for API (true = buy, false = sell)
    pub fn as_bool(&self) -> bool {
        self.is_buy()
    }
}

impl fmt::Display for Side {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Side::Buy => write!(f, "buy"),
            Side::Sell => write!(f, "sell"),
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// HIP-4 Prediction Markets
// ══════════════════════════════════════════════════════════════════════════════

/// A tradeable HIP-4 outcome side.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictionSide {
    pub outcome: u64,
    pub side: usize,
    pub name: String,
    pub symbol: String,
    pub token: String,
    pub asset_id: usize,
    pub mid: Option<String>,
    pub sz_decimals: u8,
    pub supports_priority_fee: bool,
}

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

impl From<PredictionSide> for String {
    fn from(side: PredictionSide) -> Self {
        side.symbol
    }
}

impl From<&PredictionSide> for String {
    fn from(side: &PredictionSide) -> Self {
        side.symbol.clone()
    }
}

/// A HIP-4 prediction market with yes/no tradeable sides.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictionMarket {
    pub outcome: u64,
    pub name: String,
    pub description: String,
    pub title: String,
    pub slug: String,
    pub underlying: Option<String>,
    pub target_price: Option<String>,
    pub expiry: Option<String>,
    pub period: Option<String>,
    pub collateral: String,
    pub min_order_value: String,
    pub aliases: Vec<String>,
    pub yes: PredictionSide,
    pub no: PredictionSide,
    pub sides: Vec<PredictionSide>,
}

impl PredictionMarket {
    pub fn matches(&self, query: &str) -> bool {
        let normalized = query.to_lowercase();
        let mut values = vec![
            self.slug.clone(),
            self.title.to_lowercase(),
            self.name.to_lowercase(),
            self.underlying.clone().unwrap_or_default().to_lowercase(),
            self.yes.symbol.to_lowercase(),
            self.no.symbol.to_lowercase(),
            self.yes.token.to_lowercase(),
            self.no.token.to_lowercase(),
        ];
        values.extend(self.aliases.iter().map(|alias| alias.to_lowercase()));
        values.iter().any(|value| value == &normalized || value.contains(&normalized))
    }
}

/// Filter for selecting an active HIP-4 prediction market.
#[derive(Debug, Clone, Default)]
pub struct PredictionMarketFilter {
    pub query: Option<String>,
    pub underlying: Option<String>,
    pub target_price: Option<String>,
    pub expiry: Option<String>,
}

impl FromStr for Side {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "buy" | "b" | "long" => Ok(Side::Buy),
            "sell" | "s" | "short" => Ok(Side::Sell),
            _ => Err(format!("invalid side: {}", s)),
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Time In Force (TIF)
// ══════════════════════════════════════════════════════════════════════════════

/// Time in force for orders
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TIF {
    /// Immediate or Cancel - fill immediately or cancel
    #[default]
    Ioc,
    /// Good Till Cancel - stays on book until filled or cancelled
    Gtc,
    /// Add Liquidity Only (post-only) - rejected if would cross
    Alo,
    /// Market order (converted to IOC with slippage)
    Market,
}

impl fmt::Display for TIF {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TIF::Ioc => write!(f, "ioc"),
            TIF::Gtc => write!(f, "gtc"),
            TIF::Alo => write!(f, "alo"),
            TIF::Market => write!(f, "market"),
        }
    }
}

impl FromStr for TIF {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "ioc" => Ok(TIF::Ioc),
            "gtc" => Ok(TIF::Gtc),
            "alo" | "post_only" => Ok(TIF::Alo),
            "market" => Ok(TIF::Market),
            _ => Err(format!("invalid tif: {}", s)),
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// TimeInForce (API format)
// ══════════════════════════════════════════════════════════════════════════════

/// Time in force for the wire format (PascalCase)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TimeInForce {
    Alo,
    Ioc,
    Gtc,
    FrontendMarket,
}

impl From<TIF> for TimeInForce {
    fn from(tif: TIF) -> Self {
        match tif {
            TIF::Ioc => TimeInForce::Ioc,
            TIF::Gtc => TimeInForce::Gtc,
            TIF::Alo => TimeInForce::Alo,
            TIF::Market => TimeInForce::Ioc, // Market orders use IOC with slippage
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// TpSl (Take Profit / Stop Loss)
// ══════════════════════════════════════════════════════════════════════════════

/// Take profit or stop loss trigger type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TpSl {
    /// Take profit
    Tp,
    /// Stop loss
    Sl,
}

impl fmt::Display for TpSl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TpSl::Tp => write!(f, "tp"),
            TpSl::Sl => write!(f, "sl"),
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Order Grouping
// ══════════════════════════════════════════════════════════════════════════════

/// Order grouping for TP/SL attachment
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OrderGrouping {
    /// No grouping
    #[default]
    Na,
    /// Normal TP/SL grouping
    NormalTpsl,
    /// Position-based TP/SL grouping
    PositionTpsl,
}

impl fmt::Display for OrderGrouping {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OrderGrouping::Na => write!(f, "na"),
            OrderGrouping::NormalTpsl => write!(f, "normalTpsl"),
            OrderGrouping::PositionTpsl => write!(f, "positionTpsl"),
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// EIP-712 Domain
// ══════════════════════════════════════════════════════════════════════════════

/// EIP-712 domain for Hyperliquid signing
pub const CORE_MAINNET_EIP712_DOMAIN: Eip712Domain = eip712_domain! {
    name: "Exchange",
    version: "1",
    chain_id: 1337,
    verifying_contract: Address::ZERO,
};

// ══════════════════════════════════════════════════════════════════════════════
// Signature
// ══════════════════════════════════════════════════════════════════════════════

/// ECDSA signature (r, s, v format)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Signature {
    #[serde(
        serialize_with = "serialize_u256_hex",
        deserialize_with = "deserialize_u256_hex"
    )]
    pub r: U256,
    #[serde(
        serialize_with = "serialize_u256_hex",
        deserialize_with = "deserialize_u256_hex"
    )]
    pub s: U256,
    pub v: u64,
}

impl From<alloy::signers::Signature> for Signature {
    fn from(sig: alloy::signers::Signature) -> Self {
        Self {
            r: sig.r(),
            s: sig.s(),
            v: if sig.v() { 28 } else { 27 },
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Order Type Placement
// ══════════════════════════════════════════════════════════════════════════════

/// Order type for placement (limit or trigger)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OrderTypePlacement {
    /// Limit order
    Limit {
        tif: TimeInForce,
    },
    /// Trigger order (stop loss / take profit)
    #[serde(rename_all = "camelCase")]
    Trigger {
        is_market: bool,
        #[serde(with = "decimal_normalized")]
        trigger_px: Decimal,
        tpsl: TpSl,
    },
}

// ══════════════════════════════════════════════════════════════════════════════
// Order Request
// ══════════════════════════════════════════════════════════════════════════════

/// Order request for the API
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderRequest {
    /// Asset index
    #[serde(rename = "a")]
    pub asset: usize,
    /// Is buy (true) or sell (false)
    #[serde(rename = "b")]
    pub is_buy: bool,
    /// Limit price
    #[serde(rename = "p", with = "decimal_normalized")]
    pub limit_px: Decimal,
    /// Size
    #[serde(rename = "s", with = "decimal_normalized")]
    pub sz: Decimal,
    /// Reduce only
    #[serde(rename = "r")]
    pub reduce_only: bool,
    /// Order type
    #[serde(rename = "t")]
    pub order_type: OrderTypePlacement,
    /// Client order ID
    #[serde(
        rename = "c",
        serialize_with = "serialize_cloid_hex",
        deserialize_with = "deserialize_cloid_hex"
    )]
    pub cloid: Cloid,
}

// ══════════════════════════════════════════════════════════════════════════════
// Batch Order
// ══════════════════════════════════════════════════════════════════════════════

/// Batch of orders
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchOrder {
    pub orders: Vec<OrderRequest>,
    pub grouping: OrderGrouping,
}

// ══════════════════════════════════════════════════════════════════════════════
// Modify
// ══════════════════════════════════════════════════════════════════════════════

/// Order modification
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Modify {
    #[serde(with = "oid_or_cloid")]
    pub oid: OidOrCloid,
    pub order: OrderRequest,
}

/// Batch modification
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchModify {
    pub modifies: Vec<Modify>,
}

// ══════════════════════════════════════════════════════════════════════════════
// Cancel
// ══════════════════════════════════════════════════════════════════════════════

/// Cancel request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Cancel {
    #[serde(rename = "a")]
    pub asset: usize,
    #[serde(rename = "o")]
    pub oid: u64,
}

/// Batch cancel
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchCancel {
    pub cancels: Vec<Cancel>,
}

/// Cancel by client order ID
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelByCloid {
    pub asset: u32,
    #[serde(with = "const_hex_b128")]
    pub cloid: B128,
}

/// Batch cancel by client order ID
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchCancelCloid {
    pub cancels: Vec<CancelByCloid>,
}

/// Schedule cancel (dead-man's switch)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleCancel {
    pub time: Option<u64>,
}

// ══════════════════════════════════════════════════════════════════════════════
// TWAP Orders
// ══════════════════════════════════════════════════════════════════════════════

/// TWAP order specification
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TwapSpec {
    #[serde(rename = "a")]
    pub asset: String,
    #[serde(rename = "b")]
    pub is_buy: bool,
    #[serde(rename = "s")]
    pub sz: String,
    #[serde(rename = "r")]
    pub reduce_only: bool,
    #[serde(rename = "m")]
    pub duration_minutes: i64,
    #[serde(rename = "t")]
    pub randomize: bool,
}

/// TWAP order
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TwapOrder {
    pub twap: TwapSpec,
}

/// TWAP cancel
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TwapCancel {
    #[serde(rename = "a")]
    pub asset: String,
    #[serde(rename = "t")]
    pub twap_id: i64,
}

// ══════════════════════════════════════════════════════════════════════════════
// Leverage Management
// ══════════════════════════════════════════════════════════════════════════════

/// Update leverage
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateLeverage {
    pub asset: u32,
    pub is_cross: bool,
    pub leverage: i32,
}

/// Update isolated margin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateIsolatedMargin {
    pub asset: u32,
    pub is_buy: bool,
    pub ntli: i64,
}

/// Top up isolated only margin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TopUpIsolatedOnlyMargin {
    pub asset: u32,
    pub leverage: String,
}

// ══════════════════════════════════════════════════════════════════════════════
// Transfer Operations
// ══════════════════════════════════════════════════════════════════════════════

/// USD transfer
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UsdSend {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub destination: String,
    pub amount: String,
    pub time: u64,
}

/// Spot token transfer
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpotSend {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub token: String,
    pub destination: String,
    pub amount: String,
    pub time: u64,
}

/// Withdraw to Arbitrum
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Withdraw3 {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub destination: String,
    pub amount: String,
    pub time: u64,
}

/// USD class transfer (perp <-> spot)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UsdClassTransfer {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub amount: String,
    pub to_perp: bool,
    pub nonce: u64,
}

/// Send asset
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SendAsset {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub destination: String,
    pub source_dex: String,
    pub destination_dex: String,
    pub token: String,
    pub amount: String,
    pub from_sub_account: String,
    pub nonce: u64,
}

// ══════════════════════════════════════════════════════════════════════════════
// Vault Operations
// ══════════════════════════════════════════════════════════════════════════════

/// Vault transfer (deposit/withdraw)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultTransfer {
    pub vault_address: String,
    pub is_deposit: bool,
    pub usd: f64,
}

// ══════════════════════════════════════════════════════════════════════════════
// Agent/API Key Management
// ══════════════════════════════════════════════════════════════════════════════

/// Approve agent (API key)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApproveAgent {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub agent_address: String,
    pub agent_name: Option<String>,
    pub nonce: u64,
}

/// Approve builder fee
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApproveBuilderFee {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub max_fee_rate: String,
    pub builder: String,
    pub nonce: u64,
}

// ══════════════════════════════════════════════════════════════════════════════
// Account Abstraction
// ══════════════════════════════════════════════════════════════════════════════

/// User set abstraction
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserSetAbstraction {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub user: String,
    pub abstraction: String,
    pub nonce: u64,
}

/// Agent set abstraction
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentSetAbstraction {
    pub abstraction: String,
}

// ══════════════════════════════════════════════════════════════════════════════
// Staking Operations
// ══════════════════════════════════════════════════════════════════════════════

/// Stake (cDeposit)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CDeposit {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub wei: u128,
    pub nonce: u64,
}

/// Unstake (cWithdraw)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CWithdraw {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub wei: u128,
    pub nonce: u64,
}

/// Delegate tokens
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenDelegate {
    pub hyperliquid_chain: Chain,
    pub signature_chain_id: String,
    pub validator: String,
    pub is_undelegate: bool,
    pub wei: u128,
    pub nonce: u64,
}

// ══════════════════════════════════════════════════════════════════════════════
// Misc Operations
// ══════════════════════════════════════════════════════════════════════════════

/// Reserve request weight (purchase rate limit capacity)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReserveRequestWeight {
    pub weight: i32,
}

/// No-op (consume nonce)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Noop {}

/// Validator L1 stream (vote on risk-free rate)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ValidatorL1Stream {
    pub risk_free_rate: String,
}

/// Close position
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClosePosition {
    pub asset: String,
    pub user: String,
}

// ══════════════════════════════════════════════════════════════════════════════
// Action (all possible actions)
// ══════════════════════════════════════════════════════════════════════════════

/// All possible actions that can be sent to the exchange
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
pub enum Action {
    // Trading actions (require builder fees)
    Order(BatchOrder),
    BatchModify(BatchModify),

    // Cancel actions (no builder fees)
    Cancel(BatchCancel),
    CancelByCloid(BatchCancelCloid),
    ScheduleCancel(ScheduleCancel),

    // TWAP orders
    TwapOrder(TwapOrder),
    TwapCancel(TwapCancel),

    // Leverage management
    UpdateLeverage(UpdateLeverage),
    UpdateIsolatedMargin(UpdateIsolatedMargin),
    TopUpIsolatedOnlyMargin(TopUpIsolatedOnlyMargin),

    // Transfer operations
    UsdSend(UsdSend),
    SpotSend(SpotSend),
    Withdraw3(Withdraw3),
    UsdClassTransfer(UsdClassTransfer),
    SendAsset(SendAsset),

    // Vault operations
    VaultTransfer(VaultTransfer),

    // Agent/API key management
    ApproveAgent(ApproveAgent),
    ApproveBuilderFee(ApproveBuilderFee),

    // Account abstraction
    UserSetAbstraction(UserSetAbstraction),
    AgentSetAbstraction(AgentSetAbstraction),

    // Staking operations
    CDeposit(CDeposit),
    CWithdraw(CWithdraw),
    TokenDelegate(TokenDelegate),

    // Rate limiting
    ReserveRequestWeight(ReserveRequestWeight),

    // Noop
    Noop(Noop),

    // Validator operations
    ValidatorL1Stream(ValidatorL1Stream),

    // Close position
    ClosePosition(ClosePosition),
}

impl Action {
    /// Compute the MessagePack hash of this action for signing
    pub fn hash(
        &self,
        nonce: u64,
        vault_address: Option<Address>,
        expires_after: Option<u64>,
    ) -> Result<alloy::primitives::B256, rmp_serde::encode::Error> {
        crate::signing::rmp_hash(self, nonce, vault_address, expires_after)
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Action Request
// ══════════════════════════════════════════════════════════════════════════════

/// Signed action request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionRequest {
    pub action: Action,
    pub nonce: u64,
    pub signature: Signature,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vault_address: Option<Address>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_after: Option<u64>,
}

// ══════════════════════════════════════════════════════════════════════════════
// Builder
// ══════════════════════════════════════════════════════════════════════════════

/// Builder fee information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Builder {
    /// Builder address
    #[serde(rename = "b")]
    pub address: String,
    /// Fee in tenths of basis points (40 = 0.04%)
    #[serde(rename = "f")]
    pub fee: u16,
}

// ══════════════════════════════════════════════════════════════════════════════
// Serde Helpers
// ══════════════════════════════════════════════════════════════════════════════

/// Normalized decimal serialization (removes trailing zeros)
pub mod decimal_normalized {
    use rust_decimal::Decimal;
    use serde::{de, Deserialize, Deserializer, Serializer};
    use std::str::FromStr;

    pub fn serialize<S>(value: &Decimal, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let normalized = value.normalize();
        serializer.serialize_str(&normalized.to_string())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Decimal, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Decimal::from_str(&s)
            .map(|d| d.normalize())
            .map_err(de::Error::custom)
    }
}

/// Serde module for OidOrCloid
pub mod oid_or_cloid {
    use super::Cloid;
    use either::Either;
    use serde::{de, Deserializer, Serializer};

    pub fn serialize<S>(value: &Either<u64, Cloid>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Either::Left(oid) => serializer.serialize_u64(*oid),
            Either::Right(cloid) => serializer.serialize_str(&format!("{:#x}", cloid)),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Either<u64, Cloid>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct Visitor;

        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = Either<u64, Cloid>;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a u64 oid or a hex string cloid")
            }

            fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
                Ok(Either::Left(v))
            }

            fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
                v.parse::<Cloid>().map(Either::Right).map_err(de::Error::custom)
            }
        }

        deserializer.deserialize_any(Visitor)
    }
}

/// B128 hex serialization
pub mod const_hex_b128 {
    use alloy::primitives::B128;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(value: &B128, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{:#x}", value))
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<B128, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse::<B128>().map_err(serde::de::Error::custom)
    }
}

fn serialize_cloid_hex<S>(value: &Cloid, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&format!("{:#x}", value))
}

fn deserialize_cloid_hex<'de, D>(deserializer: D) -> Result<Cloid, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    s.parse::<Cloid>().map_err(serde::de::Error::custom)
}

fn serialize_u256_hex<S>(value: &U256, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&format!("{:#x}", value))
}

fn deserialize_u256_hex<'de, D>(deserializer: D) -> Result<U256, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    let s = s.strip_prefix("0x").unwrap_or(&s);
    U256::from_str_radix(s, 16).map_err(serde::de::Error::custom)
}