1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
//! HTTP client for HyperCore API interactions.
//!
//! This module provides the HTTP client for placing orders, querying balances,
//! managing positions, and performing asset transfers on Hyperliquid.
//!
//! # Examples
//!
//! ## Query User Balances
//!
//! ```no_run
//! use hypersdk::hypercore;
//! use hypersdk::Address;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = hypercore::mainnet();
//! let user: Address = "0x...".parse()?;
//! let balances = client.user_balances(user).await?;
//!
//! for balance in balances {
//! println!("{}: {}", balance.coin, balance.total);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Place Orders
//!
//! ```no_run
//! use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = hypercore::mainnet();
//! let signer: PrivateKeySigner = "your_key".parse()?;
//!
//! // Note: This example shows the structure but cannot run without
//! // the rust_decimal_macros::dec!() macro and chrono clock feature.
//! // In real usage, replace with actual decimal values and timestamp.
//! # Ok(())
//! # }
//! ```
use std::{
collections::{HashMap, VecDeque},
time::Duration,
};
use alloy::{
primitives::{Address, Bytes},
signers::{Signer, SignerSync},
};
use anyhow::{Context, Result, anyhow};
use chrono::{DateTime, Utc};
use rust_decimal::{Decimal, prelude::ToPrimitive};
use serde::Deserialize;
use url::Url;
use super::{ApiError, AssetTarget, signing::*};
use crate::hypercore::{
ActionError, ApiAgent, Builder, CandleInterval, Chain, Cloid, Dex, GossipPriorityAuctionStatus,
Market, MultiSigConfig, OidOrCloid, OutcomeMeta, PerpMarket, SettledOutcome, Signature,
SpotMarket, SpotToken,
api::{
Action, ActionRequest, AddressEncoding, ApproveAgent, ApproveBuilderFee, Aqav2Role,
AuthorizeAqav2Role, BorrowLendAction, CSignerAction, CValidatorAction,
ConvertToMultiSigUser, CreateVault, FinalizeEvmContract, FinalizeEvmContractInput,
GossipPriorityBid, Hip3LiquidatorTransferAction, LinkStakingUserAction, ModifyAction,
OkResponse, Response, SendToEvmWithDataAction, SignersConfig, SpotUserAction,
StakingLinkDisableTradingUserAction, SubAccountModify, SubAccountSpotTransfer,
SubAccountTransfer, ToggleSpotDusting, TokenDelegateAction, TopUpIsolatedOnlyMargin,
TrailingStop, TwapOrderParams, UpdateIsolatedMargin, UpdateLeverage,
UsdClassTransferAction, UserOutcomeAction, UserPortfolioMarginAction, ValidatorL1Stream,
VaultDistribute, VaultModify, VaultTransfer, Withdraw3Action,
},
deploy::{ActivateOutcomeDeployer, OutcomeDeploy, PerpDeployAction, SpotDeployAction},
mainnet_url, testnet_url,
types::{
AbstractionMode, ActiveAssetData, AgentSendAsset, BasicOrder, BatchCancel,
BatchCancelCloid, BatchModify, BatchOrder, ClearinghouseState, Delegation,
DelegatorSummary, DeployAuctionStatus, ExchangeStatus, Fill, FundingRate, InfoRequest,
L2Book, LegalCheck, MarginTable, OrderGrouping, OrderRequest, OrderResponseStatus,
OrderTypePlacement, OrderUpdate, PerpDexDetails, PerpDexLimits, PerpDexStatus,
PreTransferCheck, PredictedFundingVenue, ScheduleCancel, SendAsset, SendToken, SpotSend,
SubAccount, TimeInForce, TokenDetails, Trade, TwapSliceFill, UsdSend, UsdcRouting,
UserBalance, UserFees, UserFundingEntry, UserRateLimit, UserRole, UserSetAbstractionAction,
UserStarState, UserVaultEquity, VaultDetails,
},
};
/// HTTP client for HyperCore API.
///
/// Provides methods for trading, querying market data, managing positions,
/// and performing asset transfers.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore;
///
/// let client = hypercore::mainnet();
/// // Use client for API calls
/// ```
pub struct Client {
http_client: reqwest::Client,
base_url: Url,
chain: Chain,
}
impl Client {
/// Creates a new HTTP client for the specified chain.
///
/// The base URL is automatically determined based on the chain:
/// - `Chain::Mainnet`: `https://api.hyperliquid.xyz`
/// - `Chain::Testnet`: `https://api.hyperliquid-testnet.xyz`
///
/// All actions signed by this client will use chain-specific values:
/// - Agent source field: `"a"` for mainnet, `"b"` for testnet
/// - Multisig chain ID: `"0x66eee"` for mainnet, `"0x66eef"` for testnet
///
/// # Example
///
/// ```
/// use hypersdk::hypercore::{HttpClient, Chain};
///
/// // Create a mainnet client
/// let mainnet_client = HttpClient::new(Chain::Mainnet);
///
/// // Create a testnet client
/// let testnet_client = HttpClient::new(Chain::Testnet);
/// ```
pub fn new(chain: Chain) -> Self {
let base_url = if chain.is_mainnet() {
mainnet_url()
} else {
testnet_url()
};
let http_client = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.tcp_nodelay(true)
.build()
.unwrap();
Self {
http_client,
base_url,
chain,
}
}
/// Sets a custom base URL for this client.
///
/// This is useful when connecting to a custom Hyperliquid node or proxy.
/// The chain configuration is preserved.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore::{HttpClient, Chain};
/// use url::Url;
///
/// let custom_url: Url = "https://my-custom-node.example.com".parse().unwrap();
/// let client = HttpClient::new(Chain::Mainnet)
/// .with_url(custom_url);
/// ```
pub fn with_url(self, base_url: Url) -> Self {
Self { base_url, ..self }
}
/// Sets a custom [`reqwest::Client`] for HTTP requests.
///
/// Use this when you need custom configuration such as proxies, custom TLS settings,
/// connection pooling, or timeout policies.
#[must_use]
pub fn with_http_client(self, http_client: reqwest::Client) -> Self {
Self {
http_client,
..self
}
}
/// Returns the chain this client is configured for.
#[must_use]
pub const fn chain(&self) -> Chain {
self.chain
}
/// Creates a WebSocket connection using the same base URL as this HTTP client.
///
/// # Example
///
/// ```
/// use hypersdk::hypercore;
/// use futures::StreamExt;
///
/// # async fn example() {
/// let client = hypercore::mainnet();
/// let mut ws = client.websocket();
/// // Subscribe and process messages
/// # }
/// ```
pub fn websocket(&self) -> super::WebSocket {
let mut url = self.base_url.clone();
let _ = url.set_scheme("wss");
url.set_path("/ws");
super::WebSocket::new(url)
}
/// Creates a WebSocket connection without TLS (uses `ws://` instead of `wss://`).
///
/// Useful for testing or local development.
pub fn websocket_no_tls(&self) -> super::WebSocket {
let mut url = self.base_url.clone();
let _ = url.set_scheme("ws");
url.set_path("/ws");
super::WebSocket::new(url)
}
/// Fetches all available perpetual futures markets.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let perps = client.perps().await?;
///
/// for market in perps {
/// println!("{}: {}x leverage", market.name, market.max_leverage);
/// }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub async fn perps(&self) -> Result<Vec<PerpMarket>> {
super::perp_markets(self.base_url.clone(), self.http_client.clone(), None).await
}
/// Fetches perpetual markets from a specific DEX.
///
/// Returns a list of perpetual futures markets available on the specified DEX.
/// Use this when you want to query markets from a specific exchange rather than
/// the default Hyperliquid DEX.
///
/// # Parameters
///
/// - `dex`: The DEX to query markets from
///
/// # Example
///
/// ```no_run
/// # use hypersdk::hypercore;
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
///
/// // Get available DEXes
/// let dexes = client.perp_dexes().await?;
///
/// // Query markets from a specific DEX
/// if let Some(dex) = dexes.first() {
/// let markets = client.perps_from(dex.clone()).await?;
/// for market in markets {
/// println!("{}: {}x leverage", market.name, market.max_leverage);
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub async fn perps_from(&self, dex: Dex) -> Result<Vec<PerpMarket>> {
super::perp_markets(self.base_url.clone(), self.http_client.clone(), Some(dex)).await
}
/// Fetches all available perpetual futures DEXes.
///
/// Returns a list of all DEXes that offer perpetual futures trading on Hyperliquid.
/// Each DEX has a unique name and index.
///
/// # Example
///
/// ```no_run
/// # use hypersdk::hypercore;
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let dexes = client.perp_dexes().await?;
///
/// for dex in dexes {
/// println!("DEX: {}", dex.name());
/// }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub async fn perp_dexes(&self) -> Result<Vec<Dex>> {
super::perp_dexes(self.base_url.clone(), self.http_client.clone()).await
}
/// Misspelled alias of [`Self::perp_dexes`].
#[deprecated(since = "0.2.9", note = "use perp_dexes instead")]
#[inline(always)]
pub async fn perp_dexs(&self) -> Result<Vec<Dex>> {
self.perp_dexes().await
}
/// Fetches all available spot markets.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let spots = client.spot().await?;
///
/// for market in spots {
/// println!("{}", market.symbol());
/// }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub async fn spot(&self) -> Result<Vec<SpotMarket>> {
super::spot_markets(self.base_url.clone(), self.http_client.clone()).await
}
/// Fetches all available spot tokens.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let tokens = client.spot_tokens().await?;
///
/// for token in tokens {
/// println!("{}: {} decimals", token.name, token.sz_decimals);
/// }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub async fn spot_tokens(&self) -> Result<Vec<SpotToken>> {
super::spot_tokens(self.base_url.clone(), self.http_client.clone()).await
}
/// Fetches outcome market metadata.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::testnet();
/// let meta = client.outcome_meta().await?;
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub async fn outcome_meta(&self) -> Result<OutcomeMeta> {
super::outcome_meta(self.base_url.clone(), self.http_client.clone()).await
}
/// Fetch all outcome markets, one per side.
///
/// Returns a list of [`super::OutcomeMarket`] with the market index
/// derived from outcome ID and side position.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::testnet();
/// let markets = client.outcomes().await?;
/// for m in markets {
/// println!("{}: O{} {} (market {})", m.coin(), m.info.outcome, m.side, m.market);
/// }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub async fn outcomes(&self) -> Result<Vec<super::OutcomeMarket>> {
super::outcomes(self.base_url.clone(), self.http_client.clone()).await
}
/// Send an info request to `/info` and deserialize the JSON response.
///
/// Private helper that encapsulates the repeated HTTP send → check status →
/// parse JSON workflow used across all unsigned info endpoint methods.
///
/// The `label` parameter is included in error messages for debugging — it should
/// identify the calling endpoint (e.g., `"open_orders"`, `"user_balances"`).
pub(crate) async fn send_info_request<R>(
&self,
label: &str,
req: &impl serde::Serialize,
) -> Result<R>
where
R: for<'de> Deserialize<'de>,
{
let mut api_url = self.base_url.clone();
api_url.set_path("/info");
let res = self.http_client.post(api_url).json(&req).send().await?;
let status = res.status();
let bytes = res.bytes().await?;
let text = String::from_utf8_lossy(&bytes);
if !status.is_success() {
return Err(ApiError(format!("[{label}] HTTP {status} body={text}")).into());
}
serde_json::from_str(&text).with_context(|| format!("[{label}] body={text}"))
}
/// Returns all open orders for a user.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user: Address = "0x...".parse()?;
/// let orders = client.open_orders(user, None).await?;
///
/// for order in orders {
/// println!("{} {} @ {}", order.side, order.sz, order.limit_px);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn open_orders(
&self,
user: Address,
dex_name: Option<String>,
) -> Result<Vec<BasicOrder>> {
let req = InfoRequest::FrontendOpenOrders {
user,
dex: dex_name,
};
self.send_info_request("open_orders", &req).await
}
/// Returns mid prices for all perpetual markets.
///
/// Returns a map of market name to mid price.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let mids = client.all_mids(None).await?;
///
/// for (market, price) in mids {
/// println!("{}: {}", market, price);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn all_mids(&self, dex_name: Option<String>) -> Result<HashMap<String, Decimal>> {
let req = InfoRequest::AllMids { dex: dex_name };
self.send_info_request("all_mids", &req).await
}
/// Retrieves historical orders for a user.
///
/// Returns all past (non-open) orders, including filled, canceled, and expired orders.
pub async fn historical_orders(&self, user: Address) -> Result<Vec<OrderUpdate<BasicOrder>>> {
let req = InfoRequest::HistoricalOrders { user };
self.send_info_request("historical_orders", &req).await
}
/// Returns the user's fills.
///
/// Retrieves all trade fills (executed orders) for a user, including the fill price, size,
/// side, and associated order ID.
pub async fn user_fills(&self, user: Address) -> Result<Vec<Fill>> {
let req = InfoRequest::UserFills {
user,
aggregate_by_time: None,
};
self.send_info_request("user_fills", &req).await
}
/// Returns the user's fills filtered by time range.
///
/// Retrieves all trade fills for a user within the specified time window.
/// This is useful for P&L calculation and trade history analysis.
///
/// # Parameters
///
/// - `user`: The address to query fills for
/// - `start_time`: Start timestamp in milliseconds (inclusive)
/// - `end_time`: Optional end timestamp in milliseconds (inclusive). Defaults to now if `None`.
pub async fn user_fills_by_time(
&self,
user: Address,
start_time: u64,
end_time: Option<u64>,
) -> Result<Vec<Fill>> {
let req = InfoRequest::UserFillsByTime {
user,
start_time,
end_time,
aggregate_by_time: None,
};
self.send_info_request("user_fills_by_time", &req).await
}
/// Returns the status of an order.
///
/// Checks whether an order is still open, filled, canceled, or unknown.
/// Returns `None` if the order ID is not found.
///
/// # Parameters
///
/// - `user`: The address that placed the order
/// - `oid`: Either an exchange-assigned order ID (OID) or a client-assigned order ID (CLOID)
pub async fn order_status(
&self,
user: Address,
oid: OidOrCloid,
) -> Result<Option<OrderUpdate<BasicOrder>>> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "status")]
enum Response {
Order { order: OrderUpdate<BasicOrder> },
UnknownOid,
}
let req = InfoRequest::OrderStatus { user, oid };
let data: Response = self.send_info_request("order_status", &req).await?;
Ok(match data {
Response::Order { order } => Some(order),
Response::UnknownOid => None,
})
}
/// Returns historical candlestick data for a market.
///
/// Retrieves OHLCV (Open, High, Low, Close, Volume) candlestick data for the specified
/// market and time range. Only the most recent 5000 candles are available.
///
/// # Parameters
///
/// - `coin`: Market symbol (e.g., "BTC", "ETH"). For HIP-3 assets, prefix with dex name (e.g., "xyz:XYZ100")
/// - `interval`: Candle interval (e.g., "1m", "15m", "1h", "1d")
/// - `start_time`: Start time in milliseconds
/// - `end_time`: End time in milliseconds
///
/// # Available Intervals
///
/// - Minutes: 1m, 3m, 5m, 15m, 30m
/// - Hours: 1h, 2h, 4h, 8h, 12h
/// - Days: 1d, 3d, 1w, 1M
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, CandleInterval};
/// use chrono::{Utc, Duration};
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
///
/// // Get last 100 15-minute candles
/// let end_time = Utc::now().timestamp_millis() as u64;
/// let start_time = (Utc::now() - Duration::hours(25)).timestamp_millis() as u64;
///
/// let candles = client
/// .candle_snapshot("BTC", CandleInterval::FifteenMinutes, start_time, end_time)
/// .await?;
///
/// for candle in candles {
/// println!("BTC: O:{} H:{} L:{} C:{} V:{}",
/// candle.open, candle.high, candle.low, candle.close, candle.volume);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn candle_snapshot(
&self,
coin: impl Into<String>,
interval: CandleInterval,
start_time: u64,
end_time: u64,
) -> Result<Vec<super::types::Candle>> {
let req = InfoRequest::CandleSnapshot {
req: super::types::CandleSnapshotRequest {
coin: coin.into(),
interval,
start_time,
end_time,
},
};
self.send_info_request("candle_snapshot", &req).await
}
/// Retrieves spot token balances for a user.
///
/// Returns all tokens the user holds on the spot market, including held (locked) and total amounts.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user: Address = "0x...".parse()?;
/// let balances = client.user_balances(user).await?;
///
/// for balance in balances {
/// println!("{}: total={}, held={}", balance.coin, balance.total, balance.hold);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn user_balances(&self, user: Address) -> Result<Vec<UserBalance>> {
#[derive(Deserialize)]
struct Balances {
balances: Vec<UserBalance>,
}
let req = InfoRequest::SpotClearinghouseState { user };
let data: Balances = self.send_info_request("user_balances", &req).await?;
Ok(data.balances)
}
/// Retrieves user-specific fee rates.
///
/// Returns effective maker/taker rates for perps and spot, referral discount,
/// daily volume, and staking discount information.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user: Address = "0x...".parse()?;
/// let fees = client.user_fees(user).await?;
///
/// println!("maker={} taker={} referral_discount={}",
/// fees.maker_rate,
/// fees.taker_rate,
/// fees.active_referral_discount
/// );
/// # Ok(())
/// # }
/// ```
pub async fn user_fees(&self, user: Address) -> Result<UserFees> {
let req = InfoRequest::UserFees { user };
self.send_info_request("user_fees", &req).await
}
/// Retrieves the clearinghouse state for a user's perpetual positions.
///
/// Returns the complete state of a user's perpetual trading account, including
/// margin summaries, withdrawable amounts, and all open positions.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user: Address = "0x...".parse()?;
/// let state = client.clearinghouse_state(user, None).await?;
///
/// // Check account value and withdrawable amount
/// println!("Account value: {}", state.margin_summary.account_value);
/// println!("Withdrawable: {}", state.withdrawable);
///
/// // Check margin utilization
/// let utilization = state.margin_summary.margin_utilization();
/// println!("Margin utilization: {}%", utilization);
///
/// // Iterate through positions
/// for asset_position in &state.asset_positions {
/// let pos = &asset_position.position;
/// println!("{} {}: {} @ {:?} (PnL: {})",
/// pos.side(),
/// pos.coin,
/// pos.szi,
/// pos.entry_px,
/// pos.unrealized_pnl
/// );
/// }
/// # Ok(())
/// # }
/// ```
pub async fn clearinghouse_state(
&self,
user: Address,
dex_name: Option<String>,
) -> Result<ClearinghouseState> {
let req = InfoRequest::ClearinghouseState {
user,
dex: dex_name,
};
self.send_info_request("clearinghouse_state", &req).await
}
/// Retrieves historical funding rates for a perpetual market.
///
/// Returns funding rate snapshots for the specified coin within the given time range.
/// Hyperliquid pays funding every hour.
///
/// # Parameters
///
/// - `coin`: Market symbol (e.g., "BTC", "ETH")
/// - `start_time`: Start time in milliseconds (inclusive)
/// - `end_time`: Optional end time in milliseconds (inclusive). Defaults to current time.
///
/// # Notes
///
/// - Only the most recent 500 records are returned per request
/// - To paginate, use the last returned timestamp as the next `start_time`
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
///
/// // Get BTC funding rates from the last 24 hours
/// let end_time = chrono::Utc::now().timestamp_millis() as u64;
/// let start_time = end_time - 24 * 60 * 60 * 1000; // 24 hours ago
///
/// let rates = client.funding_history("BTC", start_time, Some(end_time)).await?;
///
/// for rate in rates {
/// println!("Funding rate at {}: {} (premium: {})",
/// rate.time, rate.funding_rate, rate.premium);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn funding_history(
&self,
coin: impl Into<String>,
start_time: u64,
end_time: Option<u64>,
) -> Result<Vec<FundingRate>> {
let req = InfoRequest::FundingHistory {
coin: coin.into(),
start_time,
end_time,
};
self.send_info_request("funding_history", &req).await
}
/// Retrieves the multi-signature wallet configuration for a user.
///
/// Returns the list of authorized signers and the signature threshold required
/// for executing transactions on behalf of a multisig account.
///
/// # Arguments
///
/// * `user` - The address of the multisig account to query
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let multisig_addr = "0x1234567890abcdef1234567890abcdef12345678".parse()?;
///
/// // Get multisig configuration
/// let config = client.multi_sig_config(multisig_addr).await?;
///
/// println!("Multisig requires {} of {} signatures",
/// config.threshold,
/// config.authorized_users.len()
/// );
///
/// for (i, signer) in config.authorized_users.iter().enumerate() {
/// println!("Authorized signer {}: {:?}", i + 1, signer);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn multi_sig_config(&self, user: Address) -> Result<MultiSigConfig> {
let req = InfoRequest::UserToMultiSigSigners { user };
self.send_info_request("multi_sig_config", &req).await
}
/// Get API agents for a user.
///
/// Returns a list of additional agents authorized to act on behalf of the specified user.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use alloy::primitives::address;
/// async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user = address!("0000000000000000000000000000000000000000");
/// let agents = client.api_agents(user).await?;
///
/// for agent in agents {
/// println!("Agent {}: {:?}, valid until: {:?}", agent.name, agent.address, agent.valid_until);
/// }
///
/// Ok(())
/// }
/// ```
pub async fn api_agents(&self, user: Address) -> Result<Vec<ApiAgent>> {
let req = InfoRequest::ExtraAgents { user };
self.send_info_request("api_agents", &req).await
}
/// Retrieve details for a vault.
///
/// Returns comprehensive information about a vault including performance metrics,
/// follower information, and configuration.
///
/// # Parameters
///
/// - `vault_address`: The address of the vault to query
/// - `user`: Optional user address to include follower state for that user
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let vault: Address = "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303".parse()?;
///
/// // Get vault details without user-specific follower state
/// let details = client.vault_details(vault, None).await?;
/// println!("Vault: {} (APR: {}%)", details.name, details.apr);
///
/// // Get vault details with user-specific follower state
/// let user: Address = "0x...".parse()?;
/// let details_with_state = client.vault_details(vault, Some(user)).await?;
/// if let Some(state) = details_with_state.follower_state {
/// println!("Your equity: {}", state.vault_equity);
/// }
/// # Ok(())
/// # }
/// ```
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-details-for-a-vault>
pub async fn vault_details(
&self,
vault_address: Address,
user: Option<Address>,
) -> Result<VaultDetails> {
let req = InfoRequest::VaultDetails {
vault_address,
user,
};
self.send_info_request("vault_details", &req).await
}
/// Retrieve a user's vault deposits.
///
/// Returns all vaults that a user has deposited into, along with their
/// current equity in each vault.
///
/// # Parameters
///
/// - `user`: The address of the user to query vault deposits for
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user: Address = "0x...".parse()?;
///
/// let equities = client.user_vault_equities(user).await?;
/// for equity in equities {
/// println!("Vault {:?}: equity = {}", equity.vault_address, equity.equity);
/// }
/// # Ok(())
/// # }
/// ```
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-vault-deposits>
pub async fn user_vault_equities(&self, user: Address) -> Result<Vec<UserVaultEquity>> {
let req = InfoRequest::UserVaultEquities { user };
self.send_info_request("user_vault_equities", &req).await
}
/// Query a user's role.
///
/// Returns the role of an address in the Hyperliquid system. This can be used
/// to determine if an address is a regular user, vault, agent, or subaccount.
///
/// # Parameters
///
/// - `user`: The address to query the role for
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let addr: Address = "0x...".parse()?;
///
/// let role = client.user_role(addr).await?;
/// match role {
/// hypersdk::hypercore::types::UserRole::User => println!("Regular user"),
/// hypersdk::hypercore::types::UserRole::Vault => println!("Vault account"),
/// hypersdk::hypercore::types::UserRole::Agent { user } => {
/// println!("Agent wallet for {}", user);
/// }
/// hypersdk::hypercore::types::UserRole::SubAccount { master } => println!("Subaccount {master}"),
/// hypersdk::hypercore::types::UserRole::Missing => println!("Not found"),
/// }
/// # Ok(())
/// # }
/// ```
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-a-users-role>
pub async fn user_role(&self, user: Address) -> Result<UserRole> {
let req = InfoRequest::UserRole { user };
self.send_info_request("user_role", &req).await
}
/// Retrieve a user's subaccounts.
///
/// Returns all subaccounts associated with a master account, including their
/// clearinghouse state (perpetuals) and spot balances.
///
/// # Parameters
///
/// - `user`: The address of the master account
///
/// # Notes
///
/// Subaccounts do not have private keys. To perform actions on behalf of a
/// subaccount, signing should be done by the master account with the
/// `vault_address` parameter set to the subaccount's address.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let master: Address = "0x...".parse()?;
///
/// let subaccounts = client.subaccounts(master).await?;
/// for sub in subaccounts {
/// println!("Subaccount '{}': {:?}", sub.name, sub.sub_account_user);
/// println!(" Account value: {}", sub.clearinghouse_state.margin_summary.account_value);
/// println!(" Withdrawable: {}", sub.clearinghouse_state.withdrawable);
///
/// // Check spot balances
/// for balance in &sub.spot_state.balances {
/// println!(" {}: {}", balance.coin, balance.total);
/// }
/// }
/// # Ok(())
/// # }
/// ```
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-subaccounts>
pub async fn subaccounts(&self, user: Address) -> Result<Vec<SubAccount>> {
let req = InfoRequest::SubAccounts { user };
self.send_info_request("subaccounts", &req).await
}
/// Place a gossip priority bid (Dutch auction for read priority).
///
/// This is a **signed action** sent to `/exchange`. Fees are deducted from your
/// spot HYPE balance and burned. Lower `slot_id` = higher priority (~10ms faster
/// per slot). There are 5 slots (0–4), each running a Dutch auction on a
/// synchronized 3-minute schedule.
///
/// `max_gas` is in **wei of HYPE** — 1 HYPE = 1e18 wei. Example: `50 HYPE`
/// = `U256::from(50u128) * U256::from(1e18)`.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/priority-fees>
#[allow(clippy::too_many_arguments)]
pub async fn gossip_priority_bid<S: SignerSync>(
&self,
signer: &S,
slot_id: u8,
ip: impl Into<String>,
max_gas: u64,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<Response> {
// Debug: print the action JSON to diagnose serialization issues.
let action = GossipPriorityBid {
slot_id,
ip: ip.into(),
max_gas,
};
self.sign_and_send_sync(signer, action, nonce, vault_address, expires_after)
.await
}
/// Query the current gossip priority auction status.
///
/// Returns winning prices, time remaining, and winners for all 5 slots.
/// Use this to decide how much to bid before calling [`Self::gossip_priority_bid`].
///
/// This is an unsigned info request sent to `/info`.
pub async fn gossip_priority_auction_status(&self) -> Result<GossipPriorityAuctionStatus> {
let req = InfoRequest::GossipPriorityAuctionStatus;
self.send_info_request("gossip_priority_auction_status", &req)
.await
}
/// Schedules a cancellation of all open orders at a specified time.
///
/// This is a signed action that tells the exchange to cancel all of the user's
/// open orders at the given timestamp. Useful for risk management — for example,
/// scheduling an end-of-day order sweep.
///
/// # Parameters
///
/// - `signer`: The wallet signing the schedule action
/// - `nonce`: Unique nonce for this request
/// - `when`: The UTC time at which all open orders should be canceled
/// - `vault_address`: Optional vault/subaccount address
/// - `expires_after`: Optional expiration time for the request itself
pub async fn schedule_cancel<S: SignerSync>(
&self,
signer: &S,
nonce: u64,
when: DateTime<Utc>,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let resp = self
.sign_and_send_sync(
signer,
ScheduleCancel {
time: Some(when.timestamp_millis() as u64),
},
nonce,
vault_address,
expires_after,
)
.await?;
resp.into_default()
}
/// Places a batch of orders.
///
/// Submits one or more orders to the exchange. Each order must be signed with your private key.
///
/// # Parameters
///
/// - `signer`: Private key signer for EIP-712 signatures
/// - `batch`: Batch of orders to place
/// - `nonce`: Unique nonce (typically current timestamp in milliseconds)
/// - `vault_address`: Optional vault address if trading on behalf of a vault
/// - `expires_after`: Optional expiration timestamp for the request
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let signer: PrivateKeySigner = "your_key".parse()?;
///
/// // Example order placement - requires dec!() macro and timestamp
/// // let order = BatchOrder { ... };
/// // let nonce = chrono::Utc::now().timestamp_millis() as u64;
/// // let statuses = client.place(&signer, order, nonce, None, None).await?;
/// # Ok(())
/// # }
/// ```
pub fn place<S: SignerSync>(
&self,
signer: &S,
batch: BatchOrder,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<Cloid>>> + Send + 'static
{
let cloids: Vec<_> = batch.orders.iter().map(|req| req.cloid).collect();
let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);
async move {
let resp = future.await.map_err(|err| ActionError {
ids: cloids.clone(),
err: err.to_string(),
})?;
match resp {
Response::Ok(OkResponse::Order { statuses }) => Ok(statuses),
Response::Err(err) => Err(ActionError { ids: cloids, err }),
_ => Err(ActionError {
ids: cloids,
err: format!("unexpected response type: {resp:?}"),
}),
}
}
}
/// Place a market buy or sell order for any tradeable market.
///
/// Uses Hyperliquid's native [`TimeInForce::FrontendMarket`] order type, which
/// fills immediately up to the provided worst acceptable limit price.
///
/// # Parameters
///
/// - `signer`: Private key signer for EIP-712 signatures
/// - `market`: Market to trade on — pass a [`PerpMarket`], [`SpotMarket`], or [`OutcomeMarket`]
/// - `is_buy`: `true` for buy, `false` for sell
/// - `limit_px`: Worst acceptable execution price. Round it to the market tick before calling.
/// - `size`: Position size in base asset units
/// - `nonce`: Unique nonce (typically current timestamp in milliseconds)
/// - `vault_address`: Optional vault address if trading on behalf of a vault
/// - `expires_after`: Optional expiration timestamp for the request
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, NonceHandler};
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::testnet();
/// let signer: hypercore::PrivateKeySigner = "your_key".parse()?;
/// let nonce_handler = NonceHandler::default();
///
/// // Find ETH perpetual market
/// let perps = client.perps().await?;
/// let eth = perps.iter().find(|m| m.name == "ETH").expect("ETH");
///
/// // Market buy 0.01 ETH, accepting fills up to 3500 USDC
/// let statuses = client
/// .market_open(&signer, eth, true, rust_decimal::dec!(3500), rust_decimal::dec!(0.01), nonce_handler.next(), None, None, None)
/// .await?;
///
/// for status in &statuses {
/// println!("Order result: {:?}", status);
/// }
/// # Ok(())
/// # }
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn market_open<S: SignerSync>(
&self,
signer: &S,
market: impl Market,
is_buy: bool,
limit_px: Decimal,
size: Decimal,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
builder: Option<Builder>,
) -> Result<Vec<OrderResponseStatus>> {
let batch = BatchOrder {
orders: vec![OrderRequest {
asset: market.asset_index(),
is_buy,
limit_px,
sz: size,
reduce_only: false,
order_type: OrderTypePlacement::Limit {
tif: TimeInForce::FrontendMarket,
},
cloid: Default::default(),
}],
grouping: OrderGrouping::Na,
builder,
};
Ok(self
.place(signer, batch, nonce, vault_address, expires_after)
.await?)
}
/// Cancel a batch of orders by exchange-assigned order ID (OID).
///
/// Each cancel request specifies an asset and an order ID. Returns the status
/// for each cancellation attempt. Errors are wrapped in [`ActionError`] with the
/// failed OIDs accessible via `.ids()`.
pub fn cancel<S: SignerSync>(
&self,
signer: &S,
batch: BatchCancel,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<u64>>> + Send + 'static
{
let oids: Vec<_> = batch.cancels.iter().map(|req| req.oid).collect();
let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);
async move {
let resp = future.await.map_err(|err| ActionError {
ids: oids.clone(),
err: err.to_string(),
})?;
match resp {
Response::Ok(OkResponse::Cancel { statuses }) => Ok(statuses),
Response::Err(err) => Err(ActionError { ids: oids, err }),
_ => Err(ActionError {
ids: oids,
err: format!("unexpected response type: {resp:?}"),
}),
}
}
}
/// Cancel a batch of orders by client-assigned order ID (CLOID).
///
/// Each cancel request specifies an asset and a client order ID. Returns the status
/// for each cancellation attempt. Errors are wrapped in [`ActionError`] with the
/// failed CLOIDs accessible via `.ids()`.
pub fn cancel_by_cloid<S: SignerSync>(
&self,
signer: &S,
batch: BatchCancelCloid,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<Cloid>>> + Send + 'static
{
let cloids: Vec<_> = batch.cancels.iter().map(|req| req.cloid).collect();
let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);
async move {
let resp = future.await.map_err(|err| ActionError {
ids: cloids.clone(),
err: err.to_string(),
})?;
match resp {
Response::Ok(OkResponse::Cancel { statuses }) => Ok(statuses),
Response::Err(err) => Err(ActionError { ids: cloids, err }),
_ => Err(ActionError {
ids: cloids,
err: format!("unexpected response type: {resp:?}"),
}),
}
}
}
/// Modify a batch of existing orders (change price, size, or both).
///
/// Each modify request references an order by OID or CLOID and specifies the
/// new price (`limit_px`) and/or size (`sz`). If only one field is changed, set
/// the other to its current value. Returns the status for each modification attempt.
/// Errors are wrapped in [`ActionError`] with the failed order IDs accessible via `.ids()`.
pub fn modify<S: SignerSync>(
&self,
signer: &S,
batch: BatchModify,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<Vec<OrderResponseStatus>, ActionError<OidOrCloid>>> + Send + 'static
{
let cloids: Vec<_> = batch.modifies.iter().map(|req| req.oid).collect();
let future = self.sign_and_send_sync(signer, batch, nonce, vault_address, expires_after);
async move {
let resp = future.await.map_err(|err| ActionError {
ids: cloids.clone(),
err: err.to_string(),
})?;
match resp {
Response::Ok(OkResponse::Order { statuses }) => Ok(statuses),
Response::Err(err) => Err(ActionError { ids: cloids, err }),
_ => Err(ActionError {
ids: cloids,
err: format!("unexpected response type: {resp:?}"),
}),
}
}
}
/// Approve a new agent.
///
/// Approves an agent to act on behalf of the signer's account. An account can have:
/// - 1 unnamed approved wallet
/// - Up to 3 named agents
/// - 2 named agents per subaccount
///
/// # Parameters
///
/// - `signer`: The wallet signing the approval
/// - `agent`: The address of the agent to approve
/// - `name`: The name for the agent (or empty string for unnamed)
/// - `nonce`: The nonce for this action
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use alloy::primitives::address;
/// use alloy::signers::local::PrivateKeySigner;
///
/// async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let signer = PrivateKeySigner::random();
/// let agent = address!("0x97271b6b7f3b23a2f4700ae671b05515ae5c3319");
/// let name = "my_agent".to_string();
/// let nonce = 123456789;
///
/// client.approve_agent(&signer, agent, name, nonce).await?;
/// Ok(())
/// }
/// ```
pub async fn approve_agent<S: Signer + Send + Sync>(
&self,
signer: &S,
agent: Address,
name: String,
nonce: u64,
) -> Result<()> {
let signature_chain_id = self.chain.arbitrum_id().to_owned();
let approve_agent = ApproveAgent {
signature_chain_id,
hyperliquid_chain: self.chain,
agent_address: agent,
agent_name: if name.is_empty() { None } else { Some(name) },
nonce,
};
let resp = self
.sign_and_send(signer, approve_agent, nonce, None, None)
.await?;
resp.into_default()
}
/// Approve the maximum fee rate a builder can charge for routed orders.
///
/// # Parameters
///
/// - `signer`: The wallet signing the approval
/// - `builder`: Builder address
/// - `max_fee_rate`: Max fee as percent string (e.g. `"0.001%"`)
/// - `nonce`: The nonce for this action
pub async fn approve_builder_fee<S: Signer + Send + Sync>(
&self,
signer: &S,
builder: Address,
max_fee_rate: String,
nonce: u64,
) -> Result<()> {
let approve_builder_fee = ApproveBuilderFee {
signature_chain_id: self.chain.arbitrum_id().to_owned(),
hyperliquid_chain: self.chain,
max_fee_rate,
builder,
nonce,
};
let resp = self
.sign_and_send(signer, approve_builder_fee, nonce, None, None)
.await?;
resp.into_default()
}
/// Convert account to multi-signature user.
///
/// Converts a regular account to a multisig account by specifying authorized signers
/// and the required signature threshold. After conversion, the account will require
/// multiple signatures to execute transactions.
///
/// # Parameters
///
/// - `signer`: The wallet signing the conversion (must be the account owner)
/// - `authorized_users`: List of addresses authorized to sign for the multisig
/// - `threshold`: Minimum number of signatures required (e.g., 2 for 2-of-3)
/// - `nonce`: The nonce for this action
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use alloy::primitives::address;
/// use alloy::signers::local::PrivateKeySigner;
///
/// async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let signer = PrivateKeySigner::random();
/// let authorized_users = vec![
/// address!("0x1111111111111111111111111111111111111111"),
/// address!("0x2222222222222222222222222222222222222222"),
/// address!("0x3333333333333333333333333333333333333333"),
/// ];
/// let threshold = 2; // 2-of-3 multisig
/// let nonce = 123456789;
///
/// client.convert_to_multisig(&signer, authorized_users, threshold, nonce).await?;
///
/// Ok(())
/// }
/// ```
pub async fn convert_to_multisig<S: Signer + Send + Sync>(
&self,
signer: &S,
authorized_users: Vec<Address>,
threshold: usize,
nonce: u64,
) -> Result<()> {
let chain = self.chain;
let signature_chain_id = chain.arbitrum_id().to_owned();
let convert = ConvertToMultiSigUser {
signature_chain_id,
hyperliquid_chain: chain,
signers: SignersConfig {
authorized_users,
threshold,
},
nonce,
};
let resp = self
.sign_and_send(signer, convert, nonce, None, None)
.await?;
resp.into_default()
}
/// Helper function to transfer from spot Core balance to HyperEVM.
///
/// Sends the specified token from the signer's spot balance on HyperCore to their
/// corresponding address on HyperEVM. The token must have a cross-chain address configured.
///
/// # Parameters
///
/// - `signer`: The wallet signing the transfer
/// - `token`: The [`SpotToken`] to transfer (must have a cross-chain address)
/// - `amount`: Amount to transfer
/// - `nonce`: Unique nonce for this request
pub async fn transfer_to_evm<S: Send + SignerSync>(
&self,
signer: &S,
token: SpotToken,
amount: Decimal,
nonce: u64,
) -> Result<()> {
let destination = token
.cross_chain_address
.ok_or_else(|| anyhow!("token {token} doesn't have a cross chain address"))?;
self.spot_send(
&signer,
SpotSend {
destination,
token: SendToken(token),
amount,
time: nonce,
},
nonce,
)
.await
}
/// Helper function to transfer from perpetual balance to spot.
///
/// Moves USDC from the signer's perpetual (perps) balance to their spot balance.
/// Only USDC is accepted as `token`.
///
/// # Parameters
///
/// - `signer`: The wallet signing the transfer
/// - `token`: Must be USDC — other tokens return an error
/// - `amount`: Amount to transfer
/// - `nonce`: Unique nonce for this request
pub async fn transfer_to_spot<S: Signer + SignerSync>(
&self,
signer: &S,
token: SpotToken,
amount: Decimal,
nonce: u64,
) -> Result<()> {
if token.name != "USDC" {
return Err(anyhow!(
"only USDC is accepted, tried to transfer {}",
token.name
));
}
self.send_asset(
signer,
SendAsset {
destination: signer.address(),
source_dex: AssetTarget::Perp,
destination_dex: AssetTarget::Spot,
token: SendToken(token),
from_sub_account: "".into(),
amount,
nonce,
},
nonce,
)
.await
}
/// Helper function to transfer from spot to perpetual balance.
///
/// Moves USDC from the signer's spot balance to their perpetual (perps) balance.
/// Only USDC is accepted as `token`.
///
/// # Parameters
///
/// - `signer`: The wallet signing the transfer
/// - `token`: Must be USDC — other tokens return an error
/// - `amount`: Amount to transfer
/// - `nonce`: Unique nonce for this request
pub async fn transfer_to_perps<S: Signer + SignerSync>(
&self,
signer: &S,
token: SpotToken,
amount: Decimal,
nonce: u64,
) -> Result<()> {
if token.name != "USDC" {
return Err(anyhow!(
"only USDC is accepted, tried to transfer {}",
token.name
));
}
self.send_asset(
signer,
SendAsset {
destination: signer.address(),
source_dex: AssetTarget::Spot,
destination_dex: AssetTarget::Perp,
token: SendToken(token),
from_sub_account: "".into(),
amount,
nonce,
},
nonce,
)
.await
}
/// Send USDC from perpetual balance to another address (perp-to-perp transfer).
///
/// This performs a core USDC transfer between perpetual balances. The amount is
/// deducted from the signer's perps balance and credited to the destination's
/// perps balance.
///
/// # Parameters
///
/// - `signer`: The wallet signing the transfer
/// - `send`: A [`UsdSend`] specifying destination, amount, and timestamp
/// - `nonce`: Unique nonce for this request
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#core-usdc-transfer>
pub async fn send_usdc<S: SignerSync>(
&self,
signer: &S,
send: UsdSend,
nonce: u64,
) -> Result<()> {
let resp = self
.sign_and_send_sync(signer, send.into_action(self.chain), nonce, None, None)
.await?;
resp.into_default()
}
/// Deposit or withdraw USDC from a vault.
///
/// # Parameters
///
/// - `signer`: The signer for signing the action
/// - `vault_address`: The vault to deposit into or withdraw from
/// - `usd`: Amount of USDC (e.g. `dec!(100.5)` for $100.50; converted internally to micro-units)
/// - `nonce`: Unique nonce (typically current timestamp in milliseconds)
/// - `is_deposit`: `true` to deposit, `false` to withdraw
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#vault-transfer>
pub async fn vault_transfer<S: SignerSync>(
&self,
signer: &S,
vault_address: Address,
usd: Decimal,
nonce: u64,
is_deposit: bool,
) -> Result<()> {
let usd_raw = (usd * rust_decimal::Decimal::from(1_000_000))
.to_u64()
.ok_or_else(|| anyhow!("vault_transfer: usd amount out of range: {usd}"))?;
let action = VaultTransfer {
vault_address,
is_deposit,
usd: usd_raw,
};
let resp = self
.sign_and_send_sync(signer, action, nonce, None, None)
.await?;
resp.into_default()
}
/// Send USDC between spot and DEX/subaccount balances.
///
/// This performs a `SendAsset` action for spot-to-DEX, DEX-to-spot, or subaccount transfers.
/// The source and destination are determined by the [`SendAsset`] fields.
///
/// # Parameters
///
/// - `signer`: The wallet signing the transfer
/// - `send`: A [`SendAsset`] specifying source/destination DEX, token, amount, etc.
/// - `nonce`: Unique nonce for this request
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#send-asset>
pub fn send_asset<S: SignerSync>(
&self,
signer: &S,
send: SendAsset,
nonce: u64,
) -> impl Future<Output = Result<()>> + Send + 'static {
let future =
self.sign_and_send_sync(signer, send.into_action(self.chain), nonce, None, None);
async move { future.await?.into_default() }
}
/// Agent-signed send asset.
///
/// Same purpose as [`send_asset`](Self::send_asset) but signed by an agent
/// (API wallet) via L1-action signing. The destination must equal the
/// source address, so this is limited to self-transfers across DEXes, the
/// spot balance, or between subaccounts of the same master account.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#agent-send-asset>
pub fn agent_send_asset<S: SignerSync>(
&self,
signer: &S,
send: AgentSendAsset,
nonce: u64,
) -> impl Future<Output = Result<()>> + Send + 'static {
let future = self.sign_and_send_sync(signer, send.into_action(), nonce, None, None);
async move { future.await?.into_default() }
}
/// Send a spot token to another address (spot-to-spot transfer).
///
/// Transfers any spot token between accounts. Unlike [`send_usdc`](Self::send_usdc)
/// which only handles USDC on perpetual balances, this works with any spot token.
///
/// # Parameters
///
/// - `signer`: The wallet signing the transfer
/// - `send`: A [`SpotSend`] specifying destination, token, and amount
/// - `nonce`: Unique nonce for this request
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#core-spot-transfer>
pub fn spot_send<S: SignerSync>(
&self,
signer: &S,
send: SpotSend,
nonce: u64,
) -> impl Future<Output = Result<()>> + Send + 'static {
let future =
self.sign_and_send_sync(signer, send.into_action(self.chain), nonce, None, None);
async move { future.await?.into_default() }
}
/// Update leverage for a perpetual asset.
///
/// Sets the leverage and margin mode (cross or isolated) for a specific asset.
/// This must be called before opening a position to ensure the correct leverage
/// is applied.
///
/// # Arguments
///
/// * `signer` - The signer for authentication
/// * `asset` - The asset index (from [`PerpMarket::index`])
/// * `is_cross` - `true` for cross margin, `false` for isolated margin
/// * `leverage` - The desired leverage value (e.g., 10 for 10x)
/// * `nonce` - Unique nonce for this request
/// * `vault_address` - Optional vault address if trading on behalf of a vault
/// * `expires_after` - Optional expiry time for the request
///
/// # Example
///
/// ```rust,ignore
/// use hypersdk::hypercore::{self, PrivateKeySigner, NonceHandler};
///
/// let client = hypercore::mainnet();
/// let signer: PrivateKeySigner = "0x...".parse()?;
/// let nonce_handler = NonceHandler::default();
///
/// // Set BTC (asset 0) to 10x cross margin
/// client.update_leverage(&signer, 0, true, 10, nonce_handler.next(), None, None).await?;
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn update_leverage<S: SignerSync>(
&self,
signer: &S,
asset: usize,
is_cross: bool,
leverage: u32,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let resp = self
.sign_and_send_sync(
signer,
Action::UpdateLeverage(UpdateLeverage {
asset,
is_cross,
leverage,
}),
nonce,
vault_address,
expires_after,
)
.await?;
resp.into_default()
}
/// Updates isolated margin for a position.
///
/// `ntli` is the margin delta in USD with 6 decimals: positive adds margin, negative removes it.
pub async fn update_isolated_margin<S: SignerSync>(
&self,
signer: &S,
asset: usize,
is_buy: bool,
ntli: i64,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let resp = self
.sign_and_send_sync(
signer,
Action::UpdateIsolatedMargin(UpdateIsolatedMargin {
asset,
is_buy,
ntli,
}),
nonce,
vault_address,
expires_after,
)
.await?;
resp.into_default()
}
/// Toggle the EVM user "big blocks" setting via signed action.
///
/// Enables or disables big block processing for the user's HyperEVM account.
///
/// # Parameters
///
/// - `signer`: The wallet signing the action
/// - `toggle`: `true` to enable big blocks, `false` to disable
/// - `nonce`: Unique nonce for this request
/// - `vault_address`: Optional vault/subaccount address
/// - `expires_after`: Optional expiration time for the request
pub async fn evm_user_modify<S: SignerSync>(
&self,
signer: &S,
toggle: bool,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let resp = self
.sign_and_send_sync(
signer,
Action::EvmUserModify {
using_big_blocks: toggle,
},
nonce,
vault_address,
expires_after,
)
.await?;
resp.into_default()
}
/// Invalidate a nonce by sending a no-op action.
///
/// This burns a nonce without performing any state change. Useful for ensuring
/// monotonically increasing nonces stay in sync when some transactions are skipped
/// or when you need to advance the nonce past a specific value.
///
/// # Parameters
///
/// - `signer`: The wallet signing the noop
/// - `nonce`: The nonce to invalidate
/// - `vault_address`: Optional vault/subaccount address
/// - `expires_after`: Optional expiration time for the request
pub async fn noop<S: SignerSync>(
&self,
signer: &S,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let resp = self
.sign_and_send_sync(signer, Action::Noop, nonce, vault_address, expires_after)
.await?;
resp.into_default()
}
// -----------------------------------------------------------------
// Account Abstraction Mode actions
// -----------------------------------------------------------------
/// Query the maximum builder fee approved by a user for a specific builder.
///
/// Returns the maximum fee approved by `user` for `builder`,
/// expressed in tenths of a basis point (e.g. `1` means 0.001%).
/// Returns `0` if no approval has been granted.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user: Address = "0x...".parse()?;
/// let builder: Address = "0x...".parse()?;
/// let max_fee = client.max_builder_fee(user, builder).await?;
/// println!("Max approved fee: {} (tenths of a bps)", max_fee);
/// # Ok(())
/// # }
/// ```
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#check-builder-fee-approval>
pub async fn max_builder_fee(&self, user: Address, builder: Address) -> Result<u32> {
let req = InfoRequest::MaxBuilderFee { user, builder };
self.send_info_request("max_builder_fee", &req).await
}
/// Query the current account abstraction mode for a user.
///
/// Sends an info request to `/info` with type `"abstraction"`.
/// Returns the current mode as parsed by [`AbstractionMode`].
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// let user: hypersdk::Address = "0x...".parse()?;
/// let mode = client.abstraction_mode(user).await?;
/// println!("Current mode: {mode}");
/// # Ok(())
/// # }
/// ```
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-abstraction-mode>
pub async fn abstraction_mode(&self, user: Address) -> Result<AbstractionMode> {
let req = InfoRequest::UserAbstraction { user };
// Response is a plain string like "unifiedAccount" or "disabled"
let s: String = self
.send_info_request("user_abstraction_mode", &req)
.await?;
AbstractionMode::from_api_str(&s)
.map_err(|e| anyhow!("failed to parse user abstraction mode: {e}"))
}
/// Query whether HIP-3 DEX abstraction is enabled for a user.
///
/// Returns `None` when the user has never set it, which the API reports as `null`.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-a-users-hip-3-dex-abstraction-state>
pub async fn user_dex_abstraction(&self, user: Address) -> Result<Option<bool>> {
let req = InfoRequest::UserDexAbstraction { user };
self.send_info_request("user_dex_abstraction", &req).await
}
/// Set abstraction mode via agent-signed action (L1/RMP signing).
///
/// Changes the account's abstraction mode to one of:
/// - [`AbstractionMode::Standard`] (`"i"`): Separate perp/spot balances
/// - [`AbstractionMode::UnifiedAccount`] (`"u"`): Unified per-asset balance
/// - [`AbstractionMode::PortfolioMargin`] (`"p"`): Portfolio margin (pre-alpha)
///
/// This uses RMP-based signing (Agent wrapper) — suitable for API wallets / agents.
///
/// # Parameters
///
/// - `signer`: The agent/API wallet signer
/// - `mode`: The target abstraction mode
/// - `nonce`: Unique nonce (typically current timestamp in ms)
/// - `vault_address`: Optional subaccount/vault address
/// - `expires_after`: Optional expiration time
///
/// # Important Notes
///
/// - Builder code addresses **must** be in Standard mode to accrue builder fees
/// - Unified Account and Portfolio Margin have a 50k daily action limit
/// - Standard mode has no action limits
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#set-account-abstraction-mode-agent-signed>
pub async fn agent_set_abstraction<S: SignerSync>(
&self,
signer: &S,
mode: AbstractionMode,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::AgentSetAbstraction { abstraction: mode };
let resp = self
.sign_and_send_sync(signer, action, nonce, vault_address, expires_after)
.await?;
resp.into_default()
}
/// Set abstraction mode via user-signed action (EIP-712 signing).
///
/// User-signed variant: requires EIP-712 signing with the `HyperliquidSignTransaction` domain.
/// This is used when the main account owner wants to change their own abstraction mode
/// directly (not through an API agent).
///
/// # Parameters
///
/// - `signer`: The account owner's signer (must match the `user` address)
/// - `user`: The user address to set the mode for (lowercase hex)
/// - `mode`: The target abstraction mode
/// - `nonce`: Unique nonce (typically current timestamp in ms)
///
/// Note: user-signed actions do not support `vault_address` or `expires_after`.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#set-account-abstraction-mode-user-signed>
pub async fn user_set_abstraction<S: Signer + Send + Sync>(
&self,
signer: &S,
user: Address,
mode: AbstractionMode,
nonce: u64,
) -> Result<()> {
let signature_chain_id = self.chain.arbitrum_id().to_owned();
let action = UserSetAbstractionAction {
signature_chain_id,
hyperliquid_chain: self.chain,
user,
abstraction: mode,
nonce,
};
let resp = self
.sign_and_send(
signer,
Action::UserSetAbstraction(action),
nonce,
None,
None,
)
.await?;
resp.into_default()
}
/// Executes a multisig action on Hyperliquid.
///
/// This method allows multiple signers to authorize a single action (such as placing orders,
/// canceling orders, or transferring funds) from a multisig wallet. All provided signers must
/// be authorized on the multisig wallet configuration.
///
/// # Parameters
///
/// - `lead`: The lead signer who submits the transaction to the exchange
/// - `multi_sig_user`: The multisig wallet address that will execute the action
/// - `signers`: Iterator of all signers whose signatures are required (typically includes the lead)
/// - `action`: The action to execute (Order, Cancel, Transfer, etc.)
/// - `nonce`: Unique nonce for this transaction (typically current timestamp in milliseconds)
///
/// # Multisig Process
///
/// 1. The action is hashed with the multisig address and lead signer
/// 2. Each signer signs the action hash using their private key
/// 3. All signatures are collected into a multisig payload
/// 4. The lead signer signs the entire multisig payload
/// 5. The signed multisig transaction is submitted to the exchange
/// 6. The exchange verifies all signatures match the multisig wallet's authorized signers
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
///
/// // Parse the signers for the multisig wallet
/// let signer1: PrivateKeySigner = "key1".parse()?;
/// let signer2: PrivateKeySigner = "key2".parse()?;
///
/// // The multisig wallet address
/// let multisig_addr: hypersdk::Address = "0x...".parse()?;
///
/// // Execute multisig operations - requires dec!() macro and timestamp
/// // let nonce = chrono::Utc::now().timestamp_millis() as u64;
/// // let response = client.multi_sig(&signer1, multisig_addr, nonce)
/// // .signer(&signer2)
/// // .place(order, None, None)
/// // .await?;
/// # Ok(())
/// # }
/// ```
pub fn multi_sig<'a, S: Signer + Send + Sync>(
&'a self,
lead: &'a S,
multi_sig_user: Address,
nonce: u64,
) -> MultiSig<'a, S> {
MultiSig {
lead,
multi_sig_user,
signers: VecDeque::new(),
signatures: VecDeque::new(),
client: self,
nonce,
}
}
/// Send a signed action hashing.
fn sign_and_send_sync<S: SignerSync, A: Into<Action>>(
&self,
signer: &S,
action: A,
nonce: u64,
maybe_vault_address: Option<Address>,
maybe_expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<Response>> + Send + 'static {
let action: Action = action.into();
let res = action.sign_sync(
signer,
nonce,
maybe_vault_address,
maybe_expires_after,
self.chain,
);
let http_client = self.http_client.clone();
let mut url = self.base_url.clone();
url.set_path("/exchange");
async move {
let req = res?;
let res = http_client.post(url).json(&req).send().await?;
let status = res.status();
let bytes = res.bytes().await?;
let text = String::from_utf8_lossy(&bytes);
if !status.is_success() {
return Err(ApiError(format!("HTTP {status} body={text}")).into());
}
let parsed = serde_json::from_str(&text).with_context(|| format!("body={text}"))?;
Ok(parsed)
}
}
/// Send a signed action hashing.
async fn sign_and_send<S: Signer + Send + Sync, A: Into<Action>>(
&self,
signer: &S,
action: A,
nonce: u64,
maybe_vault_address: Option<Address>,
maybe_expires_after: Option<DateTime<Utc>>,
) -> Result<Response> {
let action: Action = action.into();
let req = action
.sign(
signer,
nonce,
maybe_vault_address,
maybe_expires_after,
self.chain,
)
.await?;
self.send(req).await
}
#[doc(hidden)]
pub async fn send(&self, req: ActionRequest) -> Result<Response> {
let http_client = self.http_client.clone();
let mut url = self.base_url.clone();
url.set_path("/exchange");
let res = http_client
.post(url)
.timeout(Duration::from_secs(5))
// .header(header::CONTENT_TYPE, "application/json")
// .body(text)
.json(&req)
.send()
.await?;
let status = res.status();
let bytes = res.bytes().await?;
let text = String::from_utf8_lossy(&bytes);
if !status.is_success() {
return Err(ApiError(format!("HTTP {status} body={text}")).into());
}
let parsed = serde_json::from_str(&text).with_context(|| format!("body={text}"))?;
Ok(parsed)
}
/// Returns combined perpetual metadata and asset contexts.
pub async fn meta_and_asset_ctxs(&self, dex: Option<String>) -> Result<serde_json::Value> {
let req = InfoRequest::MetaAndAssetCtxs { dex };
self.send_info_request("meta_and_asset_ctxs", &req).await
}
/// Returns combined spot metadata and asset contexts.
pub async fn spot_meta_and_asset_ctxs(&self) -> Result<serde_json::Value> {
let req = InfoRequest::SpotMetaAndAssetCtxs;
self.send_info_request("spot_meta_and_asset_ctxs", &req)
.await
}
/// Returns the user's rate limit usage.
pub async fn user_rate_limit(&self, user: Address) -> Result<UserRateLimit> {
let req = InfoRequest::UserRateLimit { user };
self.send_info_request("user_rate_limit", &req).await
}
/// Returns the user's funding history.
pub async fn user_funding(
&self,
user: Address,
start_time: u64,
end_time: Option<u64>,
) -> Result<Vec<UserFundingEntry>> {
let req = InfoRequest::UserFunding {
user,
start_time,
end_time,
};
self.send_info_request("user_funding", &req).await
}
/// Returns the user's non-funding ledger updates.
pub async fn user_non_funding_ledger_updates(
&self,
user: Address,
start_time: u64,
end_time: Option<u64>,
) -> Result<Vec<serde_json::Value>> {
let req = InfoRequest::UserNonFundingLedgerUpdates {
user,
start_time,
end_time,
};
self.send_info_request("user_non_funding_ledger_updates", &req)
.await
}
/// Returns predicted funding rates for all coins, across every venue the exchange tracks.
///
/// A venue's entry is `None` when the coin is not listed there, which is distinct from a
/// funding rate of zero. Treating `None` as zero invents a spread against the venues that
/// did report one.
pub async fn predicted_fundings(
&self,
) -> Result<Vec<(String, Vec<(String, Option<PredictedFundingVenue>)>)>> {
let req = InfoRequest::PredictedFundings;
self.send_info_request("predicted_fundings", &req).await
}
/// Returns coins at open interest cap.
pub async fn perps_at_open_interest_cap(&self, dex: Option<String>) -> Result<Vec<String>> {
let req = InfoRequest::PerpsAtOpenInterestCap { dex };
self.send_info_request("perps_at_open_interest_cap", &req)
.await
}
/// Returns perp deploy auction status.
pub async fn perp_deploy_auction_status(&self) -> Result<DeployAuctionStatus> {
let req = InfoRequest::PerpDeployAuctionStatus;
self.send_info_request("perp_deploy_auction_status", &req)
.await
}
/// Returns user leverage and trade-size limits for a specific asset.
pub async fn active_asset_data(&self, user: Address, coin: String) -> Result<ActiveAssetData> {
let req = InfoRequest::ActiveAssetData { user, coin };
self.send_info_request("active_asset_data", &req).await
}
/// Returns OI caps and transfer limits for a HIP-3 DEX.
pub async fn perp_dex_limits(&self, dex: String) -> Result<PerpDexLimits> {
let req = InfoRequest::PerpDexLimits { dex };
self.send_info_request("perp_dex_limits", &req).await
}
/// Returns total net deposit for a HIP-3 DEX.
pub async fn perp_dex_status(&self, dex: String) -> Result<PerpDexStatus> {
let req = InfoRequest::PerpDexStatus { dex };
self.send_info_request("perp_dex_status", &req).await
}
/// Returns the configuration of every HIP-3 DEX: deployer, oracle updater, fee recipient,
/// sub-deployer permissions, OI caps, and funding settings.
///
/// Same `perpDexs` request as [`Self::perp_dexes`], which keeps only names and indices.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = hypercore::mainnet();
/// for dex in client.perp_dex_details().await? {
/// println!("{} oracle signers: {:?}", dex.name, dex.sub_deployers_for("setOracle"));
/// }
/// # Ok(())
/// # }
/// ```
pub async fn perp_dex_details(&self) -> Result<Vec<PerpDexDetails>> {
let dexes = self
.send_info_request("perp_dex_details", &InfoRequest::PerpDexs)
.await?;
Ok(PerpDexDetails::from_response(dexes))
}
/// Returns a user's approval state on every HIP-3\* venue that has approved them. Venues
/// that have since removed the approval are listed with no flags.
///
/// HIP-3\* venues are testnet-only.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-3-deployer-actions#reading-state>
pub async fn user_star_state(&self, user: Address) -> Result<UserStarState> {
let req = InfoRequest::UserStarState { user };
self.send_info_request("user_star_state", &req).await
}
/// Returns all DEXs' meta + asset contexts.
pub async fn all_perp_metas(&self) -> Result<serde_json::Value> {
let req = InfoRequest::AllPerpMetas;
self.send_info_request("all_perp_metas", &req).await
}
/// Returns category and description for a coin.
pub async fn perp_annotation(&self, coin: String) -> Result<serde_json::Value> {
let req = InfoRequest::PerpAnnotation { coin };
self.send_info_request("perp_annotation", &req).await
}
/// Returns all coin categories.
pub async fn perp_categories(&self) -> Result<Vec<(String, String)>> {
let req = InfoRequest::PerpCategories;
self.send_info_request("perp_categories", &req).await
}
/// Returns concise coin annotations.
pub async fn perp_concise_annotations(&self) -> Result<serde_json::Value> {
let req = InfoRequest::PerpConciseAnnotations;
self.send_info_request("perp_concise_annotations", &req)
.await
}
/// Returns spot token deploy state for a user.
pub async fn spot_deploy_state(&self, user: Address) -> Result<serde_json::Value> {
let req = InfoRequest::SpotDeployState { user };
self.send_info_request("spot_deploy_state", &req).await
}
/// Returns spot pair deploy auction status.
pub async fn spot_pair_deploy_auction_status(&self) -> Result<DeployAuctionStatus> {
let req = InfoRequest::SpotPairDeployAuctionStatus;
self.send_info_request("spot_pair_deploy_auction_status", &req)
.await
}
/// Returns detailed token info by tokenId.
pub async fn token_details(&self, token_id: String) -> Result<TokenDetails> {
let req = InfoRequest::TokenDetails { token_id };
self.send_info_request("token_details", &req).await
}
/// Returns how a HIP-4 outcome settled, or `None` if it has not settled. The exchange
/// answers `null` both for an outcome that is still trading and for an unknown ID.
pub async fn settled_outcome(&self, outcome: u64) -> Result<Option<SettledOutcome>> {
let req = InfoRequest::SettledOutcome { outcome };
self.send_info_request("settled_outcome", &req).await
}
/// Returns user portfolio performance.
pub async fn portfolio(&self, user: Address) -> Result<serde_json::Value> {
let req = InfoRequest::Portfolio { user };
self.send_info_request("portfolio", &req).await
}
/// Returns referral state and rewards.
pub async fn referral(&self, user: Address) -> Result<serde_json::Value> {
let req = InfoRequest::Referral { user };
self.send_info_request("referral", &req).await
}
/// Returns list of approved builder addresses.
pub async fn approved_builders(&self, user: Address) -> Result<Vec<Address>> {
let req = InfoRequest::ApprovedBuilders { user };
self.send_info_request("approved_builders", &req).await
}
/// Returns user's staking delegations.
pub async fn delegations(&self, user: Address) -> Result<Vec<Delegation>> {
let req = InfoRequest::Delegations { user };
self.send_info_request("delegations", &req).await
}
/// Returns delegation summary for a user.
pub async fn delegator_summary(&self, user: Address) -> Result<DelegatorSummary> {
let req = InfoRequest::DelegatorSummary { user };
self.send_info_request("delegator_summary", &req).await
}
/// Returns delegation history for a user.
pub async fn delegator_history(&self, user: Address) -> Result<Vec<serde_json::Value>> {
let req = InfoRequest::DelegatorHistory { user };
self.send_info_request("delegator_history", &req).await
}
/// Returns delegation rewards for a user.
pub async fn delegator_rewards(&self, user: Address) -> Result<Vec<serde_json::Value>> {
let req = InfoRequest::DelegatorRewards { user };
self.send_info_request("delegator_rewards", &req).await
}
/// Returns borrow/lend user state.
pub async fn borrow_lend_user_state(&self, user: Address) -> Result<serde_json::Value> {
let req = InfoRequest::BorrowLendUserState { user };
self.send_info_request("borrow_lend_user_state", &req).await
}
/// Returns borrow/lend reserve state for a specific token.
pub async fn borrow_lend_reserve_state(&self, token: u32) -> Result<serde_json::Value> {
let req = InfoRequest::BorrowLendReserveState { token };
self.send_info_request("borrow_lend_reserve_state", &req)
.await
}
/// Returns all borrow/lend reserve states.
pub async fn all_borrow_lend_reserve_states(&self) -> Result<serde_json::Value> {
let req = InfoRequest::AllBorrowLendReserveStates;
self.send_info_request("all_borrow_lend_reserve_states", &req)
.await
}
/// Returns all HIP-4 outcome templates.
///
/// Templates are voted on by validators and fix the display text, side names, and typed
/// keywords that outcome deployments are built from.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions#read-api>
pub async fn outcome_templates(&self) -> Result<serde_json::Value> {
let req = InfoRequest::OutcomeTemplates;
self.send_info_request("outcome_templates", &req).await
}
/// Returns TWAP slice fills for a user via info endpoint.
pub async fn user_twap_slice_fills(&self, user: Address) -> Result<Vec<TwapSliceFill>> {
let req = InfoRequest::UserTwapSliceFills { user };
self.send_info_request("user_twap_slice_fills", &req).await
}
/// Returns L2 order book snapshot.
pub async fn l2_book(
&self,
coin: String,
n_sig_figs: Option<u8>,
mantissa: Option<u8>,
) -> Result<L2Book> {
let req = InfoRequest::L2Book {
coin,
n_sig_figs,
mantissa,
};
self.send_info_request("l2_book", &req).await
}
/// Returns simple open orders for a user.
pub async fn simple_open_orders(&self, user: Address) -> Result<Vec<serde_json::Value>> {
let req = InfoRequest::OpenOrders { user };
self.send_info_request("simple_open_orders", &req).await
}
// --- Undocumented info requests ---
//
// None of these appear in the gitbook, but mainnet answers all of them. Where the
// response shape is stable it is modelled; the rest return raw JSON.
/// Returns exchange-wide status flags and server time.
pub async fn exchange_status(&self) -> Result<ExchangeStatus> {
self.send_info_request("exchange_status", &InfoRequest::ExchangeStatus)
.await
}
/// Returns the IP addresses of the gossip root nodes.
pub async fn gossip_root_ips(&self) -> Result<Vec<String>> {
self.send_info_request("gossip_root_ips", &InfoRequest::GossipRootIps)
.await
}
/// Returns whether the user has VIP fee status.
pub async fn is_vip(&self, user: Address) -> Result<bool> {
self.send_info_request("is_vip", &InfoRequest::IsVip { user })
.await
}
/// Returns the vaults the user leads.
pub async fn leading_vaults(&self, user: Address) -> Result<serde_json::Value> {
self.send_info_request("leading_vaults", &InfoRequest::LeadingVaults { user })
.await
}
/// Returns whether the user has accepted terms and may trade.
pub async fn legal_check(&self, user: Address) -> Result<LegalCheck> {
self.send_info_request("legal_check", &InfoRequest::LegalCheck { user })
.await
}
/// Returns the accounts currently eligible for liquidation.
pub async fn liquidatable(&self) -> Result<serde_json::Value> {
self.send_info_request("liquidatable", &InfoRequest::Liquidatable)
.await
}
/// Returns one margin table by id.
pub async fn margin_table(&self, id: u32) -> Result<MarginTable> {
self.send_info_request("margin_table", &InfoRequest::MarginTable { id })
.await
}
/// Returns the maximum market order notional for each leverage bucket,
/// as `(leverage, max notional)` pairs.
pub async fn max_market_order_ntls(&self) -> Result<Vec<(u32, Decimal)>> {
self.send_info_request("max_market_order_ntls", &InfoRequest::MaxMarketOrderNtls)
.await
}
/// Returns the sanction, existence and fee checks for transferring from `source` to `user`.
pub async fn pre_transfer_check(
&self,
user: Address,
source: Address,
) -> Result<PreTransferCheck> {
let req = InfoRequest::PreTransferCheck { user, source };
self.send_info_request("pre_transfer_check", &req).await
}
/// Returns recent trades for a coin.
pub async fn recent_trades(&self, coin: String) -> Result<Vec<Trade>> {
self.send_info_request("recent_trades", &InfoRequest::RecentTrades { coin })
.await
}
/// Returns the user's subaccounts in the newer response shape.
///
/// [`subaccounts`](Self::subaccounts) returns the documented shape.
pub async fn subaccounts2(&self, user: Address) -> Result<serde_json::Value> {
self.send_info_request("subaccounts2", &InfoRequest::SubAccounts2 { user })
.await
}
/// Returns the user's TWAP order history.
pub async fn twap_history(&self, user: Address) -> Result<serde_json::Value> {
self.send_info_request("twap_history", &InfoRequest::TwapHistory { user })
.await
}
/// Returns which bridge USDC deposits and withdrawals currently route over.
pub async fn usdc_routing(&self) -> Result<UsdcRouting> {
self.send_info_request("usdc_routing", &InfoRequest::UsdcRouting)
.await
}
/// Returns the user's accrued borrow/lend interest.
pub async fn user_borrow_lend_interest(
&self,
user: Address,
start_time: u64,
end_time: Option<u64>,
) -> Result<serde_json::Value> {
let req = InfoRequest::UserBorrowLendInterest {
user,
start_time,
end_time,
};
self.send_info_request("user_borrow_lend_interest", &req)
.await
}
/// Returns the user's TWAP slice fills within a time range.
pub async fn user_twap_slice_fills_by_time(
&self,
user: Address,
start_time: u64,
end_time: Option<u64>,
aggregate_by_time: Option<bool>,
) -> Result<Vec<TwapSliceFill>> {
let req = InfoRequest::UserTwapSliceFillsByTime {
user,
start_time,
end_time,
aggregate_by_time,
};
self.send_info_request("user_twap_slice_fills_by_time", &req)
.await
}
/// Returns pending validator votes on L1 actions.
pub async fn validator_l1_votes(&self) -> Result<serde_json::Value> {
self.send_info_request("validator_l1_votes", &InfoRequest::ValidatorL1Votes)
.await
}
/// Returns every validator's stake, commission and uptime.
pub async fn validator_summaries(&self) -> Result<serde_json::Value> {
self.send_info_request("validator_summaries", &InfoRequest::ValidatorSummaries)
.await
}
/// Returns every vault's headline stats.
pub async fn vault_summaries(&self) -> Result<serde_json::Value> {
self.send_info_request("vault_summaries", &InfoRequest::VaultSummaries)
.await
}
/// Returns the frontend-style aggregate account snapshot.
///
/// The matching websocket subscription was removed; subscribe to
/// [`Subscription::WebData3`](crate::hypercore::types::Subscription::WebData3) for a live
/// feed.
pub async fn web_data2(&self, user: Address, dex: Option<String>) -> Result<serde_json::Value> {
self.send_info_request("web_data2", &InfoRequest::WebData2 { user, dex })
.await
}
// --- Exchange actions (Phase 2) ---
/// Place a TWAP order.
pub async fn twap_order<S: SignerSync>(
&self,
signer: &S,
params: TwapOrderParams,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<Response> {
let action = Action::TwapOrder { twap: params };
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await
}
/// Cancel a TWAP order.
pub async fn twap_cancel<S: SignerSync>(
&self,
signer: &S,
asset: usize,
twap_id: u64,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<Response> {
let action = Action::TwapCancel {
a: asset,
t: twap_id,
};
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await
}
/// Place a native trailing stop and return the ID of the order it places.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-a-trailing-stop-order>
pub async fn trailing_stop<S: SignerSync>(
&self,
signer: &S,
trailing_stop: TrailingStop,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<u64> {
let action = Action::TrailingStop(trailing_stop);
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
match self.send(req).await? {
Response::Ok(OkResponse::TrailingStop { oid }) => Ok(oid),
Response::Err(err) => Err(ApiError(err).into()),
other => Err(ApiError(format!("unexpected response: {other:?}")).into()),
}
}
/// Withdraw to Arbitrum L1.
pub async fn withdraw<S: SignerSync>(
&self,
signer: &S,
destination: Address,
amount: Decimal,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::Withdraw3(Withdraw3Action {
signature_chain_id: self.chain.arbitrum_id().to_string(),
hyperliquid_chain: self.chain,
destination,
amount,
time: nonce,
});
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Transfer between spot and perp balances.
pub async fn usd_class_transfer<S: SignerSync>(
&self,
signer: &S,
amount: Decimal,
to_perp: bool,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::UsdClassTransfer(UsdClassTransferAction {
signature_chain_id: self.chain.arbitrum_id().to_string(),
hyperliquid_chain: self.chain,
amount: amount.to_string(),
to_perp,
nonce,
});
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Stake native token (HYPE).
pub async fn stake<S: SignerSync>(
&self,
signer: &S,
wei: u64,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::CDeposit { wei };
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Unstake native token (HYPE). 7-day queue.
pub async fn unstake<S: SignerSync>(
&self,
signer: &S,
wei: u64,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::CWithdraw { wei };
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Delegate or undelegate staked tokens to a validator.
pub async fn token_delegate<S: SignerSync>(
&self,
signer: &S,
validator: Address,
is_undelegate: bool,
wei: u64,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::TokenDelegate(TokenDelegateAction {
signature_chain_id: self.chain.arbitrum_id().to_owned(),
hyperliquid_chain: self.chain,
validator,
is_undelegate,
wei,
nonce,
});
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Reserve rate-limit request capacity.
///
/// `destination` credits the reserved capacity to another account; `None` credits the signer.
pub async fn reserve_request_weight<S: SignerSync>(
&self,
signer: &S,
weight: u32,
destination: Option<Address>,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::ReserveRequestWeight {
weight,
destination,
};
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// HIP-3 backstop liquidator transfer.
pub async fn hip3_liquidator_transfer<S: SignerSync>(
&self,
signer: &S,
dex: String,
ntl: u64,
is_deposit: bool,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::Hip3LiquidatorTransfer(Hip3LiquidatorTransferAction {
dex,
ntl,
is_deposit,
});
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Send a HIP-1/HIP-2 spot deploy action, or a HIP-4 outcome deploy action.
///
/// Deploying a token is the five-step sequence described on [`SpotDeployAction`]. Lists of
/// tuples must already be sorted, since the signature covers their encoding.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/deploying-hip-1-and-hip-2-assets>
pub async fn spot_deploy<S: SignerSync>(
&self,
signer: &S,
action: SpotDeployAction,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SpotDeploy(action);
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Send a HIP-3 perp DEX deployer action.
///
/// Lists of tuples must already be sorted, since the signature covers their encoding.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-3-deployer-actions>
pub async fn perp_deploy<S: SignerSync>(
&self,
signer: &S,
action: PerpDeployAction,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::PerpDeploy(action);
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Send a HIP-4 outcome deployer action for a venue.
///
/// Lists of tuples must already be sorted, since the signature covers their encoding.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions#action-reference>
pub async fn outcome_deploy<S: SignerSync>(
&self,
signer: &S,
action: OutcomeDeploy,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::OutcomeDeploy(action);
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Activate or permanently retire a HIP-4 outcome deployer.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions#activation>
pub async fn activate_outcome_deployer<S: SignerSync>(
&self,
signer: &S,
action: ActivateOutcomeDeployer,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::ActivateOutcomeDeployer(action);
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Transfer a token from Core to the EVM with an extra data payload.
///
/// The recipient contract must implement `ICoreReceiveWithData`. `nonce` is written into the
/// action as well as the request envelope, so both must match.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#send-to-evm-with-data>
#[allow(clippy::too_many_arguments)]
pub async fn send_to_evm_with_data<S: SignerSync>(
&self,
signer: &S,
token: String,
amount: Decimal,
source_dex: String,
destination_recipient: String,
address_encoding: AddressEncoding,
destination_chain_id: u32,
gas_limit: u64,
data: Bytes,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SendToEvmWithData(SendToEvmWithDataAction {
signature_chain_id: self.chain.arbitrum_id().to_string(),
hyperliquid_chain: self.chain,
token,
amount,
source_dex,
destination_recipient,
address_encoding,
destination_chain_id,
gas_limit,
data,
nonce,
});
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Add isolated margin to a position until it reaches `leverage`.
///
/// The leverage-targeting counterpart to [`update_isolated_margin`](Self::update_isolated_margin),
/// which moves a fixed USDC amount instead.
pub async fn top_up_isolated_only_margin<S: SignerSync>(
&self,
signer: &S,
asset: u32,
leverage: Decimal,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::TopUpIsolatedOnlyMargin(TopUpIsolatedOnlyMargin { asset, leverage });
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Claim accrued referral and builder rewards.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#claim-rewards>
pub async fn claim_rewards<S: SignerSync>(
&self,
signer: &S,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let req = Action::ClaimRewards.sign_sync(
signer,
nonce,
vault_address,
expires_after,
self.chain,
)?;
self.send(req).await?.into_default()
}
/// Authorize an AQAv2 role for an aligned quote asset.
///
/// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#authorize-aqav2-role>
pub async fn authorize_aqav2_role<S: SignerSync>(
&self,
signer: &S,
token: u32,
role: Aqav2Role,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::AuthorizeAqav2Role(AuthorizeAqav2Role { token, role });
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Validator vote on the risk-free rate for an aligned quote asset.
///
/// Only meaningful when the signer is a validator.
pub async fn validator_l1_stream<S: SignerSync>(
&self,
signer: &S,
risk_free_rate: Decimal,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::ValidatorL1Stream(ValidatorL1Stream { risk_free_rate });
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Replace a single resting order.
///
/// [`modify`](Self::modify) is the batch form. See [`ModifyAction::always_place`] for what
/// the replacement order is restricted to when that flag is `false`.
pub async fn modify_order<S: SignerSync>(
&self,
signer: &S,
modify: ModifyAction,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<Vec<OrderResponseStatus>> {
let action = Action::Modify(modify);
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
match self.send(req).await? {
Response::Ok(OkResponse::Order { statuses }) => Ok(statuses),
Response::Err(err) => Err(ApiError(err).into()),
other => Err(ApiError(format!("unexpected response: {other:?}")).into()),
}
}
// --- Undocumented exchange actions ---
//
// None of these appear in the gitbook, but mainnet accepts all of them. Shapes are
// cross-checked against the nktkas TypeScript SDK.
/// Supply, withdraw, repay or borrow on the borrow/lend markets.
///
/// A `None` amount means the maximum available.
pub async fn borrow_lend<S: SignerSync>(
&self,
signer: &S,
borrow_lend: BorrowLendAction,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::BorrowLend(borrow_lend);
let req = action.sign_sync(signer, nonce, vault_address, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Create a sub-account and return its address.
pub async fn create_sub_account<S: SignerSync>(
&self,
signer: &S,
name: String,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<Address> {
let action = Action::CreateSubAccount { name };
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
match self.send(req).await? {
Response::Ok(OkResponse::CreateSubAccount(address)) => Ok(address),
Response::Err(err) => Err(ApiError(err).into()),
other => Err(ApiError(format!("unexpected response: {other:?}")).into()),
}
}
/// Rename a sub-account.
pub async fn sub_account_modify<S: SignerSync>(
&self,
signer: &S,
sub_account_user: Address,
name: String,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SubAccountModify(SubAccountModify {
sub_account_user,
name,
});
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Move perp USDC to or from a sub-account. `usd` is in 1e-6 units.
pub async fn sub_account_transfer<S: SignerSync>(
&self,
signer: &S,
sub_account_user: Address,
is_deposit: bool,
usd: u64,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SubAccountTransfer(SubAccountTransfer {
sub_account_user,
is_deposit,
usd,
});
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Move a spot token to or from a sub-account.
///
/// `token` is the `NAME:0x...` identifier from `spotMeta`.
pub async fn sub_account_spot_transfer<S: SignerSync>(
&self,
signer: &S,
transfer: SubAccountSpotTransfer,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SubAccountSpotTransfer(transfer);
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Create a vault led by the signer and return its address.
///
/// `initial_usd` is in 1e-6 USDC units and must be at least 100 USDC. The action carries
/// the nonce a second time, which this sets for you.
pub async fn create_vault<S: SignerSync>(
&self,
signer: &S,
name: String,
description: String,
initial_usd: u64,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<Address> {
let action = Action::CreateVault(CreateVault {
name,
description,
initial_usd,
nonce,
});
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
match self.send(req).await? {
Response::Ok(OkResponse::CreateVault(address)) => Ok(address),
Response::Err(err) => Err(ApiError(err).into()),
other => Err(ApiError(format!("unexpected response: {other:?}")).into()),
}
}
/// Change a vault's deposit and withdrawal policy. `None` leaves a setting unchanged.
pub async fn vault_modify<S: SignerSync>(
&self,
signer: &S,
vault_address: Address,
allow_deposits: Option<bool>,
always_close_on_withdraw: Option<bool>,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::VaultModify(VaultModify {
vault_address,
allow_deposits,
always_close_on_withdraw,
});
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Pay USDC from a vault leader's balance out to depositors.
///
/// `usd` is in 1e-6 units; `0` closes the vault.
pub async fn vault_distribute<S: SignerSync>(
&self,
signer: &S,
vault_address: Address,
usd: u64,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::VaultDistribute(VaultDistribute { vault_address, usd });
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Set the display name shown on the leaderboard. An empty string clears it.
pub async fn set_display_name<S: SignerSync>(
&self,
signer: &S,
display_name: String,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SetDisplayName { display_name };
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Record the referral code the signer was referred by. Can only be set once.
pub async fn set_referrer<S: SignerSync>(
&self,
signer: &S,
code: String,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SetReferrer { code };
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Claim a referral code for the signer to refer others with.
pub async fn register_referrer<S: SignerSync>(
&self,
signer: &S,
code: String,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::RegisterReferrer { code };
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Opt in or out of automatic dusting of small spot balances.
pub async fn toggle_spot_dusting<S: SignerSync>(
&self,
signer: &S,
opt_out: bool,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::SpotUser(SpotUserAction {
toggle_spot_dusting: ToggleSpotDusting { opt_out },
});
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Link a HyperEVM contract to a HIP-1 token so the token can be traded on the EVM.
pub async fn finalize_evm_contract<S: SignerSync>(
&self,
signer: &S,
token: u32,
input: FinalizeEvmContractInput,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::FinalizeEvmContract(FinalizeEvmContract { token, input });
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Jail or unjail the signer's own validator.
pub async fn c_signer_action<S: SignerSync>(
&self,
signer: &S,
action: CSignerAction,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::CSignerAction(action);
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Register, reconfigure, or deregister the signer's validator.
pub async fn c_validator_action<S: SignerSync>(
&self,
signer: &S,
action: CValidatorAction,
nonce: u64,
expires_after: Option<DateTime<Utc>>,
) -> Result<()> {
let action = Action::CValidatorAction(action);
let req = action.sign_sync(signer, nonce, None, expires_after, self.chain)?;
self.send(req).await?.into_default()
}
/// Link a staking account to a trading account.
///
/// Sent twice: the staking account signs with `is_finalize = false`, then the trading
/// account signs with `is_finalize = true`. Each signer passes the *other* account as
/// `user`.
pub async fn link_staking_user<S: Signer + Send + Sync>(
&self,
signer: &S,
user: Address,
is_finalize: bool,
nonce: u64,
) -> Result<()> {
let action = Action::LinkStakingUser(LinkStakingUserAction {
signature_chain_id: self.chain.arbitrum_id().to_owned(),
hyperliquid_chain: self.chain,
user,
is_finalize,
nonce,
});
let req = action.sign(signer, nonce, None, None, self.chain).await?;
self.send(req).await?.into_default()
}
/// Remove a trading account's staking link.
pub async fn staking_link_disable_trading_user<S: Signer + Send + Sync>(
&self,
signer: &S,
trading_user: Address,
nonce: u64,
) -> Result<()> {
let action = Action::StakingLinkDisableTradingUser(StakingLinkDisableTradingUserAction {
signature_chain_id: self.chain.arbitrum_id().to_owned(),
hyperliquid_chain: self.chain,
trading_user,
nonce,
});
let req = action.sign(signer, nonce, None, None, self.chain).await?;
self.send(req).await?.into_default()
}
/// Enable or disable portfolio margin for an account.
pub async fn user_portfolio_margin<S: Signer + Send + Sync>(
&self,
signer: &S,
user: Address,
enabled: bool,
nonce: u64,
) -> Result<()> {
let action = Action::UserPortfolioMargin(UserPortfolioMarginAction {
signature_chain_id: self.chain.arbitrum_id().to_owned(),
hyperliquid_chain: self.chain,
user,
enabled,
nonce,
});
let req = action.sign(signer, nonce, None, None, self.chain).await?;
self.send(req).await?.into_default()
}
/// Submit a HIP-4 outcome action (`userOutcome`): split, merge, or negate outcome tokens.
///
/// See [`UserOutcomeAction`] for the available operations and their semantics, or use the
/// convenience methods [`split_outcome`](Self::split_outcome),
/// [`merge_outcome`](Self::merge_outcome), [`merge_outcome_question`](Self::merge_outcome_question),
/// and [`negate_outcome`](Self::negate_outcome).
pub fn user_outcome<S: SignerSync>(
&self,
signer: &S,
action: UserOutcomeAction,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<()>> + Send + 'static {
let future = self.sign_and_send_sync(
signer,
Action::UserOutcome(action),
nonce,
vault_address,
expires_after,
);
async move { future.await?.into_default() }
}
/// Split `amount` of the quote token into one share of each side of `outcome`.
pub fn split_outcome<S: SignerSync>(
&self,
signer: &S,
outcome: u32,
amount: Decimal,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<()>> + Send + 'static {
self.user_outcome(
signer,
UserOutcomeAction::split(outcome, amount),
nonce,
vault_address,
expires_after,
)
}
/// Merge matching shares of `outcome` back into the quote token.
///
/// `amount = None` merges the maximum available.
pub fn merge_outcome<S: SignerSync>(
&self,
signer: &S,
outcome: u32,
amount: Option<Decimal>,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<()>> + Send + 'static {
self.user_outcome(
signer,
UserOutcomeAction::merge(outcome, amount),
nonce,
vault_address,
expires_after,
)
}
/// Merge a full set of mutually-exclusive outcomes within `question` back into the quote token.
///
/// `amount = None` merges the maximum available.
pub fn merge_outcome_question<S: SignerSync>(
&self,
signer: &S,
question: u32,
amount: Option<Decimal>,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<()>> + Send + 'static {
self.user_outcome(
signer,
UserOutcomeAction::merge_question(question, amount),
nonce,
vault_address,
expires_after,
)
}
/// Negate `outcome` within `question`, converting its shares into the complementary basket.
pub fn negate_outcome<S: SignerSync>(
&self,
signer: &S,
question: u32,
outcome: u32,
amount: Decimal,
nonce: u64,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> impl Future<Output = Result<()>> + Send + 'static {
self.user_outcome(
signer,
UserOutcomeAction::negate(question, outcome, amount),
nonce,
vault_address,
expires_after,
)
}
}
/// Builder for constructing and executing multisig transactions on Hyperliquid.
///
/// The `MultiSig` struct provides a fluent API for building multisig transactions that require
/// multiple signers to authorize actions. It collects signatures from all required signers and
/// submits the complete multisig transaction to the exchange.
///
/// # Multisig Flow
///
/// 1. Create a `MultiSig` instance via `Client::multi_sig()`
/// 2. Add signers using `signer()` or `signers()`
/// 3. Execute an action (e.g., `place()`, `send_usdc()`)
/// 4. The builder collects signatures from all signers
/// 5. The lead signer submits the transaction
///
/// # Type Parameters
///
/// - `'a`: Lifetime of the client and signer references
/// - `S`: The signer type implementing `SignerSync + Signer`
///
/// # Example
///
/// ```rust,ignore
/// use hypersdk::hypercore::Client;
/// use alloy::signers::local::PrivateKeySigner;
///
/// let client = Client::mainnet();
/// let lead_signer: PrivateKeySigner = "0x...".parse()?;
/// let signer2: PrivateKeySigner = "0x...".parse()?;
/// let signer3: PrivateKeySigner = "0x...".parse()?;
/// let multisig_address = "0x...".parse()?;
/// let nonce = chrono::Utc::now().timestamp_millis() as u64;
///
/// // Execute a multisig order
/// let response = client
/// .multi_sig(&lead_signer, multisig_address, nonce)
/// .signer(&signer2)
/// .signer(&signer3)
/// .place(order, None, None)
/// .await?;
/// ```
///
/// # Notes
///
/// - The lead signer is the one who submits the transaction but also signs it
/// - All signers (including lead) must be authorized on the multisig wallet
/// - The order of signers should match the wallet's configuration
/// - Nonce must be unique for each transaction (typically millisecond timestamp)
pub struct MultiSig<'a, S: Signer + Send + Sync> {
lead: &'a S,
multi_sig_user: Address,
signers: VecDeque<&'a S>,
signatures: VecDeque<Signature>,
nonce: u64,
client: &'a Client,
}
impl<'a, S> MultiSig<'a, S>
where
S: Signer + Send + Sync,
{
/// Add a single signer to the multisig transaction.
///
/// This method adds one signer to the list of signers who will authorize the transaction.
/// You can chain multiple calls to add multiple signers.
///
/// # Parameters
///
/// - `signer`: A reference to the signer to add
///
/// # Example
///
/// ```rust,ignore
/// client
/// .multi_sig(&lead, multisig_addr, nonce)
/// .signer(&signer1)
/// .signer(&signer2)
/// .signer(&signer3)
/// .place(order, None, None)
/// .await?;
/// ```
pub fn signer(mut self, signer: &'a S) -> Self {
self.signers.push_back(signer);
self
}
/// Add multiple signers to the multisig transaction.
///
/// This method adds a collection of signers at once. More convenient than calling
/// `signer()` multiple times when you have signers in a collection.
///
/// # Parameters
///
/// - `signers`: An iterable collection of signer references
///
/// # Example
///
/// ```rust,ignore
/// let signers = vec![&signer1, &signer2, &signer3];
///
/// client
/// .multi_sig(&lead, multisig_addr, nonce)
/// .signers(signers)
/// .place(order, None, None)
/// .await?;
/// ```
pub fn signers(mut self, signers: impl IntoIterator<Item = &'a S>) -> Self {
self.signers.extend(signers);
self
}
/// Append pre-existing signatures to the multisig transaction.
///
/// This method allows you to include signatures that were already collected separately,
/// rather than generating them from signers. This is useful when:
/// - Signatures were collected offline or asynchronously
/// - You're aggregating signatures from multiple sources
/// - You have a partial multisig that needs additional signatures
///
/// The signatures should be in the same order and format as expected by the multisig
/// wallet configuration.
///
/// # Parameters
///
/// - `signatures`: An iterable collection of pre-existing signatures
///
/// # Example
///
/// ```rust,ignore
/// use hypersdk::hypercore::types::Signature;
///
/// // Signatures collected from external sources
/// let existing_sigs: Vec<Signature> = vec![
/// sig1, sig2, sig3
/// ];
///
/// client
/// .multi_sig(&lead, multisig_addr, nonce)
/// .signatures(existing_sigs)
/// .signer(&additional_signer) // Can still add more signers
/// .place(order, None, None)
/// .await?;
/// ```
///
/// # Notes
///
/// - Signatures are appended in order to the signature list
/// - You can mix pre-existing signatures with new signers
/// - Ensure signatures match the action being signed and the multisig configuration
/// - The total number of signatures must match the multisig threshold
pub fn signatures(mut self, signatures: impl IntoIterator<Item = Signature>) -> Self {
self.signatures.extend(signatures);
self
}
/// Place orders using the multisig account.
///
/// This method collects signatures from all signers for a batch order placement using
/// RMP (MessagePack) hashing, then submits the multisig transaction to the exchange.
///
/// # Process
///
/// 1. Creates an RMP hash of the order action
/// 2. Each signer signs the hash using EIP-712
/// 3. Collects all signatures into a `MultiSigAction`
/// 4. Lead signer submits the complete transaction
///
/// # Parameters
///
/// - `batch`: The batch order to place
/// - `vault_address`: Optional vault address if trading on behalf of a vault
/// - `expires_after`: Optional expiration time for the request
///
/// # Example
///
/// ```rust,ignore
/// use hypersdk::hypercore::types::{BatchOrder, OrderRequest, OrderTypePlacement, TimeInForce};
/// use rust_decimal::dec;
///
/// let order = OrderRequest {
/// asset: 0,
/// is_buy: true,
/// limit_px: dec!(50000),
/// sz: dec!(0.1),
/// reduce_only: false,
/// order_type: OrderTypePlacement::Limit {
/// tif: TimeInForce::Gtc,
/// },
/// cloid: [0u8; 16].into(),
/// };
///
/// let batch = BatchOrder {
/// orders: vec![order],
/// grouping: OrderGrouping::Na,
/// builder: None,
/// };
///
/// let statuses = client
/// .multi_sig(&lead, multisig_addr, nonce)
/// .signers(&signers)
/// .place(batch, None, None)
/// .await?;
///
/// for status in statuses {
/// match status {
/// OrderResponseStatus::Resting { oid, .. } => {
/// println!("Order {} placed", oid);
/// }
/// OrderResponseStatus::Error(err) => {
/// eprintln!("Order failed: {}", err);
/// }
/// _ => {}
/// }
/// }
/// ```
pub async fn place(
&self,
batch: BatchOrder,
vault_address: Option<Address>,
expires_after: Option<DateTime<Utc>>,
) -> Result<Vec<OrderResponseStatus>, ActionError<Cloid>> {
let cloids: Vec<_> = batch.orders.iter().map(|req| req.cloid).collect();
let action = multisig_collect_signatures_with_context(
self.lead.address(),
self.multi_sig_user,
self.signers.iter().copied(),
self.signatures.iter().copied(),
Action::Order(batch),
self.nonce,
vault_address,
expires_after,
self.client.chain,
)
.await
.map_err(|err| ActionError {
ids: cloids.clone(),
err: err.to_string(),
})?;
let resp = self
.client
.sign_and_send(self.lead, action, self.nonce, vault_address, expires_after)
.await
.map_err(|err| ActionError {
ids: cloids.clone(),
err: err.to_string(),
})?;
match resp {
Response::Ok(OkResponse::Order { statuses }) => Ok(statuses),
Response::Err(err) => Err(ActionError { ids: cloids, err }),
_ => Err(ActionError {
ids: cloids,
err: format!("unexpected response type: {resp:?}"),
}),
}
}
/// Send USDC from the multisig account.
///
/// This method collects signatures from all signers for a USDC transfer using EIP-712
/// typed data, then submits the multisig transaction to the exchange.
///
/// # Process
///
/// 1. Creates EIP-712 typed data from the UsdSend action
/// 2. Each signer signs the typed data directly using EIP-712
/// 3. Collects all signatures into a `MultiSigAction`
/// 4. Lead signer submits the complete transaction
///
/// # Parameters
///
/// - `send`: The UsdSend parameters (destination, amount, time, chain, etc.)
///
/// # Example
///
/// ```rust,ignore
/// use hypersdk::hypercore::types::{UsdSend, Chain};
/// use hypersdk::hypercore::ARBITRUM_SIGNATURE_CHAIN_ID;
/// use rust_decimal::dec;
///
/// let send = UsdSend {
/// hyperliquid_chain: Chain::Mainnet,
/// signature_chain_id: ARBITRUM_SIGNATURE_CHAIN_ID,
/// destination: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb".parse()?,
/// amount: dec!(100),
/// time: chrono::Utc::now().timestamp_millis() as u64,
/// };
///
/// client
/// .multi_sig(&lead_signer, multisig_address, nonce)
/// .signers(&signers)
/// .send_usdc(send)
/// .await?;
///
/// println!("Successfully sent 100 USDC from multisig account");
/// ```
///
/// # Notes
///
/// - Uses EIP-712 typed data signatures (different from order placement which uses RMP)
/// - Time should typically be the current timestamp in milliseconds
/// - Destination can be any valid Ethereum address
/// - Amount is in USDC (6 decimals on-chain, but use regular decimal representation)
pub async fn send_usdc(&self, send: UsdSend) -> Result<()> {
let nonce = send.time;
let action = multisig_collect_signatures(
self.lead.address(),
self.multi_sig_user,
self.signers.iter().copied(),
self.signatures.iter().copied(),
send.into_action(self.client.chain()).into(),
nonce,
self.client.chain,
)
.await?;
let resp = self
.client
.sign_and_send(self.lead, action, self.nonce, None, None)
.await?;
resp.into_default()
}
/// Send assets from the multisig account.
///
/// This method collects signatures from all signers for an asset transfer using EIP-712
/// typed data, then submits the multisig transaction to the exchange. This can be used
/// to transfer assets between different destinations (accounts, DEXes, subaccounts).
///
/// # Process
///
/// 1. Creates EIP-712 typed data from the SendAsset action
/// 2. Each signer signs the typed data directly using EIP-712
/// 3. Collects all signatures into a `MultiSigAction`
/// 4. Lead signer submits the complete transaction
///
/// # Parameters
///
/// - `send`: The SendAsset parameters (destination, token, amount, source/dest DEX, etc.)
///
/// # Example
///
/// ```rust,ignore
/// use hypersdk::hypercore::types::{SendAsset, SendToken};
/// use hypersdk::hypercore::ARBITRUM_MAINNET_CHAIN_ID;
/// use rust_decimal::dec;
///
/// // Get the token info first
/// let tokens = client.spot_meta().await?;
/// let usdc = tokens.iter().find(|t| t.name == "USDC").unwrap();
///
/// let send = SendAsset {
/// hyperliquid_chain: Chain::Mainnet,
/// signature_chain_id: ARBITRUM_MAINNET_CHAIN_ID,
/// destination: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb".parse()?,
/// source_dex: "".to_string(), // Empty for perp balance
/// destination_dex: "".to_string(), // Empty for recipient's perp balance
/// token: SendToken(usdc.clone()),
/// from_sub_account: "".to_string(), // Empty for main account
/// amount: dec!(100),
/// nonce: chrono::Utc::now().timestamp_millis() as u64,
/// };
///
/// client
/// .multi_sig(&lead_signer, multisig_address, nonce)
/// .signers(&signers)
/// .send_asset(send)
/// .await?;
///
/// println!("Successfully sent 100 USDC from multisig account");
/// ```
///
/// # Notes
///
/// - Uses EIP-712 typed data signatures (different from order placement which uses RMP)
/// - Source/destination DEX can be: "" (perp balance), "spot", or other DEX identifiers
/// - Token must be obtained from `spot_meta()` API call
/// - Nonce should be unique for each transaction (typically current timestamp in ms)
pub async fn send_asset(&self, send: SendAsset) -> Result<()> {
let nonce = send.nonce;
let action = multisig_collect_signatures(
self.lead.address(),
self.multi_sig_user,
self.signers.iter().copied(),
self.signatures.iter().copied(),
send.into_action(self.client.chain()).into(),
nonce,
self.client.chain,
)
.await?;
let resp = self
.client
.sign_and_send(self.lead, action, self.nonce, None, None)
.await?;
resp.into_default()
}
/// Approve a new agent for the multisig account.
///
/// Approves an agent to act on behalf of the multisig account. An account can have:
/// - 1 unnamed approved wallet
/// - Up to 3 named agents
/// - 2 named agents per subaccount
///
/// # Parameters
///
/// - `agent`: The address of the agent to approve
/// - `name`: The name for the agent (or empty string for unnamed)
///
/// # Example
///
/// ```rust,ignore
/// let agent = address!("0x97271b6b7f3b23a2f4700ae671b05515ae5c3319");
/// let name = "my_agent".to_string();
///
/// client
/// .multi_sig(&lead, multisig_addr, nonce)
/// .signer(&signer1)
/// .signer(&signer2)
/// .approve_agent(agent, name)
/// .await?;
/// ```
pub async fn approve_agent(&self, agent: Address, name: String) -> Result<()> {
let chain = self.client.chain;
let signature_chain_id = chain.arbitrum_id().to_owned();
let approve_agent = ApproveAgent {
signature_chain_id,
hyperliquid_chain: chain,
agent_address: agent,
agent_name: if name.is_empty() { None } else { Some(name) },
nonce: self.nonce,
};
let action = multisig_collect_signatures(
self.lead.address(),
self.multi_sig_user,
self.signers.iter().copied(),
self.signatures.iter().copied(),
Action::ApproveAgent(approve_agent),
self.nonce,
self.client.chain,
)
.await?;
let resp = self
.client
.sign_and_send(self.lead, action, self.nonce, None, None)
.await?;
resp.into_default()
}
/// Approve the maximum fee rate a builder can charge for routed orders.
pub async fn approve_builder_fee(&self, builder: Address, max_fee_rate: String) -> Result<()> {
let chain = self.client.chain;
let approve_builder_fee = ApproveBuilderFee {
signature_chain_id: chain.arbitrum_id().to_owned(),
hyperliquid_chain: chain,
max_fee_rate,
builder,
nonce: self.nonce,
};
let action = multisig_collect_signatures(
self.lead.address(),
self.multi_sig_user,
self.signers.iter().copied(),
self.signatures.iter().copied(),
Action::ApproveBuilderFee(approve_builder_fee),
self.nonce,
self.client.chain,
)
.await?;
let resp = self
.client
.sign_and_send(self.lead, action, self.nonce, None, None)
.await?;
resp.into_default()
}
/// Convert multisig account back to normal user.
///
/// Converts the multisig account back to a regular single-signer account by setting
/// the signers to null. After conversion, the account will only require a single
/// signature to execute transactions.
///
/// # Example
///
/// ```rust,ignore
/// client
/// .multi_sig(&lead, multisig_addr, nonce)
/// .signer(&signer1)
/// .signer(&signer2)
/// .convert_to_normal_user()
/// .await?;
/// ```
pub async fn convert_to_normal_user(&self) -> Result<()> {
let chain = self.client.chain;
let convert = ConvertToMultiSigUser {
signature_chain_id: chain.arbitrum_id().to_owned(),
hyperliquid_chain: chain,
signers: SignersConfig {
authorized_users: vec![], // Empty vec serializes to "null"
threshold: 0,
},
nonce: self.nonce,
};
let action = multisig_collect_signatures(
self.lead.address(),
self.multi_sig_user,
self.signers.iter().copied(),
self.signatures.iter().copied(),
Action::ConvertToMultiSigUser(convert),
self.nonce,
self.client.chain,
)
.await?;
let resp = self
.client
.sign_and_send(self.lead, action, self.nonce, None, None)
.await?;
resp.into_default()
}
}