hyperliquid 0.2.4

A Rust library for the Hyperliquid API
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
use crate::utils::as_hex;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "PascalCase")]
pub enum Chain {
    Dev = 1337,

    Arbitrum = 42161,
    ArbitrumTestnet = 421611,
    ArbitrumGoerli = 421613,
    ArbitrumSepolia = 421614,
    ArbitrumNova = 42170,
}

impl std::fmt::Display for Chain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Chain::Dev => "Dev",
                Chain::Arbitrum => "Arbitrum",
                Chain::ArbitrumTestnet => "ArbitrumTestnet",
                Chain::ArbitrumGoerli => "ArbitrumGoerli",
                Chain::ArbitrumSepolia => "ArbitrumSepolia",
                Chain::ArbitrumNova => "ArbitrumNova",
            }
        )
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "PascalCase")]
pub enum HyperliquidChain {
    Mainnet,
    Testnet,
}

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

pub enum API {
    Info,
    Exchange,
}

pub type Cloid = Uuid;

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Oid {
    Order(u64),
    #[serde(serialize_with = "as_hex")]
    Cloid(Cloid),
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Side {
    B,
    A,
}
pub mod agent {
    pub mod l1 {
        use ethers::{
            contract::{Eip712, EthAbiType},
            types::H256,
        };

        #[derive(Eip712, Clone, EthAbiType)]
        #[eip712(
            name = "Exchange",
            version = "1",
            chain_id = 1337,
            verifying_contract = "0x0000000000000000000000000000000000000000"
        )]
        pub struct Agent {
            pub source: String,
            pub connection_id: H256,
        }
    }
}

pub mod info {
    pub mod request {
        use ethers::types::Address;
        use serde::{Deserialize, Serialize};

        use crate::types::Oid;

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct CandleSnapshotRequest {
            pub coin: String,
            pub interval: String,
            pub start_time: u64,
            pub end_time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase", tag = "type")]
        pub enum Request {
            Meta,
            AllMids,
            MetaAndAssetCtxs,
            ClearinghouseState {
                user: Address,
            },
            BatchClearinghouseStates {
                users: Vec<Address>,
            },
            OpenOrders {
                user: Address,
            },

            FrontendOpenOrders {
                user: Address,
            },
            UserFills {
                user: Address,
            },
            #[serde(rename_all = "camelCase")]
            UserFillsByTime {
                user: Address,
                start_time: u64,
                #[serde(skip_serializing_if = "Option::is_none")]
                end_time: Option<u64>,
            },
            #[serde(rename_all = "camelCase")]
            UserFunding {
                user: Address,
                start_time: u64,
                end_time: Option<u64>,
            },
            #[serde(rename_all = "camelCase")]
            FundingHistory {
                coin: String,
                start_time: u64,
                end_time: Option<u64>,
            },
            L2Book {
                coin: String,
            },
            RecentTrades {
                coin: String,
            },
            CandleSnapshot {
                req: CandleSnapshotRequest,
            },
            OrderStatus {
                user: Address,
                oid: Oid,
            },
            SubAccounts {
                user: Address,
            },

            SpotMeta,

            SpotMetaAndAssetCtxs,

            SpotClearinghouseState {
                user: Address,
            },
        }
    }

    pub mod response {
        use ethers::types::Address;
        use serde::{Deserialize, Serialize};

        use crate::types::Side;

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Asset {
            pub name: String,
            pub sz_decimals: u64,
            pub max_leverage: u64,
            pub only_isolated: bool,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Universe {
            pub universe: Vec<Asset>,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(untagged)]
        pub enum ImpactPx {
            String(String),
            StringArray(Vec<String>),
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Ctx {
            pub funding: String,
            pub open_interest: String,
            pub prev_day_px: String,
            pub day_ntl_vlm: String,
            pub premium: Option<String>,
            pub oracle_px: String,
            pub mark_px: String,
            pub mid_px: Option<String>,
            pub impact_pxs: Option<ImpactPx>,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(untagged)]
        pub enum AssetContext {
            Meta(Universe),
            Ctx(Vec<Ctx>),
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct CumFunding {
            pub all_time: String,
            pub since_change: String,
            pub since_open: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct Leverage {
            #[serde(rename = "type")]
            pub type_: String,
            pub value: u32,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]

        pub struct Position {
            pub coin: String,
            pub cum_funding: CumFunding,
            pub entry_px: Option<String>,
            pub leverage: Leverage,
            pub liquidation_px: Option<String>,
            pub margin_used: String,
            pub max_leverage: u32,
            pub position_value: String,
            pub return_on_equity: String,
            pub szi: String,
            pub unrealized_pnl: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct AssetPosition {
            pub position: Position,
            #[serde(rename = "type")]
            pub type_: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct MarginSummary {
            pub account_value: String,
            pub total_margin_used: String,
            pub total_ntl_pos: String,
            pub total_raw_usd: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct UserState {
            pub asset_positions: Vec<AssetPosition>,
            pub margin_summary: MarginSummary,
            pub cross_margin_summary: MarginSummary,
            pub withdrawable: String,
            pub time: u64,
            pub cross_maintenance_margin_used: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct OpenOrder {
            pub coin: String,
            pub limit_px: String,
            pub oid: u64,
            pub side: Side,
            pub sz: String,
            pub timestamp: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct FrontendOpenOrders {
            pub coin: String,
            pub is_position_tpsl: bool,
            pub is_trigger: bool,
            pub limit_px: String,
            pub oid: u64,
            pub order_type: String,
            pub orig_sz: String,
            pub reduce_only: bool,
            pub side: Side,
            pub sz: String,
            pub timestamp: u64,
            pub trigger_condition: String,
            pub trigger_px: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct UserFill {
            pub coin: String,
            pub px: String,
            pub sz: String,
            pub side: Side,
            pub time: u64,
            pub start_position: String,
            pub dir: String,
            pub closed_pnl: String,
            pub hash: String,
            pub oid: u64,
            pub crossed: bool,
            pub fee: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Delta {
            pub coin: String,
            pub funding_rate: String,
            pub szi: String,
            #[serde(rename = "type")]
            pub type_: String,
            pub usdc: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct UserFunding {
            pub delta: Delta,
            pub hash: String,
            pub time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct FundingHistory {
            pub coin: String,
            pub funding_rate: String,
            pub premium: String,
            pub time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Level {
            pub px: String,
            pub sz: String,
            pub n: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct L2Book {
            pub coin: String,
            pub levels: Vec<Vec<Level>>,
            pub time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct RecentTrades {
            pub coin: String,
            pub side: Side,
            pub px: String,
            pub sz: String,
            pub hash: String,
            pub time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct CandleSnapshot {
            #[serde(rename = "T")]
            pub t_: u64,
            pub c: String,
            pub h: String,
            pub i: String,
            pub l: String,
            pub n: u64,
            pub o: String,
            pub s: String,
            pub t: u64,
            pub v: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct OrderInfo {
            pub children: Vec<Option<serde_json::Value>>,
            pub cloid: Option<String>,
            pub coin: String,
            pub is_position_tpsl: bool,
            pub is_trigger: bool,
            pub limit_px: String,
            pub oid: i64,
            pub order_type: String,
            pub orig_sz: String,
            pub reduce_only: bool,
            pub side: String,
            pub sz: String,
            pub tif: Option<String>,
            pub timestamp: i64,
            pub trigger_condition: String,
            pub trigger_px: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Order {
            pub order: OrderInfo,
            pub status: String,
            pub status_timestamp: i64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct OrderStatus {
            pub order: Option<Order>,
            pub status: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct SubAccount {
            pub clearinghouse_state: UserState,
            pub master: Address,
            pub name: String,
            pub sub_account_user: Address,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct SpotAsset {
            pub index: u64,
            pub is_canonical: bool,
            pub name: String,
            pub sz_decimals: u64,
            pub token_id: String,
            pub wei_decimals: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct SpotUniverse {
            pub index: u64,
            pub is_canonical: bool,
            pub name: String,
            pub tokens: Vec<u64>,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct SpotMeta {
            pub tokens: Vec<SpotAsset>,
            pub universe: Vec<SpotUniverse>,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct SpotCtx {
            pub circulating_supply: String,
            pub coin: String,
            pub day_ntl_vlm: String,
            pub mark_px: String,
            pub mid_px: Option<String>,
            pub prev_day_px: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(untagged)]
        pub enum SpotMetaAndAssetCtxs {
            Meta(SpotMeta),
            Ctx(Vec<SpotCtx>),
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct Balance {
            pub coin: String,
            pub hold: String,
            pub total: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct UserSpotState {
            pub balances: Vec<Balance>,
        }
    }
}

pub mod exchange {
    pub mod request {

        use ethers::{
            abi::{encode, ParamType, Token, Tokenizable},
            types::{
                transaction::eip712::{
                    encode_eip712_type, make_type_hash, EIP712Domain, Eip712, Eip712Error,
                },
                Address, Signature, H256, U256,
            },
            utils::keccak256,
        };
        use serde::{Deserialize, Serialize};

        use crate::{
            types::{Cloid, HyperliquidChain},
            utils::{as_hex, as_hex_option},
            Error, Result,
        };

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "PascalCase")]
        pub enum Tif {
            Gtc,
            Ioc,
            Alo,
            FrontendMarket,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Limit {
            pub tif: Tif,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "lowercase")]
        pub enum TpSl {
            Tp,
            Sl,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Trigger {
            pub is_market: bool,
            pub trigger_px: String,
            pub tpsl: TpSl,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub enum OrderType {
            Limit(Limit),
            Trigger(Trigger),
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct OrderRequest {
            #[serde(rename = "a", alias = "asset")]
            pub asset: u32,
            #[serde(rename = "b", alias = "isBuy")]
            pub is_buy: bool,
            #[serde(rename = "p", alias = "limitPx")]
            pub limit_px: String,
            #[serde(rename = "s", alias = "sz")]
            pub sz: String,
            #[serde(rename = "r", alias = "reduceOnly", default)]
            pub reduce_only: bool,
            #[serde(rename = "t", alias = "orderType")]
            pub order_type: OrderType,
            #[serde(
                rename = "c",
                alias = "cloid",
                serialize_with = "as_hex_option",
                skip_serializing_if = "Option::is_none"
            )]
            pub cloid: Option<Cloid>,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub enum Grouping {
            Na,
            NormalTpsl,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct CancelRequest {
            #[serde(rename = "a", alias = "asset")]
            pub asset: u32,
            #[serde(rename = "o", alias = "oid")]
            pub oid: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct CancelByCloidRequest {
            pub asset: u32,
            #[serde(serialize_with = "as_hex")]
            pub cloid: Cloid,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct ModifyRequest {
            pub oid: u64,
            pub order: OrderRequest,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct TwapRequest {
            #[serde(rename = "a", alias = "asset")]
            pub asset: u32,
            #[serde(rename = "b", alias = "isBuy")]
            pub is_buy: bool,
            #[serde(rename = "s", alias = "sz")]
            pub sz: String,
            #[serde(rename = "r", alias = "reduceOnly", default)]
            pub reduce_only: bool,
            /// Running Time (5m - 24h)
            #[serde(rename = "m", alias = "duration")]
            pub duration: u64,
            /// if set to true, the size of each sub-trade will be automatically adjusted
            /// within a certain range, typically upto to 20% higher or lower than the original trade size
            #[serde(rename = "t", alias = "randomize")]
            pub randomize: bool,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Withdraw3 {
            pub signature_chain_id: U256,
            pub hyperliquid_chain: HyperliquidChain,
            pub destination: String,
            pub amount: String,
            pub time: u64,
        }

        impl Eip712 for Withdraw3 {
            type Error = Eip712Error;

            fn domain(&self) -> std::result::Result<EIP712Domain, Self::Error> {
                Ok(EIP712Domain {
                    name: Some("HyperliquidSignTransaction".into()),
                    version: Some("1".into()),
                    chain_id: Some(self.signature_chain_id),
                    verifying_contract: Some(Address::zero()),
                    salt: None,
                })
            }

            fn type_hash() -> std::result::Result<[u8; 32], Self::Error> {
                Ok(make_type_hash(
                    "HyperliquidTransaction:Withdraw".into(),
                    &[
                        ("hyperliquidChain".to_string(), ParamType::String),
                        ("destination".to_string(), ParamType::String),
                        ("amount".to_string(), ParamType::String),
                        ("time".to_string(), ParamType::Uint(64)),
                    ],
                ))
            }

            fn struct_hash(&self) -> std::result::Result<[u8; 32], Self::Error> {
                Ok(keccak256(encode(&[
                    Token::Uint(Self::type_hash()?.into()),
                    encode_eip712_type(self.hyperliquid_chain.to_string().into_token()),
                    encode_eip712_type(self.destination.clone().into_token()),
                    encode_eip712_type(self.amount.clone().into_token()),
                    encode_eip712_type(self.time.into_token()),
                ])))
            }
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Agent {
            pub source: String,
            pub connection_id: H256,
        }

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

        impl Eip712 for UsdSend {
            type Error = Eip712Error;

            fn domain(&self) -> std::result::Result<EIP712Domain, Self::Error> {
                Ok(EIP712Domain {
                    name: Some("HyperliquidSignTransaction".into()),
                    version: Some("1".into()),
                    chain_id: Some(self.signature_chain_id),
                    verifying_contract: Some(Address::zero()),
                    salt: None,
                })
            }

            fn type_hash() -> std::result::Result<[u8; 32], Self::Error> {
                Ok(make_type_hash(
                    "HyperliquidTransaction:UsdSend".into(),
                    &[
                        ("hyperliquidChain".to_string(), ParamType::String),
                        ("destination".to_string(), ParamType::String),
                        ("amount".to_string(), ParamType::String),
                        ("time".to_string(), ParamType::Uint(64)),
                    ],
                ))
            }

            fn struct_hash(&self) -> std::result::Result<[u8; 32], Self::Error> {
                Ok(keccak256(encode(&[
                    Token::Uint(Self::type_hash()?.into()),
                    encode_eip712_type(self.hyperliquid_chain.to_string().into_token()),
                    encode_eip712_type(self.destination.clone().into_token()),
                    encode_eip712_type(self.amount.clone().into_token()),
                    encode_eip712_type(self.time.into_token()),
                ])))
            }
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct ApproveAgent {
            pub signature_chain_id: U256,
            pub hyperliquid_chain: HyperliquidChain,
            pub agent_address: Address,
            #[serde(skip_serializing_if = "Option::is_none")]
            pub agent_name: Option<String>,
            pub nonce: u64,
        }

        impl Eip712 for ApproveAgent {
            type Error = Eip712Error;

            fn domain(&self) -> std::result::Result<EIP712Domain, Self::Error> {
                Ok(EIP712Domain {
                    name: Some("HyperliquidSignTransaction".into()),
                    version: Some("1".into()),
                    chain_id: Some(self.signature_chain_id),
                    verifying_contract: Some(Address::zero()),
                    salt: None,
                })
            }

            fn type_hash() -> std::result::Result<[u8; 32], Self::Error> {
                Ok(make_type_hash(
                    "HyperliquidTransaction:ApproveAgent".into(),
                    &[
                        ("hyperliquidChain".to_string(), ParamType::String),
                        ("agentAddress".to_string(), ParamType::Address),
                        ("agentName".to_string(), ParamType::String),
                        ("nonce".to_string(), ParamType::Uint(64)),
                    ],
                ))
            }

            fn struct_hash(&self) -> std::result::Result<[u8; 32], Self::Error> {
                Ok(keccak256(encode(&[
                    Token::Uint(Self::type_hash()?.into()),
                    encode_eip712_type(self.hyperliquid_chain.to_string().into_token()),
                    encode_eip712_type(self.agent_address.into_token()),
                    encode_eip712_type(self.agent_name.clone().unwrap_or_default().into_token()),
                    encode_eip712_type(self.nonce.into_token()),
                ])))
            }
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase", tag = "type")]
        pub enum Action {
            Order {
                orders: Vec<OrderRequest>,
                grouping: Grouping,
            },
            Cancel {
                cancels: Vec<CancelRequest>,
            },
            CancelByCloid {
                cancels: Vec<CancelByCloidRequest>,
            },

            Modify(ModifyRequest),

            BatchModify {
                modifies: Vec<ModifyRequest>,
            },
            TwapOrder {
                twap: TwapRequest,
            },
            UsdSend(UsdSend),

            Withdraw3(Withdraw3),
            #[serde(rename_all = "camelCase")]
            UpdateLeverage {
                asset: u32,
                is_cross: bool,
                leverage: u32,
            },
            #[serde(rename_all = "camelCase")]
            UpdateIsolatedMargin {
                asset: u32,
                is_buy: bool,
                ntli: i64,
            },
            ApproveAgent(ApproveAgent),
            CreateSubAccount {
                name: String,
            },
            #[serde(rename_all = "camelCase")]
            SubAccountModify {
                sub_account_user: Address,
                name: String,
            },
            #[serde(rename_all = "camelCase")]
            SubAccountTransfer {
                sub_account_user: Address,
                is_deposit: bool,
                usd: u64,
            },
            SetReferrer {
                code: String,
            },
            ScheduleCancel {
                time: u64,
            },
        }

        impl Action {
            /// create connection id for agent
            pub fn connection_id(
                &self,
                vault_address: Option<Address>,
                nonce: u64,
            ) -> Result<H256> {
                let mut encoded = rmp_serde::to_vec_named(self)
                    .map_err(|e| Error::RmpSerdeError(e.to_string()))?;

                encoded.extend((nonce).to_be_bytes());

                if let Some(address) = vault_address {
                    encoded.push(1);
                    encoded.extend(address.to_fixed_bytes());
                } else {
                    encoded.push(0)
                }

                Ok(keccak256(encoded).into())
            }
        }

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

    pub mod response {
        use ethers::types::Address;
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Serialize, Deserialize)]
        pub struct Resting {
            pub oid: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Filled {
            pub oid: u64,
            pub total_sz: String,
            pub avg_px: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct TwapId {
            pub twap_id: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub enum Status {
            Resting(Resting),
            Filled(Filled),
            Error(String),
            Success,
            WaitingForFill,
            WaitingForTrigger,
            Running(TwapId),
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub enum StatusType {
            Statuses(Vec<Status>),
            Status(Status),
            #[serde(untagged)]
            Address(Address),
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct Data {
            #[serde(rename = "type")]
            pub type_: String,
            pub data: Option<StatusType>,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase", tag = "status", content = "response")]
        pub enum Response {
            Ok(Data),
            Err(String),
        }
    }
}

pub mod websocket {
    pub mod request {
        use ethers::types::Address;
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Serialize, Deserialize, Clone)]
        #[serde(rename_all = "camelCase", tag = "type")]
        pub enum Subscription {
            AllMids,
            Notification { user: Address },
            OrderUpdates { user: Address },
            User { user: Address },
            WebData { user: Address },
            L2Book { coin: String },
            Trades { coin: String },
            Candle { coin: String, interval: String },
        }

        #[derive(Clone)]
        pub struct Channel {
            pub id: u64,
            pub sub: Subscription,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "lowercase")]
        pub enum Method {
            Subscribe,
            Unsubscribe,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct Request {
            pub method: Method,
            pub subscription: Subscription,
        }
    }

    pub mod response {
        use std::collections::HashMap;

        use ethers::types::{Address, TxHash};
        use serde::{Deserialize, Serialize};
        use serde_json::Value;

        use crate::types::{
            info::response::{CandleSnapshot, Ctx, Universe, UserFill, UserState},
            Side,
        };

        #[derive(Debug, Serialize, Deserialize)]
        pub struct AllMids {
            pub mids: HashMap<String, String>,
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct Notification {
            pub notification: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct LedgerUpdate {
            pub hash: TxHash,
            pub delta: Value,
            pub time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct WebData {
            pub user_state: UserState,
            pub lending_vaults: Option<Vec<Value>>,
            pub total_vault_equity: String,
            pub open_orders: Vec<Value>,
            pub fills: Vec<Value>,
            pub whitelisted: bool,
            pub ledger_updates: Vec<LedgerUpdate>,
            pub agent_address: Address,
            pub pending_withdraws: Option<Vec<Value>>,
            pub cum_ledger: String,
            pub meta: Universe,
            pub asset_contexts: Option<Vec<Ctx>>,
            pub order_history: Vec<Value>,
            pub server_time: u64,
            pub is_vault: bool,
            pub user: Address,
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct WsTrade {
            pub coin: String,
            pub side: String,
            pub px: String,
            pub sz: String,
            pub hash: TxHash,
            pub time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct WsLevel {
            pub px: String,
            pub sz: String,
            pub n: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct WsBook {
            pub coin: String,
            pub levels: Vec<Vec<WsLevel>>,
            pub time: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct WsBasicOrder {
            pub coin: String,
            pub side: Side,
            pub limit_px: String,
            pub sz: String,
            pub oid: u64,
            pub timestamp: u64,
            pub orig_sz: String,
            #[serde(default)]
            pub reduce_only: bool,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct WsOrder {
            pub order: WsBasicOrder,
            pub status: String,
            pub status_timestamp: u64,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct WsUserFunding {
            pub time: u64,
            pub coin: String,
            pub usdc: String,
            pub szi: String,
            pub funding_rate: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "snake_case")]
        pub struct WsLiquidation {
            pub liq: u64,
            pub liquidator: String,
            pub liquidated_user: String,
            pub liquidated_ntl_pos: String,
            pub liquidated_account_value: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct WsNonUserCancel {
            pub oid: u64,
            pub coin: String,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase", untagged)]
        pub enum WsUserEvent {
            WsFill(Vec<UserFill>),
            WsUserFunding(WsUserFunding),
            WsLiquidation(WsLiquidation),
            WsNonUserCancel(Vec<WsNonUserCancel>),
        }

        #[derive(Debug, Serialize, Deserialize)]
        pub struct Channel {
            pub method: String,
            pub subscription: Value,
        }

        #[derive(Debug, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase", tag = "channel", content = "data")]
        pub enum Response {
            AllMids(AllMids),
            Notification(Notification),
            WebData(WebData),
            Candle(CandleSnapshot),
            L2Book(WsBook),
            Trades(Vec<WsTrade>),
            OrderUpdates(Vec<WsOrder>),
            User(WsUserEvent),
            SubscriptionResponse(Channel),
        }
    }
}