Drift Client

This object is used to interact with the protocol (deposit, withdraw, trade, lp, etc.)

Example

drift_client = DriftClient.from_config(config,provider)
# open a 10 SOL long position
sig = await drift_client.open_position(
    PositionDirection.LONG(), # long
    int(10 * BASE_PRECISION), # 10 in base precision
    0, # sol market index
)

# mint 100 LP shares on the SOL market
await drift_client.add_liquidity(
    int(100 * AMM_RESERVE_PRECISION),
    0,
)

Configuration

Use the JUPITER_URL environment variable to set the endpoint URL for the Jupiter V6 Swap API. This allows you to switch between self-hosted, paid-hosted, or other public API endpoints such as jupiterapi.com for higher rate limits and reduced latency. For more details, see the official self-hosted and paid-hosted documentation.

drift_client

DEFAULT_TX_OPTIONS = TxOpts(skip_confirmation=False, preflight_commitment=Processed) module-attribute

DEFAULT_USER_NAME = 'Main Account' module-attribute

DriftClient

This class is the main way to interact with Drift Protocol including depositing, opening new positions, closing positions, placing orders, etc.

Source code in src/driftpy/drift_client.py
 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
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
class DriftClient:
    """This class is the main way to interact with Drift Protocol including
    depositing, opening new positions, closing positions, placing orders, etc.
    """

    def __init__(
        self,
        connection: AsyncClient,
        wallet: Keypair | Wallet,
        env: DriftEnv | None = "mainnet",
        opts: TxOpts = DEFAULT_TX_OPTIONS,
        authority: Pubkey | None = None,
        account_subscription: AccountSubscriptionConfig = AccountSubscriptionConfig.default(),
        perp_market_indexes: list[int] | None = None,
        spot_market_indexes: list[int] | None = None,
        oracle_infos: list[OracleInfo] | None = None,
        tx_params: Optional[TxParams] = None,
        tx_version: Optional[TransactionVersion] = None,
        tx_sender: TxSender | None = None,
        active_sub_account_id: Optional[int] = None,
        sub_account_ids: Optional[list[int]] = None,
        market_lookup_table: Optional[Pubkey] = None,
        market_lookup_tables: Optional[list[Pubkey]] = None,
        jito_params: Optional[JitoParams] = None,
        tx_sender_blockhash_commitment: Commitment | None = None,
        enforce_tx_sequencing: bool = False,
    ):
        """Initializes the drift client object

        Args:
            connection (AsyncClient): Solana RPC connection
            wallet (Keypair | Wallet): Wallet for transaction signing
            env (DriftEnv | None, optional): Drift environment. Defaults to "mainnet".
            opts (TxOpts, optional): Transaction options. Defaults to DEFAULT_TX_OPTIONS.
            authority (Pubkey | None, optional): Authority for transactions. If None, defaults to wallet's public key.
            account_subscription (AccountSubscriptionConfig, optional): Config for account subscriptions. Defaults to AccountSubscriptionConfig.default().
            perp_market_indexes (list[int] | None, optional): List of perp market indexes to subscribe to. Defaults to None.
            spot_market_indexes (list[int] | None, optional): List of spot market indexes to subscribe to. Defaults to None.
            oracle_infos (list[OracleInfo] | None, optional): List of oracle infos to subscribe to. Defaults to None.
            tx_params (Optional[TxParams], optional): Transaction parameters. Defaults to None.
            tx_version (Optional[TransactionVersion], optional): Transaction version. Defaults to None.
            tx_sender (TxSender | None, optional): Custom transaction sender. Defaults to None.
            active_sub_account_id (Optional[int], optional): Active sub-account ID. Defaults to None.
            sub_account_ids (Optional[list[int]], optional): List of sub-account IDs. Defaults to None.
            market_lookup_table (Optional[Pubkey], optional): Market lookup table pubkey (deprecated). Defaults to None.
            market_lookup_tables (Optional[list[Pubkey]], optional): List of market lookup table pubkeys. Defaults to None.
            jito_params (Optional[JitoParams], optional): Parameters for Jito MEV integration. Defaults to None.
            tx_sender_blockhash_commitment (Commitment | None, optional): Blockhash commitment for tx sender. Defaults to None.
            enforce_tx_sequencing (bool, optional): Whether to enforce transaction sequencing. Defaults to False.
        """
        self.connection = connection
        self.signer_public_key: Optional[Pubkey] = None

        file = Path(str(next(iter(driftpy.__path__))) + "/idl/drift.json")
        idl = Idl.from_json(file.read_text())

        if isinstance(wallet, Keypair):
            wallet = Wallet(wallet)

        provider = Provider(connection, wallet, opts)
        self.program_id = DRIFT_PROGRAM_ID
        self.program = Program(idl, self.program_id, provider)

        if authority is None:
            authority = wallet.public_key

        self.wallet: Wallet = wallet
        self.authority = authority

        self.active_sub_account_id = (
            active_sub_account_id if active_sub_account_id is not None else 0
        )
        self.sub_account_ids = (
            sub_account_ids
            if sub_account_ids is not None
            else [self.active_sub_account_id]
        )
        self.users: dict[int, DriftUser] = {}
        self.user_stats: dict[Pubkey, DriftUserStats] = {}

        self.last_perp_market_seen_cache = {}
        self.last_spot_market_seen_cache = {}

        self.account_subscriber = account_subscription.get_drift_client_subscriber(
            self.program, perp_market_indexes, spot_market_indexes, oracle_infos
        )
        if self.account_subscriber is None:
            raise ValueError("No account subscriber found")

        self.account_subscription_config = account_subscription

        # deprecated, use market_lookup_tables instead
        self.market_lookup_table = None
        if env is not None:
            self.market_lookup_table = (
                market_lookup_table
                if market_lookup_table is not None
                else configs[env].market_lookup_table
            )
        # deprecated, use market_lookup_table_accounts instead
        self.market_lookup_table_account: Optional[AddressLookupTableAccount] = None

        self.market_lookup_tables = None
        if env is not None and market_lookup_tables is not None:
            self.market_lookup_tables = market_lookup_tables
        else:
            self.market_lookup_tables = configs[env].market_lookup_tables

        self.market_lookup_table_accounts: list[AddressLookupTableAccount] = []

        if tx_params is None:
            tx_params = TxParams(600_000, 0)

        self.tx_params = tx_params

        self.tx_version = tx_version if tx_version is not None else 0

        self.enforce_tx_sequencing = enforce_tx_sequencing
        if self.enforce_tx_sequencing is True:
            file = Path(
                str(next(iter(driftpy.__path__))) + "/idl/sequence_enforcer.json"
            )
            idl = Idl.from_json(file.read_text())

            provider = Provider(connection, wallet, opts)
            self.sequence_enforcer_pid = (
                SEQUENCER_PROGRAM_ID
                if env == "mainnet"
                else DEVNET_SEQUENCER_PROGRAM_ID
            )
            self.sequence_enforcer_program = Program(
                idl,
                self.sequence_enforcer_pid,
                provider,
            )
            self.sequence_number_by_subaccount = {}
            self.sequence_bump_by_subaccount = {}
            self.sequence_initialized_by_subaccount = {}
            self.sequence_address_by_subaccount = {}
            self.resetting_sequence = False

        if jito_params is not None:
            from driftpy.tx.jito_tx_sender import JitoTxSender

            self.tx_sender = JitoTxSender(
                self,
                opts,
                jito_params.block_engine_url,
                jito_params.jito_keypair,
                blockhash_refresh_interval_secs=jito_params.blockhash_refresh_rate,
                tip_amount=jito_params.tip_amount,
            )
        else:
            self.tx_sender = (
                StandardTxSender(
                    self.connection,
                    opts,
                    blockhash_commitment=(
                        tx_sender_blockhash_commitment
                        if tx_sender_blockhash_commitment is not None
                        else Commitment("finalized")
                    ),
                )
                if tx_sender is None
                else tx_sender
            )

    async def subscribe(self):
        if self.account_subscriber is None:
            raise ValueError("No account subscriber found")
        await self.account_subscriber.subscribe()
        if self.enforce_tx_sequencing:
            await self.load_sequence_info()
        for sub_account_id in self.sub_account_ids:
            await self.add_user(sub_account_id)
        await self.add_user_stats(self.authority)

    async def fetch_market_lookup_table_accounts(self):
        if self.market_lookup_tables is None:
            raise ValueError("No market lookup tables found")
        self.market_lookup_table_accounts: list[
            AddressLookupTableAccount
        ] = await asyncio.gather(
            *[
                get_address_lookup_table(self.connection, table)
                for table in self.market_lookup_tables
            ]
        )
        return self.market_lookup_table_accounts

    def resurrect(self, spot_markets, perp_markets, spot_oracles, perp_oracles):
        if not isinstance(self.account_subscriber, CachedDriftClientAccountSubscriber):
            raise ValueError(
                'You can only resurrect a DriftClient that was initialized with AccountSubscriptionConfig("cached")'
            )
        self.account_subscriber.resurrect(
            spot_markets, perp_markets, spot_oracles, perp_oracles
        )

    async def add_user(self, sub_account_id: int):
        if sub_account_id in self.users:
            return

        user = DriftUser(
            drift_client=self,
            user_public_key=self.get_user_account_public_key(sub_account_id),
            account_subscription=self.account_subscription_config,
        )
        await user.subscribe()
        self.users[sub_account_id] = user

    async def add_user_stats(self, authority: Pubkey):
        if authority in self.user_stats:
            return

        self.user_stats[authority] = DriftUserStats(
            self,
            self.get_user_stats_public_key(),
            UserStatsSubscriptionConfig("confirmed"),
        )

        # don't subscribe because up to date UserStats is not required
        await self.user_stats[authority].fetch_accounts()

    async def unsubscribe(self):
        if self.account_subscriber is None:
            raise ValueError("No account subscriber found")
        await self.account_subscriber.unsubscribe()

    def get_user(self, sub_account_id: int | None = None) -> DriftUser:
        sub_account_id = (
            sub_account_id if sub_account_id is not None else self.active_sub_account_id
        )
        if sub_account_id not in self.sub_account_ids:
            raise KeyError(
                f"No sub account id {sub_account_id} found, need to include in `sub_account_ids` when initializing DriftClient"
            )

        if sub_account_id not in self.users:
            raise KeyError(
                f"No sub account id {sub_account_id} found, need to call `await DriftClient.subscribe()` first"
            )

        return self.users[sub_account_id]

    def get_user_account(self, sub_account_id=None) -> UserAccount:
        return self.get_user(sub_account_id).get_user_account()

    def get_user_stats(self, authority=None) -> DriftUserStats:
        if authority is None:
            authority = self.authority

        if authority not in self.user_stats:
            raise KeyError(
                f"No UserStats for {authority} found, need to call `await DriftClient.subscribe()` first"
            )

        return self.user_stats[authority]

    def switch_active_user(self, sub_account_id: int):
        self.active_sub_account_id = sub_account_id

    def get_state_public_key(self):
        return get_state_public_key(self.program_id)

    def get_signer_public_key(self) -> Pubkey:
        if self.signer_public_key:
            return self.signer_public_key

        self.signer_public_key = get_drift_client_signer_public_key(self.program_id)
        return self.signer_public_key

    def get_user_account_public_key(self, sub_account_id=None) -> Pubkey:
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
        return get_user_account_public_key(
            self.program_id, self.authority, sub_account_id
        )

    def get_user_stats_public_key(self):
        return get_user_stats_account_public_key(self.program_id, self.authority)

    def get_associated_token_account_public_key(self, market_index: int) -> Pubkey:
        spot_market = self.get_spot_market_account(market_index)
        mint = spot_market.mint
        return get_associated_token_address(self.wallet.public_key, mint)

    def get_state_account(self) -> Optional[StateAccount]:
        state_and_slot = self.account_subscriber.get_state_account_and_slot()
        return getattr(state_and_slot, "data", None)

    def get_perp_market_account(self, market_index: int) -> Optional[PerpMarketAccount]:
        if self.account_subscriber is None:
            raise ValueError("No account subscriber found")
        perp_market_and_slot = self.account_subscriber.get_perp_market_and_slot(
            market_index
        )
        return getattr(perp_market_and_slot, "data", None)

    def get_spot_market_account(self, market_index: int) -> Optional[SpotMarketAccount]:
        spot_market_and_slot = self.account_subscriber.get_spot_market_and_slot(
            market_index
        )
        return getattr(spot_market_and_slot, "data", None)

    def get_quote_spot_market_account(self) -> Optional[SpotMarketAccount]:
        spot_market_and_slot = self.account_subscriber.get_spot_market_and_slot(
            QUOTE_SPOT_MARKET_INDEX
        )
        return getattr(spot_market_and_slot, "data", None)

    def get_oracle_price_data(self, oracle_id: str) -> Optional[OraclePriceData]:
        if self.account_subscriber is None:
            return None

        data_and_slot = self.account_subscriber.get_oracle_price_data_and_slot(
            oracle_id
        )

        if data_and_slot is None:
            return None

        return getattr(data_and_slot, "data", None)

    def get_oracle_price_data_for_perp_market(
        self, market_index: int
    ) -> Optional[OraclePriceData]:
        if self.account_subscriber is None:
            raise ValueError("No account subscriber found")

        if isinstance(self.account_subscriber, DemoDriftClientAccountSubscriber):
            raise ValueError("Cannot get market for demo subscriber")

        data = self.account_subscriber.get_oracle_price_data_and_slot_for_perp_market(
            market_index
        )
        if isinstance(data, DataAndSlot):
            return getattr(
                data,
                "data",
                None,
            )

        return data

    def get_oracle_price_data_for_spot_market(
        self, market_index: int
    ) -> Optional[OraclePriceData]:
        if self.account_subscriber is None:
            return None
        if isinstance(self.account_subscriber, DemoDriftClientAccountSubscriber):
            raise ValueError("Cannot get market for demo subscriber")

        data = self.account_subscriber.get_oracle_price_data_and_slot_for_spot_market(
            market_index
        )
        if isinstance(data, DataAndSlot):
            return getattr(
                data,
                "data",
                None,
            )

        return data

    def convert_to_spot_precision(self, amount: Union[int, float], market_index) -> int:
        spot_market = self.get_spot_market_account(market_index)
        return cast_to_spot_precision(amount, spot_market)

    def convert_to_perp_precision(self, amount: Union[int, float]) -> int:
        return int(amount * BASE_PRECISION)

    def convert_to_price_precision(self, amount: Union[int, float]) -> int:
        return int(amount * PRICE_PRECISION)

    def get_sub_account_id_for_ix(self, sub_account_id: Optional[int] = None):
        return (
            sub_account_id if sub_account_id is not None else self.active_sub_account_id
        )

    async def fetch_market_lookup_table(self) -> AddressLookupTableAccount:
        if self.market_lookup_table_account is not None:
            return self.market_lookup_table_account

        self.market_lookup_table_account = await get_address_lookup_table(
            self.connection, self.market_lookup_table
        )
        return self.market_lookup_table_account

    async def send_ixs(
        self,
        ixs: Union[Instruction, list[Instruction]],
        signers=None,
        lookup_tables: list[AddressLookupTableAccount] = None,
        tx_version: Optional[Union[Legacy, int]] = None,
        sequencer_subaccount: Optional[int] = None,
    ) -> TxSigAndSlot:
        if isinstance(ixs, Instruction):
            ixs = [ixs]

        if not tx_version:
            tx_version = self.tx_version

        compute_unit_instructions = []
        if self.tx_params.compute_units is not None:
            compute_unit_instructions.append(
                set_compute_unit_limit(self.tx_params.compute_units)
            )

        if self.tx_params.compute_units_price is not None:
            compute_unit_instructions.append(
                set_compute_unit_price(self.tx_params.compute_units_price)
            )

        ixs[0:0] = compute_unit_instructions

        subaccount = sequencer_subaccount or self.active_sub_account_id

        if (
            self.enforce_tx_sequencing
            and self.sequence_initialized_by_subaccount[subaccount]
            and not self.resetting_sequence
        ):
            sequence_instruction = self.get_check_and_set_sequence_number_ix(
                self.sequence_number_by_subaccount[subaccount], subaccount
            )
            ixs.insert(len(compute_unit_instructions), sequence_instruction)

        if tx_version == Legacy:
            tx = await self.tx_sender.get_legacy_tx(ixs, self.wallet.payer, signers)
        elif tx_version == 0:
            if lookup_tables is None:
                lookup_tables = await self.fetch_market_lookup_table_accounts()
            tx = await self.tx_sender.get_versioned_tx(
                ixs, self.wallet.payer, lookup_tables, signers
            )
        else:
            raise NotImplementedError("unknown tx version", self.tx_version)

        return await self.tx_sender.send(tx)

    def get_remaining_accounts(
        self,
        user_accounts: list[UserAccount] = (),
        writable_perp_market_indexes: list[int] = (),
        writable_spot_market_indexes: list[int] = (),
        readable_spot_market_indexes: list[int] = (),
        readable_perp_market_indexes: list[int] = (),
    ):
        (
            oracle_map,
            spot_market_map,
            perp_market_map,
        ) = self.get_remaining_accounts_for_users(user_accounts)

        last_user_slot = self.get_user().get_user_account_and_slot().slot
        for perp_market_index, slot in self.last_perp_market_seen_cache.items():
            if slot > last_user_slot:
                self.add_perp_market_to_remaining_account_maps(
                    perp_market_index,
                    False,
                    oracle_map,
                    spot_market_map,
                    perp_market_map,
                )

        for spot_market_index, slot in self.last_spot_market_seen_cache.items():
            if slot > last_user_slot:
                self.add_spot_market_to_remaining_account_maps(
                    spot_market_index, False, oracle_map, spot_market_map
                )

        for perp_market_index in readable_perp_market_indexes:
            self.add_perp_market_to_remaining_account_maps(
                perp_market_index, False, oracle_map, spot_market_map, perp_market_map
            )

        for spot_market_index in readable_spot_market_indexes:
            self.add_spot_market_to_remaining_account_maps(
                spot_market_index, False, oracle_map, spot_market_map
            )

        for perp_market_index in writable_perp_market_indexes:
            self.add_perp_market_to_remaining_account_maps(
                perp_market_index, True, oracle_map, spot_market_map, perp_market_map
            )

        for spot_market_index in writable_spot_market_indexes:
            self.add_spot_market_to_remaining_account_maps(
                spot_market_index, True, oracle_map, spot_market_map
            )

        remaining_accounts = [
            *oracle_map.values(),
            *spot_market_map.values(),
            *perp_market_map.values(),
        ]

        return remaining_accounts

    def add_perp_market_to_remaining_account_maps(
        self,
        market_index: int,
        writable: bool,
        oracle_account_map: dict[str, AccountMeta],
        spot_market_account_map: dict[int, AccountMeta],
        perp_market_account_map: dict[int, AccountMeta],
    ) -> None:
        perp_market_account = self.get_perp_market_account(market_index)
        if not perp_market_account:
            raise ValueError(
                f"No perp market account found for market index {market_index}"
            )

        perp_market_account_map[market_index] = AccountMeta(
            pubkey=perp_market_account.pubkey, is_signer=False, is_writable=writable
        )

        oracle_writable = writable and is_variant(
            perp_market_account.amm.oracle_source, "Prelaunch"
        )
        oracle_account_map[str(perp_market_account.amm.oracle)] = AccountMeta(
            pubkey=perp_market_account.amm.oracle,
            is_signer=False,
            is_writable=oracle_writable,
        )

        self.add_spot_market_to_remaining_account_maps(
            perp_market_account.quote_spot_market_index,
            False,
            oracle_account_map,
            spot_market_account_map,
        )

    def add_spot_market_to_remaining_account_maps(
        self,
        market_index: int,
        writable: bool,
        oracle_account_map: dict[str, AccountMeta],
        spot_market_account_map: dict[int, AccountMeta],
    ) -> None:
        spot_market_account = self.get_spot_market_account(market_index)

        spot_market_account_map[market_index] = AccountMeta(
            pubkey=spot_market_account.pubkey, is_signer=False, is_writable=writable
        )

        if spot_market_account.oracle != Pubkey.default():
            oracle_account_map[str(spot_market_account.oracle)] = AccountMeta(
                pubkey=spot_market_account.oracle, is_signer=False, is_writable=False
            )

    def get_remaining_accounts_for_users(
        self, user_accounts: list[UserAccount]
    ) -> (dict[str, AccountMeta], dict[int, AccountMeta], dict[int, AccountMeta]):
        oracle_map = {}
        spot_market_map = {}
        perp_market_map = {}

        for user_account in user_accounts:
            for spot_position in user_account.spot_positions:
                if not is_spot_position_available(spot_position):
                    self.add_spot_market_to_remaining_account_maps(
                        spot_position.market_index, False, oracle_map, spot_market_map
                    )

                if spot_position.open_asks != 0 or spot_position.open_bids != 0:
                    self.add_spot_market_to_remaining_account_maps(
                        QUOTE_SPOT_MARKET_INDEX, False, oracle_map, spot_market_map
                    )

            for position in user_account.perp_positions:
                if not is_available(position):
                    self.add_perp_market_to_remaining_account_maps(
                        position.market_index,
                        False,
                        oracle_map,
                        spot_market_map,
                        perp_market_map,
                    )

        return oracle_map, spot_market_map, perp_market_map

    def add_spot_fulfillment_accounts(
        self,
        market_index: int,
        remaining_accounts: list[AccountMeta],
        fulfillment_config: Optional[
            Union[SerumV3FulfillmentConfigAccount, PhoenixV1FulfillmentConfigAccount]
        ] = None,
    ) -> None:
        if fulfillment_config is not None:
            if isinstance(fulfillment_config, SerumV3FulfillmentConfigAccount):
                self.add_serum_remaining_accounts(
                    market_index, remaining_accounts, fulfillment_config
                )
            elif isinstance(fulfillment_config, PhoenixV1FulfillmentConfigAccount):
                self.add_phoenix_remaining_accounts(
                    market_index, remaining_accounts, fulfillment_config
                )
            else:
                raise Exception(
                    f"unknown fulfillment config: {type(fulfillment_config)}"
                )
        else:
            remaining_accounts.append(
                AccountMeta(
                    self.get_spot_market_account(market_index).vault,
                    is_writable=False,
                    is_signer=False,
                )
            )
            remaining_accounts.append(
                AccountMeta(
                    self.get_spot_market_account(QUOTE_SPOT_MARKET_INDEX).vault,
                    is_writable=False,
                    is_signer=False,
                )
            )

    def add_serum_remaining_accounts(
        self,
        market_index: int,
        remaining_accounts: list[AccountMeta],
        fulfillment_config: SerumV3FulfillmentConfigAccount,
    ) -> None:
        remaining_accounts.append(
            AccountMeta(fulfillment_config.pubkey, is_writable=False, is_signer=False)
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_program_id, is_writable=False, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_market, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_request_queue,
                is_writable=True,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_event_queue, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_bids, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_asks, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_base_vault, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_quote_vault, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.serum_open_orders, is_writable=True, is_signer=False
            )
        )
        serum_signer_key = get_serum_signer_public_key(
            fulfillment_config.serum_program_id,
            fulfillment_config.serum_market,
            fulfillment_config.serum_signer_nonce,
        )
        remaining_accounts.append(
            AccountMeta(serum_signer_key, is_writable=False, is_signer=False)
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_signer_public_key(), is_writable=False, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(TOKEN_PROGRAM_ID, is_writable=False, is_signer=False)
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_spot_market_account(market_index).vault,
                is_writable=True,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_spot_market_account(QUOTE_SPOT_MARKET_INDEX).vault,
                is_writable=True,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_state_account().srm_vault, is_writable=False, is_signer=False
            )
        )

    def add_phoenix_remaining_accounts(
        self,
        market_index: int,
        remaining_accounts: list[AccountMeta],
        fulfillment_config: PhoenixV1FulfillmentConfigAccount,
    ) -> None:
        remaining_accounts.append(
            AccountMeta(fulfillment_config.pubkey, is_writable=False, is_signer=False)
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.phoenix_program_id,
                is_writable=False,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.phoenix_log_authority,
                is_writable=False,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.phoenix_market, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_signer_public_key(), is_writable=False, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.phoenix_base_vault, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                fulfillment_config.phoenix_quote_vault,
                is_writable=True,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_spot_market_account(market_index).vault,
                is_writable=True,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_spot_market_account(QUOTE_SPOT_MARKET_INDEX).vault,
                is_writable=True,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(TOKEN_PROGRAM_ID, is_writable=False, is_signer=False)
        )

    async def initialize_user(
        self,
        sub_account_id: int = 0,
        name: str = None,
        referrer_info: ReferrerInfo = None,
    ) -> Signature:
        """intializes a drift user

        Args:
            sub_account_id (int, optional): subaccount id to initialize. Defaults to 0.

        Returns:
            str: tx signature
        """
        ixs = []
        if sub_account_id == 0:
            ixs.append(self.get_initialize_user_stats())
            if name is None:
                name = DEFAULT_USER_NAME

        if name is None:
            name = "Subaccount " + str(sub_account_id + 1)

        ix = self.get_initialize_user_instructions(sub_account_id, name, referrer_info)
        ixs.append(ix)
        return (await self.send_ixs(ixs)).tx_sig

    def get_initialize_user_stats(
        self,
    ):
        state_public_key = self.get_state_public_key()
        user_stats_public_key = self.get_user_stats_public_key()

        return self.program.instruction["initialize_user_stats"](
            ctx=Context(
                accounts={
                    "user_stats": user_stats_public_key,
                    "state": state_public_key,
                    "authority": self.wallet.public_key,
                    "payer": self.wallet.public_key,
                    "rent": RENT,
                    "system_program": ID,
                },
            ),
        )

    def get_initialize_user_instructions(
        self,
        sub_account_id: int = 0,
        name: str = DEFAULT_USER_NAME,
        referrer_info: ReferrerInfo = None,
    ) -> Instruction:
        user_public_key = self.get_user_account_public_key(sub_account_id)
        state_public_key = self.get_state_public_key()
        user_stats_public_key = self.get_user_stats_public_key()

        encoded_name = encode_name(name)

        remaining_accounts = []
        if referrer_info is not None:
            remaining_accounts.append(
                AccountMeta(referrer_info.referrer, is_writable=True, is_signer=False)
            )
            remaining_accounts.append(
                AccountMeta(
                    referrer_info.referrer_stats, is_writable=True, is_signer=False
                )
            )

        initialize_user_account_ix = self.program.instruction["initialize_user"](
            sub_account_id,
            encoded_name,
            ctx=Context(
                accounts={
                    "user": user_public_key,
                    "user_stats": user_stats_public_key,
                    "state": state_public_key,
                    "authority": self.wallet.public_key,
                    "payer": self.wallet.public_key,
                    "rent": RENT,
                    "system_program": ID,
                },
                remaining_accounts=remaining_accounts,
            ),
        )
        return initialize_user_account_ix

    def random_string(self, length: int) -> str:
        return "".join(random.choices(string.ascii_letters + string.digits, k=length))

    async def get_wrapped_sol_account_creation_ixs(
        self, amount: int, include_rent: bool = True
    ) -> (List[Instruction], Pubkey):
        wallet_pubkey = self.wallet.public_key
        seed = self.random_string(32)
        wrapped_sol_account = Pubkey.create_with_seed(
            wallet_pubkey, seed, TOKEN_PROGRAM_ID
        )
        result = {"ixs": [], "pubkey": wrapped_sol_account}

        LAMPORTS_PER_SOL: int = 1_000_000_000
        rent_space_lamports = int(LAMPORTS_PER_SOL / 100)
        lamports = amount + rent_space_lamports if include_rent else rent_space_lamports

        create_params = system_program.CreateAccountWithSeedParams(
            from_pubkey=wallet_pubkey,
            to_pubkey=wrapped_sol_account,
            base=wallet_pubkey,
            seed=seed,
            lamports=lamports,
            space=165,
            owner=TOKEN_PROGRAM_ID,
        )

        result["ixs"].append(system_program.create_account_with_seed(create_params))

        initialize_params = InitializeAccountParams(
            program_id=TOKEN_PROGRAM_ID,
            account=wrapped_sol_account,
            mint=WRAPPED_SOL_MINT,
            owner=wallet_pubkey,
        )

        result["ixs"].append(initialize_account(initialize_params))

        return result["ixs"], result["pubkey"]

    async def deposit(
        self,
        amount: int,
        spot_market_index: int,
        user_token_account: Pubkey,
        sub_account_id: Optional[int] = None,
        reduce_only=False,
        user_initialized=True,
    ) -> TxSigAndSlot:
        """deposits collateral into protocol

        Args:
            amount (int): amount to deposit
            spot_market_index (int):
            user_token_account (Pubkey):
            sub_account_id (int, optional): subaccount to deposit into. Defaults to 0.
            reduce_only (bool, optional): paying back borrow vs depositing new assets. Defaults to False.
            user_initialized (bool, optional): if need to initialize user account too set this to False. Defaults to True.

        Returns:
            TxSigAndSlot: tx sig and slot
        """
        tx_sig_and_slot = await self.send_ixs(
            await self.get_deposit_collateral_ix(
                amount,
                spot_market_index,
                user_token_account,
                sub_account_id,
                reduce_only,
                user_initialized,
            )
        )
        self.last_spot_market_seen_cache[spot_market_index] = tx_sig_and_slot.slot
        return tx_sig_and_slot

    async def get_deposit_collateral_ix(
        self,
        amount: int,
        spot_market_index: int,
        user_token_account: Pubkey,
        sub_account_id: Optional[int] = None,
        reduce_only: Optional[bool] = False,
        user_initialized: Optional[bool] = True,
    ) -> List[Instruction]:
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
        spot_market_account = self.get_spot_market_account(spot_market_index)
        if not spot_market_account:
            raise Exception("Spot market account not found")

        is_sol_market = spot_market_account.mint == WRAPPED_SOL_MINT
        signer_authority = self.wallet.public_key

        create_WSOL_token_account = (
            is_sol_market and user_token_account == signer_authority
        )

        if user_initialized:
            remaining_accounts = self.get_remaining_accounts(
                writable_spot_market_indexes=[spot_market_index],
                user_accounts=[self.get_user_account(sub_account_id)],
            )
        else:
            raise Exception("not implemented...")

        instructions = []

        if create_WSOL_token_account:
            ixs, ata_pubkey = await self.get_wrapped_sol_account_creation_ixs(amount)
            instructions.extend(ixs)
            user_token_account = ata_pubkey

        user_token_account = (
            user_token_account
            if user_token_account is not None
            else self.get_associated_token_account_public_key(spot_market_index)
        )

        spot_market_pk = get_spot_market_public_key(self.program_id, spot_market_index)
        spot_vault_public_key = get_spot_market_vault_public_key(
            self.program_id, spot_market_index
        )
        user_account_public_key = get_user_account_public_key(
            self.program_id, self.authority, sub_account_id
        )
        deposit_ix = self.program.instruction["deposit"](
            spot_market_index,
            amount,
            reduce_only,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "spot_market": spot_market_pk,
                    "spot_market_vault": spot_vault_public_key,
                    "user": user_account_public_key,
                    "user_stats": self.get_user_stats_public_key(),
                    "user_token_account": user_token_account,
                    "authority": self.wallet.public_key,
                    "token_program": TOKEN_PROGRAM_ID,
                },
                remaining_accounts=remaining_accounts,
            ),
        )
        instructions.append(deposit_ix)
        if create_WSOL_token_account:
            close_account_params = CloseAccountParams(
                program_id=TOKEN_PROGRAM_ID,
                account=user_token_account,
                dest=signer_authority,
                owner=signer_authority,
            )
            close_account_ix = close_account(close_account_params)
            instructions.append(close_account_ix)
        return instructions

    async def withdraw(
        self,
        amount: int,
        market_index: int,
        user_token_account: Pubkey,
        reduce_only: bool = False,
        sub_account_id: int = None,
    ) -> TxSigAndSlot:
        """withdraws from drift protocol (can also allow borrowing)

        Args:
            amount (int): amount to withdraw
            market_index (int):
            user_token_account (Pubkey): ata of the account to withdraw to
            reduce_only (bool, optional): if True will only withdraw existing funds else if False will allow taking out borrows. Defaults to False.
            sub_account_id (int, optional): subaccount. Defaults to 0.

        Returns:
            str: tx sig
        """
        tx_sig_and_slot = await self.send_ixs(
            await self.get_withdraw_collateral_ix(
                amount,
                market_index,
                user_token_account,
                reduce_only,
                sub_account_id,
            )
        )
        self.last_spot_market_seen_cache[market_index] = tx_sig_and_slot.slot
        return tx_sig_and_slot

    async def get_withdraw_collateral_ix(
        self,
        amount: int,
        market_index: int,
        user_token_account: Pubkey,
        reduce_only: bool = False,
        sub_account_id: Optional[int] = None,
    ) -> List[Instruction]:
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        spot_market = self.get_spot_market_account(market_index)
        if not spot_market:
            raise Exception("Spot market account not found")

        is_sol_market = spot_market.mint == WRAPPED_SOL_MINT
        signer_authority = self.wallet.public_key

        create_WSOL_token_account = (
            is_sol_market and user_token_account == signer_authority
        )

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)],
            writable_spot_market_indexes=[market_index],
        )
        dc_signer = self.get_signer_public_key()

        instructions = []
        temp_wsol_account_pubkey = None

        if create_WSOL_token_account:
            # Withdraw SOL to main wallet - create temporary WSOL account
            # Pass include_rent=False as rent is not needed for withdrawal destination
            (
                ixs,
                temp_wsol_account_pubkey,
            ) = await self.get_wrapped_sol_account_creation_ixs(amount, False)
            instructions.extend(ixs)
            user_token_account_for_ix = temp_wsol_account_pubkey
        else:
            account_info = await self.connection.get_account_info(user_token_account)
            if not account_info.value:
                create_ata_ix = (
                    self.create_associated_token_account_idempotent_instruction(
                        account=user_token_account,
                        payer=signer_authority,
                        owner=signer_authority,
                        mint=spot_market.mint,
                    )
                )
                instructions.append(create_ata_ix)
            user_token_account_for_ix = user_token_account

        withdraw_ix = self.program.instruction[
            "withdraw"
        ](
            market_index,
            amount,
            reduce_only,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "spot_market": spot_market.pubkey,
                    "spot_market_vault": spot_market.vault,
                    "drift_signer": dc_signer,
                    "user": self.get_user_account_public_key(sub_account_id),
                    "user_stats": self.get_user_stats_public_key(),
                    "user_token_account": user_token_account_for_ix,  # Use correct account
                    "authority": signer_authority,
                    "token_program": TOKEN_PROGRAM_ID,
                },
                remaining_accounts=remaining_accounts,
            ),
        )
        instructions.append(withdraw_ix)

        if create_WSOL_token_account and temp_wsol_account_pubkey:
            close_account_params = CloseAccountParams(
                program_id=TOKEN_PROGRAM_ID,
                account=temp_wsol_account_pubkey,
                dest=signer_authority,
                owner=signer_authority,
            )
            close_account_ix = close_account(close_account_params)
            instructions.append(close_account_ix)

        return instructions

    async def transfer_deposit(
        self,
        amount: int,
        market_index: int,
        from_sub_account_id: int,
        to_sub_account_id: int,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                await self.get_transfer_deposit_ix(
                    amount,
                    market_index,
                    from_sub_account_id,
                    to_sub_account_id,
                )
            ]
        )
        self.last_spot_market_seen_cache[market_index] = tx_sig_and_slot.slot
        return tx_sig_and_slot.tx_sig

    async def get_transfer_deposit_ix(
        self,
        amount: int,
        market_index: int,
        from_sub_account_id: int,
        to_sub_account_id: int,
    ):
        from_user_public_key = self.get_user_account_public_key(from_sub_account_id)
        to_user_public_key = self.get_user_account_public_key(to_sub_account_id)

        if from_sub_account_id not in self.users:
            from_user_account = await self.program.account["User"].fetch(
                from_user_public_key
            )
        else:
            from_user_account = self.get_user_account(from_sub_account_id)

        if to_sub_account_id not in self.users:
            to_user_account = await self.program.account["User"].fetch(
                to_user_public_key
            )
        else:
            to_user_account = self.get_user_account(to_sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_spot_market_indexes=[
                market_index,
            ],
            user_accounts=[from_user_account, to_user_account],
        )

        ix = self.program.instruction["transfer_deposit"](
            market_index,
            amount,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user_stats": self.get_user_stats_public_key(),
                    "from_user": from_user_public_key,
                    "to_user": to_user_public_key,
                    "authority": self.wallet.public_key,
                    "spot_market_vault": self.get_spot_market_account(
                        market_index
                    ).vault,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return ix

    async def place_spot_order(
        self,
        order_params: OrderParams,
        sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                self.get_place_spot_order_ix(order_params, sub_account_id),
            ]
        )
        self.last_spot_market_seen_cache[order_params.market_index] = (
            tx_sig_and_slot.slot
        )
        self.last_spot_market_seen_cache[QUOTE_SPOT_MARKET_INDEX] = tx_sig_and_slot.slot
        return tx_sig_and_slot.tx_sig

    def get_place_spot_order_ix(
        self,
        order_params: OrderParams,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        order_params.set_spot()
        user_account_public_key = self.get_user_account_public_key(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            readable_spot_market_indexes=[
                QUOTE_SPOT_MARKET_INDEX,
                order_params.market_index,
            ],
            user_accounts=[self.get_user_account(sub_account_id)],
        )

        ix = self.program.instruction["place_spot_order"](
            order_params,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_account_public_key,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return ix

    async def place_perp_order(
        self,
        order_params: OrderParams,
        sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                self.get_place_perp_order_ix(order_params, sub_account_id),
            ]
        )
        self.last_perp_market_seen_cache[order_params.market_index] = (
            tx_sig_and_slot.slot
        )
        return tx_sig_and_slot.tx_sig

    def get_place_perp_order_ix(
        self,
        order_params: OrderParams,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        order_params.set_perp()
        user_account_public_key = self.get_user_account_public_key(sub_account_id)
        user_stats_public_key = self.get_user_stats_public_key()
        remaining_accounts = self.get_remaining_accounts(
            readable_perp_market_indexes=[order_params.market_index],
            user_accounts=[self.get_user_account(sub_account_id)],
        )

        if OrderParamsBitFlag.is_update_high_leverage_mode(order_params.bit_flags):
            remaining_accounts.append(
                AccountMeta(
                    pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                    is_writable=True,
                    is_signer=False,
                )
            )

        ix = self.program.instruction["place_perp_order"](
            order_params,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_account_public_key,
                    "userStats": user_stats_public_key,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return ix

    async def place_orders(
        self,
        order_params: List[OrderParams],
        sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                self.get_place_orders_ix(order_params, sub_account_id),
            ]
        )

        for order_param in order_params:
            if is_variant(order_param.market_type, "Perp"):
                self.last_perp_market_seen_cache[order_param.market_index] = (
                    tx_sig_and_slot.slot
                )
            else:
                self.last_spot_market_seen_cache[order_param.market_index] = (
                    tx_sig_and_slot.slot
                )

        return tx_sig_and_slot.tx_sig

    def get_place_orders_ix(
        self,
        order_params: List[OrderParams],
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        user_account_public_key = self.get_user_account_public_key(sub_account_id)
        user_stats_public_key = self.get_user_stats_public_key()

        readable_perp_market_indexes = []
        readable_spot_market_indexes = []
        for order_param in order_params:
            order_param.check_market_type()

            if is_variant(order_param.market_type, "Perp"):
                readable_perp_market_indexes.append(order_param.market_index)
            else:
                if len(readable_spot_market_indexes) == 0:
                    readable_spot_market_indexes.append(QUOTE_SPOT_MARKET_INDEX)

                readable_spot_market_indexes.append(order_param.market_index)

        remaining_accounts = self.get_remaining_accounts(
            readable_perp_market_indexes=readable_perp_market_indexes,
            readable_spot_market_indexes=readable_spot_market_indexes,
            user_accounts=[self.get_user_account(sub_account_id)],
        )

        ix = self.program.instruction["place_orders"](
            order_params,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_account_public_key,
                    "userStats": user_stats_public_key,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return ix

    async def cancel_order(
        self,
        order_id: Optional[int] = None,
        sub_account_id: int = None,
    ) -> Signature:
        """cancel specific order (if order_id=None will be most recent order)

        Args:
            order_id (Optional[int], optional): Defaults to None.
            sub_account_id (int, optional): subaccount id which contains order. Defaults to 0.

        Returns:
            str: tx sig
        """
        return (
            await self.send_ixs(
                self.get_cancel_order_ix(order_id, sub_account_id),
            )
        ).tx_sig

    def get_cancel_order_ix(
        self, order_id: Optional[int] = None, sub_account_id: int = None
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)]
        )

        return self.program.instruction["cancel_order"](
            order_id,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def cancel_order_by_user_id(
        self,
        user_order_id: int,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        return (
            await self.send_ixs(
                self.get_cancel_order_by_user_id_ix(user_order_id, sub_account_id),
            )
        ).tx_sig

    def get_cancel_order_by_user_id_ix(
        self, user_order_id: int, sub_account_id: int = None
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)]
        )

        return self.program.instruction["cancel_order_by_user_id"](
            user_order_id,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def cancel_orders(
        self,
        market_type: MarketType = None,
        market_index: int = None,
        direction: PositionDirection = None,
        sub_account_id: int = None,
    ) -> Signature:
        """cancel all existing orders on the book

        Args:
            market_type (MarketType, optional): only cancel orders for single market, used with market_index
            market_index (int, optional): only cancel orders for single market, used with market_type
            direction: (PositionDirection, optional): only cancel bids or asks
            sub_account_id (int, optional): subaccount id. Defaults to 0.

        Returns:
            Signature: tx sig
        """
        return (
            await self.send_ixs(
                self.get_cancel_orders_ix(
                    market_type, market_index, direction, sub_account_id
                )
            )
        ).tx_sig

    def get_cancel_orders_ix(
        self,
        market_type: MarketType = None,
        market_index: int = None,
        direction: PositionDirection = None,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)]
        )

        return self.program.instruction["cancel_orders"](
            market_type,
            market_index,
            direction,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def cancel_and_place_orders(
        self,
        cancel_params: Tuple[
            Optional[MarketType],
            Optional[int],
            Optional[PositionDirection],
        ],
        place_order_params: List[OrderParams],
        sub_account_id: Optional[int] = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            self.get_cancel_and_place_orders_ix(
                cancel_params, place_order_params, sub_account_id
            ),
        )

        for order_param in place_order_params:
            if is_variant(order_param.market_type, "Perp"):
                self.last_perp_market_seen_cache[order_param.market_index] = (
                    tx_sig_and_slot.slot
                )
            else:
                self.last_spot_market_seen_cache[order_param.market_index] = (
                    tx_sig_and_slot.slot
                )

        return tx_sig_and_slot.tx_sig

    def get_cancel_and_place_orders_ix(
        self,
        cancel_params: Tuple[
            Optional[MarketType],
            Optional[int],
            Optional[PositionDirection],
        ],
        place_order_params: List[OrderParams],
        sub_account_id: Optional[int] = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        market_type, market_index, direction = cancel_params

        cancel_orders_ix = self.get_cancel_orders_ix(
            market_type, market_index, direction, sub_account_id
        )
        place_orders_ix = self.get_place_orders_ix(place_order_params, sub_account_id)
        return [cancel_orders_ix, place_orders_ix]

    async def modify_order(
        self,
        order_id: int,
        modify_order_params: ModifyOrderParams,
        sub_account_id: Optional[int] = None,
    ) -> Signature:
        return (
            await self.send_ixs(
                [
                    self.get_modify_order_ix(
                        order_id, modify_order_params, sub_account_id
                    )
                ],
            )
        ).tx_sig

    def get_modify_order_ix(
        self,
        order_id: int,
        modify_order_params: ModifyOrderParams,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)],
        )

        return self.program.instruction["modify_order"](
            order_id,
            modify_order_params,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def modify_order_by_user_id(
        self,
        user_order_id: int,
        modify_order_params: ModifyOrderParams,
        sub_account_id: int = None,
    ) -> Signature:
        return (
            await self.send_ixs(
                [
                    self.get_modify_order_by_user_id_ix(
                        user_order_id, modify_order_params, sub_account_id
                    )
                ],
            )
        ).tx_sig

    def get_modify_order_by_user_id_ix(
        self,
        user_order_id: int,
        modify_order_params: ModifyOrderParams,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)],
        )

        return self.program.instruction["modify_order_by_user_id"](
            user_order_id,
            modify_order_params,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def place_and_take_perp_order(
        self,
        order_params: OrderParams,
        maker_info: Union[MakerInfo, List[MakerInfo]] = None,
        referrer_info: ReferrerInfo = None,
        sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                self.get_place_and_take_perp_order_ix(
                    order_params, maker_info, referrer_info, sub_account_id
                ),
            ]
        )
        self.last_perp_market_seen_cache[order_params.market_index] = (
            tx_sig_and_slot.slot
        )
        return tx_sig_and_slot.tx_sig

    def get_place_and_take_perp_order_ix(
        self,
        order_params: OrderParams,
        maker_info: Union[MakerInfo, List[MakerInfo]] = None,
        referrer_info: ReferrerInfo = None,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        order_params.set_perp()

        user_account_public_key = self.get_user_account_public_key(sub_account_id)

        maker_infos = (
            maker_info
            if isinstance(maker_info, list)
            else [maker_info]
            if maker_info
            else []
        )

        user_accounts = [self.get_user_account(sub_account_id)]
        for maker_info in maker_infos:
            user_accounts.append(maker_info.maker_user_account)

        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[order_params.market_index],
            user_accounts=user_accounts,
        )

        if OrderParamsBitFlag.is_update_high_leverage_mode(order_params.bit_flags):
            remaining_accounts.append(
                AccountMeta(
                    pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                    is_writable=True,
                    is_signer=False,
                )
            )

        for maker_info in maker_infos:
            remaining_accounts.append(
                AccountMeta(pubkey=maker_info.maker, is_signer=False, is_writable=True)
            )
            remaining_accounts.append(
                AccountMeta(
                    pubkey=maker_info.maker_stats, is_signer=False, is_writable=True
                )
            )

        if referrer_info is not None:
            referrer_is_maker = referrer_info.referrer in [
                maker_info.maker for maker_info in maker_infos
            ]
            if not referrer_is_maker:
                remaining_accounts.append(
                    AccountMeta(
                        pubkey=referrer_info.referrer, is_signer=False, is_writable=True
                    )
                )
                remaining_accounts.append(
                    AccountMeta(
                        pubkey=referrer_info.referrer_stats,
                        is_signer=False,
                        is_writable=True,
                    )
                )

        return self.program.instruction["place_and_take_perp_order"](
            order_params,
            None,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_account_public_key,
                    "user_stats": self.get_user_stats_public_key(),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def place_and_take_spot_order(
        self,
        order_params: OrderParams,
        fulfillment_config: Optional[
            Union[SerumV3FulfillmentConfigAccount, PhoenixV1FulfillmentConfigAccount]
        ] = None,
        maker_info: Union[MakerInfo, List[MakerInfo]] = None,
        referrer_info: ReferrerInfo = None,
        sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                self.get_place_and_take_spot_order_ix(
                    order_params,
                    fulfillment_config,
                    maker_info,
                    referrer_info,
                    sub_account_id,
                ),
            ]
        )
        self.last_spot_market_seen_cache[order_params.market_index] = (
            tx_sig_and_slot.slot
        )
        return tx_sig_and_slot.tx_sig

    def get_place_and_take_spot_order_ix(
        self,
        order_params: OrderParams,
        fulfillment_config: Optional[
            Union[SerumV3FulfillmentConfigAccount, PhoenixV1FulfillmentConfigAccount]
        ] = None,
        maker_info: Union[MakerInfo, List[MakerInfo]] = None,
        referrer_info: ReferrerInfo = None,
        sub_account_id: int = None,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        order_params.set_spot()

        user_account_public_key = self.get_user_account_public_key(sub_account_id)

        user_accounts = [self.get_user_account(sub_account_id)]
        maker_infos = (
            maker_info
            if isinstance(maker_info, list)
            else [maker_info]
            if maker_info
            else []
        )
        for maker_info in maker_infos:
            user_accounts.append(maker_info.maker_user_account)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=user_accounts,
            writable_spot_market_indexes=[
                order_params.market_index,
                QUOTE_SPOT_MARKET_INDEX,
            ],
        )

        for maker_info in maker_infos:
            remaining_accounts.append(
                AccountMeta(pubkey=maker_info.maker, is_signer=False, is_writable=True)
            )
            remaining_accounts.append(
                AccountMeta(
                    pubkey=maker_info.maker_stats, is_signer=False, is_writable=True
                )
            )

        if referrer_info is not None:
            referrer_is_maker = (
                referrer_info.referrer == maker_info.maker if maker_info else False
            )
            if not referrer_is_maker:
                remaining_accounts.append(
                    AccountMeta(
                        pubkey=referrer_info.referrer, is_signer=False, is_writable=True
                    )
                )
                remaining_accounts.append(
                    AccountMeta(
                        pubkey=referrer_info.referrer_stats,
                        is_signer=False,
                        is_writable=True,
                    )
                )

        self.add_spot_fulfillment_accounts(
            order_params.market_index, remaining_accounts, fulfillment_config
        )

        return self.program.instruction["place_and_take_spot_order"](
            order_params,
            fulfillment_config,
            None,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_account_public_key,
                    "user_stats": self.get_user_stats_public_key(),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def add_liquidity(
        self, amount: int, market_index: int, sub_account_id: int = None
    ) -> Signature:
        """mint LP tokens and add liquidity to the DAMM

        Args:
            amount (int): amount of lp tokens to mint
            market_index (int): market you want to lp in
            sub_account_id (int, optional): subaccount id. Defaults to 0.

        Returns:
            Signature: tx sig
        """
        tx_sig_and_slot = await self.send_ixs(
            [self.get_add_liquidity_ix(amount, market_index, sub_account_id)]
        )

        self.last_perp_market_seen_cache[market_index] = tx_sig_and_slot.slot

        return tx_sig_and_slot.tx_sig

    def get_add_liquidity_ix(
        self, amount: int, market_index: int, sub_account_id: int = None
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[market_index],
            user_accounts=[self.get_user_account(sub_account_id)],
        )
        user_account_public_key = get_user_account_public_key(
            self.program_id, self.authority, sub_account_id
        )

        return self.program.instruction["add_perp_lp_shares"](
            amount,
            market_index,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_account_public_key,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def remove_liquidity(
        self, amount: int, market_index: int, sub_account_id: int = None
    ) -> Signature:
        """burns LP tokens and removes liquidity to the DAMM

        Args:
            amount (int): amount of lp tokens to burn
            market_index (int):
            sub_account_id (int, optional): subaccount id. Defaults to 0.

        Returns:
            Signature: tx sig
        """
        return (
            await self.send_ixs(
                [self.get_remove_liquidity_ix(amount, market_index, sub_account_id)]
            )
        ).tx_sig

    def get_remove_liquidity_ix(
        self, amount: int, market_index: int, sub_account_id: int = None
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[market_index],
            user_accounts=[self.get_user_account(sub_account_id)],
        )
        user_account_public_key = self.get_user_account_public_key(sub_account_id)

        return self.program.instruction["remove_perp_lp_shares"](
            amount,
            market_index,
            ctx=Context(
                accounts={
                    "state": get_state_public_key(self.program_id),
                    "user": user_account_public_key,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def settle_lp(
        self,
        settlee_user_account_public_key: Pubkey,
        market_index: int,
    ) -> Signature:
        return (
            await self.send_ixs(
                [
                    await self.get_settle_lp_ix(
                        settlee_user_account_public_key, market_index
                    )
                ],
                signers=[],
            )
        ).tx_sig

    async def get_settle_lp_ix(
        self,
        settlee_user_account_public_key: Pubkey,
        market_index: int,
    ):
        settlee_user_account = await self.program.account["User"].fetch(
            settlee_user_account_public_key
        )

        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[market_index],
            user_accounts=[settlee_user_account],
        )

        return self.program.instruction["settle_lp"](
            market_index,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": settlee_user_account_public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    def decode_signed_msg_order_params_message(
        self, signed_msg_order_params_buf: bytes, is_delegate: bool = False
    ) -> Union[SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage]:
        payload = signed_msg_order_params_buf[8:]
        payload_with_padding = payload + bytes(128)
        if is_delegate:
            return self.program.coder.types.decode(
                "SignedMsgOrderParamsDelegateMessage", payload_with_padding
            )
        else:
            return self.program.coder.types.decode(
                "SignedMsgOrderParamsMessage", payload_with_padding
            )

    def sign_message(self, message: bytes) -> bytes:
        """Sign a message with the wallet keypair.

        Args:
            message: The message to sign

        Returns:
            The signature
        """

        return self.wallet.payer.sign_message(message).to_bytes()

    def encode_signed_msg_order_params_message(
        self,
        order_params_message: Union[
            dict, SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage
        ],
        delegate_signer: bool = False,
    ) -> bytes:
        """Borsh encode signedMsg order params message

        Args:
            order_params_message: The order params message to encode
            delegate_signer: Whether to use delegate message format

        Returns:
            The encoded buffer
        """

        anchor_ix_name = (
            "global:SignedMsgOrderParamsMessage"
            if not delegate_signer
            else "global:SignedMsgOrderParamsDelegateMessage"
        )
        prefix = bytes.fromhex(sha256(anchor_ix_name.encode()).hexdigest()[:16])

        # Convert Pubkey to bytes if it's a delegate message
        if delegate_signer and isinstance(
            order_params_message, SignedMsgOrderParamsDelegateMessage
        ):
            taker_pubkey_bytes = bytes(order_params_message.taker_pubkey)
            order_params_message = SignedMsgOrderParamsDelegateMessage(
                signed_msg_order_params=order_params_message.signed_msg_order_params,
                slot=order_params_message.slot,
                uuid=order_params_message.uuid,
                taker_pubkey=list(taker_pubkey_bytes),
                take_profit_order_params=order_params_message.take_profit_order_params,
                stop_loss_order_params=order_params_message.stop_loss_order_params,
            )

        encoded = self.program.coder.types.encode(
            "SignedMsgOrderParamsDelegateMessage"
            if delegate_signer
            else "SignedMsgOrderParamsMessage",
            order_params_message,
        )

        buf = prefix + encoded
        return buf

    def sign_signed_msg_order_params_message(
        self,
        order_params_message: Union[
            dict, SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage
        ],
        delegate_signer: bool = False,
    ) -> SignedMsgOrderParams:
        """Sign a SignedMsgOrderParamsMessage

        Args:
            order_params_message: The order params message to sign
            delegate_signer: Whether to use delegate message format

        Returns:
            The signed order params
        """
        borsh_buf = self.encode_signed_msg_order_params_message(
            order_params_message, delegate_signer
        )
        order_params = borsh_buf.hex().encode()

        return SignedMsgOrderParams(
            order_params=order_params, signature=self.sign_message(order_params)
        )

    async def place_signed_msg_taker_order(
        self,
        signed_msg_order_params: SignedMsgOrderParams,
        market_index: int,
        taker_info: dict,
        preceding_ixs: list[Instruction] = [],
        override_ix_count: Optional[int] = None,
        include_high_leverage_mode_config: Optional[bool] = False,
    ) -> TxSigAndSlot:
        ixs = await self.get_place_signed_msg_taker_perp_order_ixs(
            signed_msg_order_params,
            market_index,
            taker_info,
            None,
            preceding_ixs,
            override_ix_count,
            include_high_leverage_mode_config,
        )
        return await self.send_ixs(ixs)

    async def get_place_signed_msg_taker_perp_order_ixs(
        self,
        signed_msg_order_params: Union[dict, SignedMsgOrderParams],
        market_index: int,
        taker_info: dict,
        authority: Optional[Pubkey] = None,
        preceding_ixs: list[Instruction] = [],
        override_ix_count: Optional[int] = None,
        include_high_leverage_mode_config: Optional[bool] = False,
    ):
        if not authority and not taker_info["taker_user_account"]:
            raise Exception("authority or taker_user_account must be provided")

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[taker_info["taker_user_account"]],
            readable_perp_market_indexes=[market_index],
        )

        if include_high_leverage_mode_config:
            remaining_accounts.append(
                AccountMeta(
                    pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                    is_writable=True,
                    is_signer=False,
                )
            )
        authority_to_use = authority or taker_info["taker_user_account"].authority

        print(f"Signed msg order params: {signed_msg_order_params}")
        if isinstance(signed_msg_order_params, SignedMsgOrderParams):
            signed_msg_order_params = {
                "signature": signed_msg_order_params.signature,
                "order_params": signed_msg_order_params.order_params,
            }

        message_length_buffer = int.to_bytes(
            len(signed_msg_order_params["order_params"]), 2, "little"
        )

        signed_msg_ix_data = b"".join(
            [
                signed_msg_order_params["signature"],
                bytes(authority_to_use),
                message_length_buffer,
                signed_msg_order_params["order_params"],
            ]
        )

        signed_msg_order_params_signature_ix = create_minimal_ed25519_verify_ix(
            override_ix_count or len(preceding_ixs) + 1,
            12,
            signed_msg_ix_data,
            0,
        )

        is_delegate_signer = False
        if (
            taker_info.get("signing_authority")
            and taker_info.get("taker_user_account")
            and taker_info["taker_user_account"].delegate
            and taker_info["signing_authority"]
            == taker_info["taker_user_account"].delegate
        ):
            is_delegate_signer = True

        sysvar_pubkey = Pubkey.from_string(
            "Sysvar1nstructions1111111111111111111111111"
        )

        place_taker_signed_msg_perp_order_ix = self.program.instruction[
            "place_signed_msg_taker_order"
        ](
            signed_msg_ix_data,
            is_delegate_signer,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": taker_info["taker"],
                    "user_stats": taker_info["taker_stats"],
                    "signed_msg_user_orders": get_signed_msg_user_account_public_key(
                        self.program_id,
                        taker_info["taker_user_account"].authority,
                    ),
                    "authority": self.wallet.public_key,
                    "ix_sysvar": sysvar_pubkey,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return [
            signed_msg_order_params_signature_ix,
            place_taker_signed_msg_perp_order_ix,
        ]

    async def place_and_make_signed_msg_perp_order(
        self,
        signed_msg_order_params: SignedMsgOrderParams,
        signed_msg_order_uuid: bytes,
        taker_info: dict,
        order_params: OrderParams,
    ):
        ixs = await self.get_place_and_make_signed_msg_perp_order_ixs(
            signed_msg_order_params,
            signed_msg_order_uuid,
            taker_info,
            order_params,
        )
        lookup_tables = await self.fetch_market_lookup_table_accounts()
        result = await self.send_ixs(ixs, lookup_tables=lookup_tables)
        self.last_perp_market_seen_cache[order_params.market_index] = result.slot
        return result.tx_sig

    async def get_place_and_make_signed_msg_perp_order_ixs(
        self,
        signed_msg_order_params: SignedMsgOrderParams,
        signed_msg_order_uuid: bytes,
        taker_info: dict,
        order_params: OrderParams,
        referrer_info: Optional[ReferrerInfo] = None,
        sub_account_id: Optional[int] = None,
        preceding_ixs: list[Instruction] = [],
        override_ix_count: Optional[int] = None,
        include_high_leverage_mode_config: Optional[bool] = False,
    ) -> list[Instruction]:
        (
            signed_msg_order_signature_ix,
            place_taker_signed_msg_perp_order_ix,
        ) = await self.get_place_signed_msg_taker_perp_order_ixs(
            signed_msg_order_params,
            order_params.market_index,
            taker_info,
            None,
            preceding_ixs,
            override_ix_count,
        )

        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
        user_stats_public_key = self.get_user_stats_public_key()
        user = self.get_user_account_public_key(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[
                self.get_user_account(sub_account_id),
                taker_info["taker_user_account"],
            ],
            writable_perp_market_indexes=[order_params.market_index],
        )

        if include_high_leverage_mode_config:
            remaining_accounts.append(
                AccountMeta(
                    pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                    is_writable=True,
                    is_signer=False,
                )
            )

        if referrer_info:
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer, is_writable=True, is_signer=False
                )
            )
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer_stats,
                    is_writable=True,
                    is_signer=False,
                )
            )

        place_and_make_ix = self.program.instruction[
            "place_and_make_signed_msg_perp_order"
        ](
            order_params,
            signed_msg_order_uuid,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user,
                    "user_stats": user_stats_public_key,
                    "taker": taker_info["taker"],
                    "taker_stats": taker_info["taker_stats"],
                    "authority": self.wallet.public_key,
                    "taker_signed_msg_user_orders": get_signed_msg_user_account_public_key(
                        self.program_id, taker_info["taker_user_account"].authority
                    ),
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return [
            signed_msg_order_signature_ix,
            place_taker_signed_msg_perp_order_ix,
            place_and_make_ix,
        ]

    def get_spot_position(
        self,
        market_index: int,
        sub_account_id: int = None,
    ) -> Optional[SpotPosition]:
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        return self.get_user(sub_account_id).get_spot_position(market_index)

    def get_perp_position(
        self,
        market_index: int,
        sub_account_id: int = None,
    ) -> Optional[PerpPosition]:
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
        return self.get_user(sub_account_id).get_perp_position(market_index)

    async def liquidate_spot(
        self,
        user_authority: Pubkey,
        asset_market_index: int,
        liability_market_index: int,
        max_liability_transfer: int,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                await self.get_liquidate_spot_ix(
                    user_authority,
                    asset_market_index,
                    liability_market_index,
                    max_liability_transfer,
                    user_sub_account_id,
                    liq_sub_account_id,
                )
            ]
        )
        self.last_spot_market_seen_cache[asset_market_index] = tx_sig_and_slot.slot
        self.last_spot_market_seen_cache[liability_market_index] = tx_sig_and_slot.slot
        return tx_sig_and_slot.tx_sig

    async def get_liquidate_spot_ix(
        self,
        user_authority: Pubkey,
        asset_market_index: int,
        liability_market_index: int,
        max_liability_transfer: int,
        limit_price: int = None,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        user_pk = get_user_account_public_key(
            self.program_id, user_authority, sub_account_id=user_sub_account_id
        )
        user_stats_pk = get_user_stats_account_public_key(
            self.program_id,
            user_authority,
        )

        liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
        liq_pk = self.get_user_account_public_key(liq_sub_account_id)
        liq_stats_pk = self.get_user_stats_public_key()

        user_account = await self.program.account["User"].fetch(user_pk)
        liq_user_account = self.get_user_account(liq_sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_spot_market_indexes=[liability_market_index, asset_market_index],
            user_accounts=[user_account, liq_user_account],
        )

        return self.program.instruction["liquidate_spot"](
            asset_market_index,
            liability_market_index,
            max_liability_transfer,
            limit_price,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                    "user": user_pk,
                    "user_stats": user_stats_pk,
                    "liquidator": liq_pk,
                    "liquidator_stats": liq_stats_pk,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def liquidate_perp(
        self,
        user_authority: Pubkey,
        market_index: int,
        max_base_asset_amount: int,
        limit_price: Optional[int] = None,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            [
                await self.get_liquidate_perp_ix(
                    user_authority,
                    market_index,
                    max_base_asset_amount,
                    limit_price,
                    user_sub_account_id,
                    liq_sub_account_id,
                )
            ]
        )
        self.last_perp_market_seen_cache[market_index] = tx_sig_and_slot.slot
        return tx_sig_and_slot.tx_sig

    async def get_liquidate_perp_ix(
        self,
        user_authority: Pubkey,
        market_index: int,
        max_base_asset_amount: int,
        limit_price: Optional[int] = None,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        user_pk = get_user_account_public_key(
            self.program_id, user_authority, user_sub_account_id
        )
        user_stats_pk = get_user_stats_account_public_key(
            self.program_id,
            user_authority,
        )

        liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
        liq_pk = self.get_user_account_public_key(liq_sub_account_id)
        liq_stats_pk = self.get_user_stats_public_key()

        user_account = await self.program.account["User"].fetch(user_pk)
        liq_user_account = self.get_user_account(liq_sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[market_index],
            user_accounts=[user_account, liq_user_account],
        )

        return self.program.instruction["liquidate_perp"](
            market_index,
            max_base_asset_amount,
            limit_price,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                    "user": user_pk,
                    "user_stats": user_stats_pk,
                    "liquidator": liq_pk,
                    "liquidator_stats": liq_stats_pk,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def liquidate_perp_pnl_for_deposit(
        self,
        user_authority: Pubkey,
        perp_market_index: int,
        spot_market_index: int,
        max_pnl_transfer: int,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        tx_sig_and_slot = await self.send_ixs(
            await self.get_liquidate_perp_pnl_for_deposit_ix(
                user_authority,
                perp_market_index,
                spot_market_index,
                max_pnl_transfer,
                user_sub_account_id,
                liq_sub_account_id,
            )
        )
        self.last_spot_market_seen_cache[spot_market_index] = tx_sig_and_slot.slot
        self.last_perp_market_seen_cache[perp_market_index] = tx_sig_and_slot.slot
        return tx_sig_and_slot.tx_sig

    async def get_liquidate_perp_pnl_for_deposit_ix(
        self,
        user_authority: Pubkey,
        perp_market_index: int,
        spot_market_index: int,
        max_pnl_transfer: int,
        limit_price: int = None,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        user_pk = get_user_account_public_key(
            self.program_id, user_authority, user_sub_account_id
        )
        user_stats_pk = get_user_stats_account_public_key(
            self.program_id,
            user_authority,
        )

        liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
        liq_pk = self.get_user_account_public_key(liq_sub_account_id)
        liq_stats_pk = self.get_user_stats_public_key()

        user_account = await self.program.account["User"].fetch(user_pk)
        liq_user_account = self.get_user_account(liq_sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[perp_market_index],
            writable_spot_market_indexes=[spot_market_index],
            user_accounts=[user_account, liq_user_account],
        )

        result = self.program.instruction["liquidate_perp_pnl_for_deposit"](
            perp_market_index,
            spot_market_index,
            max_pnl_transfer,
            limit_price,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                    "user": user_pk,
                    "user_stats": user_stats_pk,
                    "liquidator": liq_pk,
                    "liquidator_stats": liq_stats_pk,
                },
                remaining_accounts=remaining_accounts,
            ),
        )
        return result

    async def settle_pnl(
        self,
        settlee_user_account_public_key: Pubkey,
        settlee_user_account: UserAccount,
        market_index: int,
    ):
        lookup_tables = await self.fetch_market_lookup_table_accounts()
        return (
            await self.send_ixs(
                self.get_settle_pnl_ix(
                    settlee_user_account_public_key, settlee_user_account, market_index
                ),
                lookup_tables=lookup_tables,
            )
        ).tx_sig

    def get_settle_pnl_ix(
        self,
        settlee_user_public_key: Pubkey,
        settlee_user_account: UserAccount,
        market_index: int,
    ):
        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[market_index],
            writable_spot_market_indexes=[QUOTE_SPOT_MARKET_INDEX],
            user_accounts=[settlee_user_account],
        )

        instruction = self.program.instruction["settle_pnl"](
            market_index,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                    "user": settlee_user_public_key,
                    "spot_market_vault": get_spot_market_vault_public_key(
                        self.program_id, QUOTE_SPOT_MARKET_INDEX
                    ),
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return instruction

    def get_settle_pnl_ixs(
        self, users: dict[Pubkey, UserAccount], market_indexes: list[int]
    ) -> list[Instruction]:
        ixs: list[Instruction] = []
        for pubkey, account in users.items():
            for market_index in market_indexes:
                ix = self.get_settle_pnl_ix(pubkey, account, market_index)
                ixs.append(ix)

        return ixs

    async def resolve_spot_bankruptcy(
        self,
        user_authority: Pubkey,
        spot_market_index: int,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        return (
            await self.send_ixs(
                [
                    await self.get_resolve_spot_bankruptcy_ix(
                        user_authority,
                        spot_market_index,
                        user_sub_account_id,
                        liq_sub_account_id,
                    )
                ]
            )
        ).tx_sig

    async def get_resolve_spot_bankruptcy_ix(
        self,
        user_authority: Pubkey,
        spot_market_index: int,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        user_pk = get_user_account_public_key(
            self.program_id, user_authority, user_sub_account_id
        )
        user_stats_pk = get_user_stats_account_public_key(
            self.program_id,
            user_authority,
        )

        liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
        liq_pk = self.get_user_account_public_key(liq_sub_account_id)
        liq_stats_pk = self.get_user_stats_public_key()

        user_account = await self.program.account["User"].fetch(user_pk)
        liq_user_account = self.get_user_account(liq_sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_spot_market_indexes=[spot_market_index],
            user_accounts=[user_account, liq_user_account],
        )

        if_vault = get_insurance_fund_vault_public_key(
            self.program_id, spot_market_index
        )
        spot_vault = get_spot_market_vault_public_key(
            self.program_id, spot_market_index
        )
        dc_signer = self.get_signer_public_key(self.program_id)

        return self.program.instruction["resolve_spot_bankruptcy"](
            spot_market_index,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                    "user": user_pk,
                    "user_stats": user_stats_pk,
                    "liquidator": liq_pk,
                    "liquidator_stats": liq_stats_pk,
                    "spot_market_vault": spot_vault,
                    "insurance_fund_vault": if_vault,
                    "drift_signer": dc_signer,
                    "token_program": TOKEN_PROGRAM_ID,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def resolve_perp_bankruptcy(
        self,
        user_authority: Pubkey,
        market_index: int,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        return (
            await self.send_ixs(
                [
                    await self.get_resolve_perp_bankruptcy_ix(
                        user_authority,
                        market_index,
                        user_sub_account_id,
                        liq_sub_account_id,
                    )
                ]
            )
        ).tx_sig

    async def get_resolve_perp_bankruptcy_ix(
        self,
        user_authority: Pubkey,
        market_index: int,
        user_sub_account_id: int = 0,
        liq_sub_account_id: int = None,
    ):
        user_pk = get_user_account_public_key(
            self.program_id, user_authority, user_sub_account_id
        )
        user_stats_pk = get_user_stats_account_public_key(
            self.program_id,
            user_authority,
        )

        liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
        liq_pk = self.get_user_account_public_key(liq_sub_account_id)
        liq_stats_pk = self.get_user_stats_public_key()

        user_account = await self.program.account["User"].fetch(user_pk)
        liq_user_account = self.get_user_account(liq_sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            writable_perp_market_indexes=[market_index],
            user_accounts=[user_account, liq_user_account],
        )

        if_vault = get_insurance_fund_vault_public_key(self.program_id, market_index)
        spot_vault = get_spot_market_vault_public_key(self.program_id, market_index)
        dc_signer = self.get_signer_public_key(self.program_id)

        return self.program.instruction["resolve_perp_bankruptcy"](
            QUOTE_SPOT_MARKET_INDEX,
            market_index,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                    "user": user_pk,
                    "user_stats": user_stats_pk,
                    "liquidator": liq_pk,
                    "liquidator_stats": liq_stats_pk,
                    "spot_market_vault": spot_vault,
                    "insurance_fund_vault": if_vault,
                    "drift_signer": dc_signer,
                    "token_program": TOKEN_PROGRAM_ID,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def settle_expired_market(
        self,
        market_index: int,
    ):
        return (
            await self.send_ixs(
                [
                    await self.get_settle_expired_market_ix(
                        market_index,
                    ),
                ]
            )
        ).tx_sig

    async def get_settle_expired_market_ix(
        self,
        market_index: int,
    ):
        market = await get_perp_market_account(self.program, market_index)

        market_account_infos = [
            AccountMeta(
                pubkey=market.pubkey,
                is_writable=True,
                is_signer=False,
            )
        ]

        oracle_account_infos = [
            AccountMeta(
                pubkey=market.amm.oracle,
                is_writable=False,
                is_signer=False,
            )
        ]

        spot_pk = get_spot_market_public_key(self.program_id, QUOTE_SPOT_MARKET_INDEX)
        spot_account_infos = [
            AccountMeta(
                pubkey=spot_pk,
                is_writable=True,
                is_signer=False,
            )
        ]

        remaining_accounts = (
            oracle_account_infos + spot_account_infos + market_account_infos
        )

        return self.program.instruction["settle_expired_market"](
            market_index,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def request_remove_insurance_fund_stake(
        self, spot_market_index: int, amount: int
    ):
        return (
            await self.send_ixs(
                self.get_request_remove_insurance_fund_stake_ix(
                    spot_market_index, amount
                )
            )
        ).tx_sig

    def get_request_remove_insurance_fund_stake_ix(
        self,
        spot_market_index: int,
        amount: int,
    ):
        ra = self.get_remaining_accounts(
            writable_spot_market_indexes=[spot_market_index],
        )

        return self.program.instruction["request_remove_insurance_fund_stake"](
            spot_market_index,
            amount,
            ctx=Context(
                accounts={
                    "spot_market": get_spot_market_public_key(
                        self.program_id, spot_market_index
                    ),
                    "insurance_fund_stake": get_insurance_fund_stake_public_key(
                        self.program_id, self.authority, spot_market_index
                    ),
                    "user_stats": get_user_stats_account_public_key(
                        self.program_id, self.authority
                    ),
                    "authority": self.wallet.public_key,
                    "insurance_fund_vault": get_insurance_fund_vault_public_key(
                        self.program_id, spot_market_index
                    ),
                },
                remaining_accounts=ra,
            ),
        )

    async def cancel_request_remove_insurance_fund_stake(self, spot_market_index: int):
        return (
            await self.send_ixs(
                self.get_cancel_request_remove_insurance_fund_stake_ix(
                    spot_market_index
                )
            )
        ).tx_sig

    def get_cancel_request_remove_insurance_fund_stake_ix(
        self, spot_market_index: int, user_token_account: Pubkey = None
    ):
        ra = self.get_remaining_accounts(
            writable_spot_market_indexes=[spot_market_index]
        )

        return self.program.instruction["cancel_request_remove_insurance_fund_stake"](
            spot_market_index,
            ctx=Context(
                accounts={
                    "state": get_state_public_key(self.program_id),
                    "spot_market": get_spot_market_public_key(
                        self.program_id, spot_market_index
                    ),
                    "insurance_fund_stake": get_insurance_fund_stake_public_key(
                        self.program_id, self.authority, spot_market_index
                    ),
                    "user_stats": get_user_stats_account_public_key(
                        self.program_id, self.authority
                    ),
                    "authority": self.wallet.public_key,
                    "insurance_fund_vault": get_insurance_fund_vault_public_key(
                        self.program_id, spot_market_index
                    ),
                },
                remaining_accounts=ra,
            ),
        )

    async def remove_insurance_fund_stake(
        self, spot_market_index: int, user_token_account: Pubkey = None
    ):
        return (
            await self.send_ixs(
                self.get_remove_insurance_fund_stake_ix(
                    spot_market_index, user_token_account
                )
            )
        ).tx_sig

    def get_remove_insurance_fund_stake_ix(
        self, spot_market_index: int, user_token_account: Pubkey = None
    ):
        ra = self.get_remaining_accounts(
            writable_spot_market_indexes=[spot_market_index],
        )

        user_token_account = (
            user_token_account
            if user_token_account is not None
            else self.get_associated_token_account_public_key(spot_market_index)
        )

        return self.program.instruction["remove_insurance_fund_stake"](
            spot_market_index,
            ctx=Context(
                accounts={
                    "state": get_state_public_key(self.program_id),
                    "spot_market": get_spot_market_public_key(
                        self.program_id, spot_market_index
                    ),
                    "insurance_fund_stake": get_insurance_fund_stake_public_key(
                        self.program_id, self.authority, spot_market_index
                    ),
                    "user_stats": get_user_stats_account_public_key(
                        self.program_id, self.authority
                    ),
                    "authority": self.wallet.public_key,
                    "insurance_fund_vault": get_insurance_fund_vault_public_key(
                        self.program_id, spot_market_index
                    ),
                    "drift_signer": self.get_signer_public_key(self.program_id),
                    "user_token_account": user_token_account,
                    "token_program": TOKEN_PROGRAM_ID,
                },
                remaining_accounts=ra,
            ),
        )

    async def add_insurance_fund_stake(
        self, spot_market_index: int, amount: int, user_token_account: Pubkey = None
    ):
        return (
            await self.send_ixs(
                self.get_add_insurance_fund_stake_ix(
                    spot_market_index, amount, user_token_account
                )
            )
        ).tx_sig

    def get_add_insurance_fund_stake_ix(
        self, spot_market_index: int, amount: int, user_token_account: Pubkey = None
    ):
        remaining_accounts = self.get_remaining_accounts(
            writable_spot_market_indexes=[spot_market_index],
        )

        user_token_account = (
            user_token_account
            if user_token_account is not None
            else self.get_associated_token_account_public_key(spot_market_index)
        )

        return self.program.instruction["add_insurance_fund_stake"](
            spot_market_index,
            amount,
            ctx=Context(
                accounts={
                    "state": get_state_public_key(self.program_id),
                    "spot_market": get_spot_market_public_key(
                        self.program_id, spot_market_index
                    ),
                    "insurance_fund_stake": get_insurance_fund_stake_public_key(
                        self.program_id, self.authority, spot_market_index
                    ),
                    "user_stats": get_user_stats_account_public_key(
                        self.program_id, self.authority
                    ),
                    "authority": self.wallet.public_key,
                    "spot_market_vault": get_spot_market_vault_public_key(
                        self.program_id, spot_market_index
                    ),
                    "insurance_fund_vault": get_insurance_fund_vault_public_key(
                        self.program_id, spot_market_index
                    ),
                    "drift_signer": self.get_signer_public_key(self.program_id),
                    "user_token_account": user_token_account,
                    "token_program": TOKEN_PROGRAM_ID,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def initialize_insurance_fund_stake(
        self,
        spot_market_index: int,
    ):
        return (
            await self.send_ixs(
                self.get_initialize_insurance_fund_stake_ix(spot_market_index)
            )
        ).tx_sig

    def get_initialize_insurance_fund_stake_ix(
        self,
        spot_market_index: int,
    ):
        return self.program.instruction["initialize_insurance_fund_stake"](
            spot_market_index,
            ctx=Context(
                accounts={
                    "spot_market": get_spot_market_public_key(
                        self.program_id, spot_market_index
                    ),
                    "insurance_fund_stake": get_insurance_fund_stake_public_key(
                        self.program_id, self.authority, spot_market_index
                    ),
                    "user_stats": get_user_stats_account_public_key(
                        self.program_id, self.authority
                    ),
                    "state": get_state_public_key(self.program_id),
                    "authority": self.wallet.public_key,
                    "payer": self.wallet.public_key,
                    "rent": RENT,
                    "system_program": ID,
                }
            ),
        )

    async def fill_perp_order(
        self,
        user_account_pubkey: Pubkey,
        user_account: UserAccount,
        order: Order,
        maker_info: Optional[Union[MakerInfo, list[MakerInfo]]],
        referrer_info: Optional[ReferrerInfo],
    ):
        return (
            await self.send_ixs(
                [
                    await self.get_fill_perp_order_ix(
                        user_account_pubkey,
                        user_account,
                        order,
                        maker_info,
                        referrer_info,
                    )
                ]
            )
        ).tx_sig

    async def get_fill_perp_order_ix(
        self,
        user_account_pubkey: Pubkey,
        user_account: UserAccount,
        order: Order,
        maker_info: Optional[Union[MakerInfo, list[MakerInfo]]],
        referrer_info: Optional[ReferrerInfo],
    ) -> Instruction:
        user_stats_pubkey = get_user_stats_account_public_key(
            self.program.program_id, user_account.authority
        )

        filler_pubkey = self.get_user_account_public_key()
        filler_stats_pubkey = self.get_user_stats_public_key()

        market_index = (
            order.market_index
            if order
            else next(
                (
                    order.market_index
                    for order in user_account.orders
                    if order.order_id == user_account.next_order_id - 1
                ),
                None,
            )
        )

        maker_info = (
            maker_info
            if isinstance(maker_info, list)
            else [maker_info]
            if maker_info
            else []
        )

        user_accounts = [user_account]
        for maker in maker_info:
            user_accounts.append(maker.maker_user_account)

        remaining_accounts = self.get_remaining_accounts(user_accounts, [market_index])

        for maker in maker_info:
            remaining_accounts.append(
                AccountMeta(pubkey=maker.maker, is_writable=True, is_signer=False)
            )
            remaining_accounts.append(
                AccountMeta(pubkey=maker.maker_stats, is_writable=True, is_signer=False)
            )

        if referrer_info:
            referrer_is_maker = any(
                maker.maker == referrer_info.referrer for maker in maker_info
            )
            if not referrer_is_maker:
                remaining_accounts.append(
                    AccountMeta(
                        pubkey=referrer_info.referrer, is_writable=True, is_signer=False
                    )
                )
                remaining_accounts.append(
                    AccountMeta(
                        pubkey=referrer_info.referrer_stats,
                        is_writable=True,
                        is_signer=False,
                    )
                )

        order_id = order.order_id
        return self.program.instruction["fill_perp_order"](
            order_id,
            None,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "filler": filler_pubkey,
                    "filler_stats": filler_stats_pubkey,
                    "user": user_account_pubkey,
                    "user_stats": user_stats_pubkey,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    def get_revert_fill_ix(self):
        filler_pubkey = self.get_user_account_public_key()
        filler_stats_pubkey = self.get_user_stats_public_key()

        return self.program.instruction["revert_fill"](
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "filler": filler_pubkey,
                    "filler_stats": filler_stats_pubkey,
                    "authority": self.wallet.public_key,
                }
            )
        )

    def get_trigger_order_ix(
        self,
        user_account_pubkey: Pubkey,
        user_account: UserAccount,
        order: Order,
        filler_pubkey: Optional[Pubkey] = None,
    ):
        filler = filler_pubkey or self.get_user_account_public_key()

        if is_variant(order.market_type, "Perp"):
            remaining_accounts = self.get_remaining_accounts(
                user_accounts=[user_account],
                writable_perp_market_indexes=[order.market_index],
            )
        else:
            remaining_accounts = self.get_remaining_accounts(
                user_accounts=[user_account],
                writable_spot_market_indexes=[
                    order.market_index,
                    QUOTE_SPOT_MARKET_INDEX,
                ],
            )

        return self.program.instruction["trigger_order"](
            order.order_id,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "filler": filler,
                    "user": user_account_pubkey,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def force_cancel_orders(
        self,
        user_account_pubkey: Pubkey,
        user_account: UserAccount,
        filler_pubkey: Optional[Pubkey] = None,
    ) -> Signature:
        tx_sig_and_slot = await self.send_ixs(
            self.get_force_cancel_orders_ix(
                user_account_pubkey, user_account, filler_pubkey
            )
        )

        return tx_sig_and_slot.tx_sig

    def get_force_cancel_orders_ix(
        self,
        user_account_pubkey: Pubkey,
        user_account: UserAccount,
        filler_pubkey: Optional[Pubkey] = None,
    ):
        filler = filler_pubkey or self.get_user_account_public_key()

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[user_account],
            writable_spot_market_indexes=[QUOTE_SPOT_MARKET_INDEX],
        )

        return self.program.instruction["force_cancel_orders"](
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "filler": filler,
                    "user": user_account_pubkey,
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            )
        )

    @deprecated
    async def open_position(
        self,
        direction: PositionDirection,
        amount: int,
        market_index: int,
        sub_account_id: int = None,
        limit_price: int = 0,
        ioc: bool = False,
    ):
        return (
            await self.send_ixs(
                self.get_open_position_ix(
                    direction,
                    amount,
                    market_index,
                    sub_account_id,
                    limit_price,
                    ioc,
                ),
            )
        ).tx_sig

    @deprecated
    def get_open_position_ix(
        self,
        direction: PositionDirection,
        amount: int,
        market_index: int,
        sub_account_id: int = None,
        limit_price: int = 0,
        ioc: bool = False,
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        order_params = OrderParams(
            order_type=OrderType.Market(),
            direction=direction,
            market_index=market_index,
            base_asset_amount=amount,
            price=limit_price,
        )

        ix = self.get_place_and_take_perp_order_ix(
            order_params, sub_account_id=sub_account_id
        )
        return ix

    @deprecated
    async def close_position(
        self, market_index: int, limit_price: int = 0, sub_account_id: int = None
    ):
        return (
            await self.send_ixs(
                self.get_close_position_ix(
                    market_index, limit_price, sub_account_id=sub_account_id
                )
            )
        ).tx_sig

    @deprecated
    def get_close_position_ix(
        self, market_index: int, limit_price: int = 0, sub_account_id: int = None
    ):
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        position = self.get_perp_position(market_index, sub_account_id)
        if position is None or position.base_asset_amount == 0:
            print("=> user has no position to close...")
            return

        order_params = OrderParams(
            order_type=OrderType.Market(),
            market_index=market_index,
            base_asset_amount=abs(int(position.base_asset_amount)),
            direction=(
                PositionDirection.Long()
                if position.base_asset_amount < 0
                else PositionDirection.Short()
            ),
            price=limit_price,
            reduce_only=True,
        )

        ix = self.get_place_and_take_perp_order_ix(
            order_params, sub_account_id=sub_account_id
        )
        return ix

    async def update_amm(self, market_indexs: list[int]):
        return (await self.send_ixs(self.get_update_amm_ix(market_indexs))).tx_sig

    def get_update_amm_ix(
        self,
        market_indexs: list[int],
    ):
        n = len(market_indexs)
        for _ in range(5 - n):
            market_indexs.append(100)

        market_infos = []
        oracle_infos = []
        for idx in market_indexs:
            if idx != 100:
                market = self.get_perp_market_account(idx)
                market_infos.append(
                    AccountMeta(
                        pubkey=market.pubkey,
                        is_signer=False,
                        is_writable=True,
                    )
                )
                oracle_infos.append(
                    AccountMeta(
                        pubkey=market.amm.oracle, is_signer=False, is_writable=False
                    )
                )

        remaining_accounts = oracle_infos + market_infos

        return self.program.instruction["update_amms"](
            market_indexs,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def settle_revenue_to_insurance_fund(self, spot_market_index: int):
        return await self.program.rpc["settle_revenue_to_insurance_fund"](
            spot_market_index,
            ctx=Context(
                accounts={
                    "state": get_state_public_key(self.program_id),
                    "spot_market": get_spot_market_public_key(
                        self.program_id, spot_market_index
                    ),
                    "spot_market_vault": get_spot_market_vault_public_key(
                        self.program_id, spot_market_index
                    ),
                    "drift_signer": self.get_signer_public_key(self.program_id),
                    "insurance_fund_vault": get_insurance_fund_vault_public_key(
                        self.program_id,
                        spot_market_index,
                    ),
                    "token_program": TOKEN_PROGRAM_ID,
                }
            ),
        )

    def create_associated_token_account_idempotent_instruction(
        self, account: Pubkey, payer: Pubkey, owner: Pubkey, mint: Pubkey
    ):
        return Instruction(
            accounts=[
                AccountMeta(pubkey=payer, is_signer=True, is_writable=True),
                AccountMeta(pubkey=account, is_signer=False, is_writable=True),
                AccountMeta(pubkey=owner, is_signer=False, is_writable=False),
                AccountMeta(pubkey=mint, is_signer=False, is_writable=False),
                AccountMeta(pubkey=SYS_PROGRAM_ID, is_signer=False, is_writable=False),
                AccountMeta(
                    pubkey=TOKEN_PROGRAM_ID, is_signer=False, is_writable=False
                ),
                AccountMeta(pubkey=RENT, is_signer=False, is_writable=False),
            ],
            program_id=ASSOCIATED_TOKEN_PROGRAM_ID,
            data=bytes([0x01]),
        )

    async def get_swap_flash_loan_ix(
        self,
        out_market_index: int,
        in_market_index: int,
        amount_in: int,
        in_ata: Pubkey,
        out_ata: Pubkey,
        limit_price: Optional[int] = 0,
        reduce_only: Optional[SwapReduceOnly] = None,
        user_account_public_key: Optional[Pubkey] = None,
    ):
        user_public_key_to_use = (
            user_account_public_key
            if user_account_public_key
            else (self.get_user_account_public_key())
        )

        user_accounts = []

        try:
            user_accounts.append(self.get_user().get_user_account_and_slot().data)
        except:
            pass  # ignore

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=user_accounts,
            writable_spot_market_indexes=[out_market_index, in_market_index],
            readable_spot_market_indexes=[QUOTE_SPOT_MARKET_INDEX],
        )

        out_market = self.get_spot_market_account(out_market_index)
        in_market = self.get_spot_market_account(in_market_index)

        sysvar_pubkey = Pubkey.from_string(
            "Sysvar1nstructions1111111111111111111111111"
        )

        begin_swap_ix = self.program.instruction["begin_swap"](
            in_market_index,
            out_market_index,
            amount_in,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_public_key_to_use,
                    "user_stats": self.get_user_stats_public_key(),
                    "authority": self.wallet.public_key,
                    "out_spot_market_vault": out_market.vault,
                    "in_spot_market_vault": in_market.vault,
                    "in_token_account": in_ata,
                    "out_token_account": out_ata,
                    "token_program": TOKEN_PROGRAM_ID,
                    "drift_signer": self.get_state_account().signer,
                    "instructions": sysvar_pubkey,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        end_swap_ix = self.program.instruction["end_swap"](
            in_market_index,
            out_market_index,
            limit_price,
            reduce_only,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": user_public_key_to_use,
                    "user_stats": self.get_user_stats_public_key(),
                    "authority": self.wallet.public_key,
                    "out_spot_market_vault": out_market.vault,
                    "in_spot_market_vault": in_market.vault,
                    "in_token_account": in_ata,
                    "out_token_account": out_ata,
                    "token_program": TOKEN_PROGRAM_ID,
                    "drift_signer": self.get_state_account().signer,
                    "instructions": sysvar_pubkey,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

        return begin_swap_ix, end_swap_ix

    async def get_jupiter_swap_ix_v6(
        self,
        out_market_idx: int,
        in_market_idx: int,
        amount: int,
        out_ata: Optional[Pubkey] = None,
        in_ata: Optional[Pubkey] = None,
        slippage_bps: int = 50,
        quote: Optional[dict] = None,
        reduce_only: Optional[SwapReduceOnly] = None,
        user_account_public_key: Optional[Pubkey] = None,
        swap_mode: str = "ExactIn",
        fee_account: Optional[Pubkey] = None,
        platform_fee_bps: Optional[int] = None,
        only_direct_routes: bool = False,
        max_accounts: int = 50,
    ) -> Tuple[list[Instruction], list[AddressLookupTableAccount]]:
        pre_instructions: list[Instruction] = []
        JUPITER_URL = os.getenv("JUPITER_URL", "https://lite-api.jup.ag/swap/v1")

        out_market = self.get_spot_market_account(out_market_idx)
        in_market = self.get_spot_market_account(in_market_idx)

        if not out_market or not in_market:
            raise Exception("Invalid market indexes")

        if quote is None:
            params = {
                "inputMint": str(in_market.mint),
                "outputMint": str(out_market.mint),
                "amount": str(amount),
                "slippageBps": slippage_bps,
                "swapMode": swap_mode,
                "maxAccounts": max_accounts,
            }
            if only_direct_routes:
                params["onlyDirectRoutes"] = "true"
            if platform_fee_bps:
                params["platformFeeBps"] = platform_fee_bps

            url = f"{JUPITER_URL}/quote?" + "&".join(
                f"{k}={v}" for k, v in params.items()
            )
            quote_resp = requests.get(url)

            if quote_resp.status_code != 200:
                raise Exception(f"Jupiter quote failed: {quote_resp.text}")

            quote = quote_resp.json()

        if out_ata is None:
            out_ata = self.get_associated_token_account_public_key(
                out_market.market_index
            )
            ai = await self.connection.get_account_info(out_ata)
            if not ai.value:
                pre_instructions.append(
                    self.create_associated_token_account_idempotent_instruction(
                        out_ata,
                        self.wallet.public_key,
                        self.wallet.public_key,
                        out_market.mint,
                    )
                )

        if in_ata is None:
            in_ata = self.get_associated_token_account_public_key(
                in_market.market_index
            )
            ai = await self.connection.get_account_info(in_ata)
            if not ai.value:
                pre_instructions.append(
                    self.create_associated_token_account_idempotent_instruction(
                        in_ata,
                        self.wallet.public_key,
                        self.wallet.public_key,
                        in_market.mint,
                    )
                )

        swap_data = {
            "quoteResponse": quote,
            "userPublicKey": str(self.wallet.public_key),
            "destinationTokenAccount": str(out_ata),
        }
        if fee_account:
            swap_data["feeAccount"] = str(fee_account)

        swap_ix_resp = requests.post(
            f"{JUPITER_URL}/swap-instructions",
            headers={"Accept": "application/json", "Content-Type": "application/json"},
            json=swap_data,
        )

        if swap_ix_resp.status_code != 200:
            raise Exception(f"Jupiter swap instructions failed: {swap_ix_resp.text}")

        swap_ix_json = swap_ix_resp.json()
        swap_ix = swap_ix_json.get("swapInstruction")
        address_table_lookups = swap_ix_json.get("addressLookupTableAddresses")

        address_table_lookup_accounts: list[AddressLookupTableAccount] = []

        for table_pubkey in address_table_lookups:
            address_table_lookup_account = await get_address_lookup_table(
                self.connection, Pubkey.from_string(table_pubkey)
            )
            address_table_lookup_accounts.append(address_table_lookup_account)

        drift_lookup_tables = await self.fetch_market_lookup_table_accounts()
        swap_ixs = [swap_ix]

        begin_swap_ix, end_swap_ix = await self.get_swap_flash_loan_ix(
            out_market_idx,
            in_market_idx,
            amount,
            in_ata,
            out_ata,
            None,
            reduce_only,
            user_account_public_key,
        )

        ixs = [*pre_instructions, begin_swap_ix, *swap_ixs, end_swap_ix]
        cleansed_ixs: list[Instruction] = []

        for ix in ixs:
            if isinstance(ix, list):
                for i in ix:
                    if isinstance(i, dict):
                        cleansed_ixs.append(self._dict_to_instructions(i))
            elif isinstance(ix, dict):
                cleansed_ixs.append(self._dict_to_instructions(ix))
            else:
                cleansed_ixs.append(ix)

        lookup_tables = [
            *list(address_table_lookup_accounts),
            *list(drift_lookup_tables),
        ]
        return cleansed_ixs, lookup_tables

    def _dict_to_instructions(self, instructions_dict: dict) -> Instruction:
        program_id = Pubkey.from_string(instructions_dict["programId"])
        accounts = [
            AccountMeta(
                Pubkey.from_string(account["pubkey"]),
                account["isSigner"],
                account["isWritable"],
            )
            for account in instructions_dict["accounts"]
        ]
        data = base64.b64decode(instructions_dict["data"])
        return Instruction(program_id, data, accounts)

    def get_perp_market_accounts(self) -> list[PerpMarketAccount]:
        return [
            value.data
            for value in self.account_subscriber.get_market_accounts_and_slots()
            if value is not None
        ]

    def get_spot_market_accounts(self) -> list[SpotMarketAccount]:
        return [
            value.data
            for value in self.account_subscriber.get_spot_market_accounts_and_slots()
            if value is not None
        ]

    def get_market_index_and_type(
        self, name: str
    ) -> Union[Tuple[int, MarketType], None]:
        """
        Returns the market index and type for a given market name \n
        Returns `None` if the market name couldn't be matched \n
        e.g. "SOL-PERP" -> `(0, MarketType.Perp())`
        """
        name = name.upper()
        for perp_market_account in self.get_perp_market_accounts():
            if decode_name(perp_market_account.name).upper() == name:
                return (perp_market_account.market_index, MarketType.Perp())

        for spot_market_account in self.get_spot_market_accounts():
            if decode_name(spot_market_account.name).upper() == name:
                return (spot_market_account.market_index, MarketType.Spot())

        return None  # explicitly return None if no match is found

    def get_update_user_margin_trading_enabled_ix(
        self,
        margin_trading_enabled: bool,
        sub_account_id: Optional[int] = None,
    ) -> Instruction:
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)],
        )

        return self.program.instruction["update_user_margin_trading_enabled"](
            sub_account_id,
            margin_trading_enabled,
            ctx=Context(
                accounts={
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def update_user_margin_trading_enabled(
        self, margin_trading_enabled: bool, sub_account_id: Optional[int] = None
    ) -> Signature:
        """Toggles margin trading for a user

        Args:
            sub_account_id (int, optional): subaccount id. Defaults to 0.

        Returns:
            Signature: tx sig
        """
        await self.add_user(sub_account_id)

        tx_sig = (
            await self.send_ixs(
                [
                    self.get_update_user_margin_trading_enabled_ix(
                        margin_trading_enabled=margin_trading_enabled,
                        sub_account_id=sub_account_id,
                    )
                ]
            )
        ).tx_sig
        return tx_sig

    def get_update_user_custom_margin_ratio_ix(
        self,
        margin_ratio: int,
        sub_account_id: Optional[int] = None,
    ) -> Instruction:
        sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[self.get_user_account(sub_account_id)],
        )

        return self.program.instruction["update_user_custom_margin_ratio"](
            sub_account_id,
            margin_ratio,
            ctx=Context(
                accounts={
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                },
                remaining_accounts=remaining_accounts,
            ),
        )

    async def update_user_custom_margin_ratio(
        self,
        updates: List[dict],
    ) -> Signature:
        """Updates custom margin ratio for one or more subaccounts

        Args:
            updates: List of dicts with 'margin_ratio' and 'sub_account_id' keys
            for example like this
            updates = [
                {
                    "margin_ratio": 10000,
                    "sub_account_id": 0,
                }
            ]

        Returns:
            Signature: tx sig
        """
        ixs = []
        for update in updates:
            margin_ratio = update.get("margin_ratio")
            sub_account_id = update.get("sub_account_id", 0)

            if margin_ratio is None:
                raise ValueError("margin_ratio is required in each update")

            await self.add_user(sub_account_id)
            ixs.append(
                self.get_update_user_custom_margin_ratio_ix(
                    margin_ratio=margin_ratio,
                    sub_account_id=sub_account_id,
                )
            )

        tx_sig = (await self.send_ixs(ixs)).tx_sig
        return tx_sig

    async def update_prelaunch_oracle(
        self,
        market_index: int,
    ):
        return (
            await self.send_ixs(
                self.get_update_prelaunch_oracle_ix(
                    market_index,
                ),
            )
        ).tx_sig

    def get_update_prelaunch_oracle_ix(self, market_index: int):
        perp_market = self.get_perp_market_account(market_index)

        if not is_variant(perp_market.amm.oracle_source, "Prelaunch"):
            raise ValueError(f"wrong oracle source: {perp_market.amm.oracle_source}")

        return self.program.instruction["update_prelaunch_oracle"](
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "perp_market": perp_market.pubkey,
                    "oracle": perp_market.amm.oracle,
                }
            )
        )

    async def init_sequence(self, subaccount: int = 0) -> Signature:
        try:
            sig = (await self.send_ixs([self.get_sequence_init_ix(subaccount)])).tx_sig
            self.sequence_initialized_by_subaccount[subaccount] = True
            return sig
        except Exception as e:
            print(f"WARNING: failed to initialize sequence: {e}")

    def get_sequence_init_ix(self, subaccount: int = 0) -> Instruction:
        if self.enforce_tx_sequencing is False:
            raise ValueError("tx sequencing is disabled")
        return self.sequence_enforcer_program.instruction["initialize"](
            self.sequence_bump_by_subaccount[subaccount],
            str(subaccount),
            ctx=Context(
                accounts={
                    "sequence_account": self.sequence_address_by_subaccount[subaccount],
                    "authority": self.wallet.public_key,
                    "system_program": ID,
                }
            ),
        )

    async def reset_sequence_number(
        self, sequence_number: int = 0, subaccount: int = 0
    ) -> Signature:
        try:
            ix = self.get_reset_sequence_number_ix(sequence_number)
            self.resetting_sequence = True
            sig = (await self.send_ixs(ix)).tx_sig
            self.resetting_sequence = False
            self.sequence_number_by_subaccount[subaccount] = sequence_number
            return sig
        except Exception as e:
            print(f"WARNING: failed to reset sequence number: {e}")

    def get_reset_sequence_number_ix(
        self, sequence_number: int, subaccount: int = 0
    ) -> Instruction:
        if self.enforce_tx_sequencing is False:
            raise ValueError("tx sequencing is disabled")
        return self.sequence_enforcer_program.instruction["reset_sequence_number"](
            sequence_number,
            ctx=Context(
                accounts={
                    "sequence_account": self.sequence_address_by_subaccount[subaccount],
                    "authority": self.wallet.public_key,
                }
            ),
        )

    def get_check_and_set_sequence_number_ix(
        self, sequence_number: Optional[int] = None, subaccount: int = 0
    ):
        if self.enforce_tx_sequencing is False:
            raise ValueError("tx sequencing is disabled")
        sequence_number = (
            sequence_number or self.sequence_number_by_subaccount[subaccount]
        )

        if (
            sequence_number < self.sequence_number_by_subaccount[subaccount] - 1
        ):  # we increment after creating the ix, so we check - 1
            print(
                f"WARNING: sequence number {sequence_number} < last used {self.sequence_number_by_subaccount[subaccount] - 1}"
            )

        ix = self.sequence_enforcer_program.instruction[
            "check_and_set_sequence_number"
        ](
            sequence_number,
            ctx=Context(
                accounts={
                    "sequence_account": self.sequence_address_by_subaccount[subaccount],
                    "authority": self.wallet.public_key,
                }
            ),
        )

        self.sequence_number_by_subaccount[subaccount] += 1
        return ix

    async def load_sequence_info(self):
        for subaccount in self.sub_account_ids:
            address, bump = get_sequencer_public_key_and_bump(
                self.sequence_enforcer_pid, self.wallet.public_key, subaccount
            )
            try:
                sequence_account_raw = await self.sequence_enforcer_program.account[
                    "SequenceAccount"
                ].fetch(address)
            except anchorpy.error.AccountDoesNotExistError:
                self.sequence_address_by_subaccount[subaccount] = address
                self.sequence_number_by_subaccount[subaccount] = 1
                self.sequence_bump_by_subaccount[subaccount] = bump
                self.sequence_initialized_by_subaccount[subaccount] = False
                continue
            sequence_account = cast(SequenceAccount, sequence_account_raw)
            self.sequence_number_by_subaccount[subaccount] = (
                sequence_account.sequence_num + 1
            )
            self.sequence_bump_by_subaccount[subaccount] = bump
            self.sequence_initialized_by_subaccount[subaccount] = True
            self.sequence_address_by_subaccount[subaccount] = address

    async def update_user_protected_maker_orders(
        self,
        sub_account_id: int,
        protected_orders: bool,
    ):
        return (
            await self.send_ixs(
                [
                    await self.get_update_user_protected_maker_orders_ix(
                        sub_account_id, protected_orders
                    )
                ]
            )
        ).tx_sig

    async def get_update_user_protected_maker_orders_ix(
        self,
        sub_account_id: int,
        protected_orders: bool,
    ):
        return self.program.instruction["update_user_protected_maker_orders"](
            sub_account_id,
            protected_orders,
            ctx=Context(
                accounts={
                    "state": self.get_state_public_key(),
                    "user": self.get_user_account_public_key(sub_account_id),
                    "authority": self.wallet.public_key,
                    "protected_maker_mode_config": get_protected_maker_mode_config_public_key(
                        self.program_id
                    ),
                }
            ),
        )

account_subscriber = account_subscription.get_drift_client_subscriber(self.program, perp_market_indexes, spot_market_indexes, oracle_infos) instance-attribute

account_subscription_config = account_subscription instance-attribute

active_sub_account_id = active_sub_account_id if active_sub_account_id is not None else 0 instance-attribute

authority = authority instance-attribute

connection = connection instance-attribute

enforce_tx_sequencing = enforce_tx_sequencing instance-attribute

last_perp_market_seen_cache = {} instance-attribute

last_spot_market_seen_cache = {} instance-attribute

market_lookup_table = None instance-attribute

market_lookup_table_account = None instance-attribute

market_lookup_table_accounts = [] instance-attribute

market_lookup_tables = None instance-attribute

program = Program(idl, self.program_id, provider) instance-attribute

program_id = DRIFT_PROGRAM_ID instance-attribute

resetting_sequence = False instance-attribute

sequence_address_by_subaccount = {} instance-attribute

sequence_bump_by_subaccount = {} instance-attribute

sequence_enforcer_pid = SEQUENCER_PROGRAM_ID if env == 'mainnet' else DEVNET_SEQUENCER_PROGRAM_ID instance-attribute

sequence_enforcer_program = Program(idl, self.sequence_enforcer_pid, provider) instance-attribute

sequence_initialized_by_subaccount = {} instance-attribute

sequence_number_by_subaccount = {} instance-attribute

signer_public_key = None instance-attribute

sub_account_ids = sub_account_ids if sub_account_ids is not None else [self.active_sub_account_id] instance-attribute

tx_params = tx_params instance-attribute

tx_sender = JitoTxSender(self, opts, jito_params.block_engine_url, jito_params.jito_keypair, blockhash_refresh_interval_secs=(jito_params.blockhash_refresh_rate), tip_amount=(jito_params.tip_amount)) instance-attribute

tx_version = tx_version if tx_version is not None else 0 instance-attribute

user_stats = {} instance-attribute

users = {} instance-attribute

wallet = wallet instance-attribute

__init__(connection, wallet, env='mainnet', opts=DEFAULT_TX_OPTIONS, authority=None, account_subscription=AccountSubscriptionConfig.default(), perp_market_indexes=None, spot_market_indexes=None, oracle_infos=None, tx_params=None, tx_version=None, tx_sender=None, active_sub_account_id=None, sub_account_ids=None, market_lookup_table=None, market_lookup_tables=None, jito_params=None, tx_sender_blockhash_commitment=None, enforce_tx_sequencing=False)

Initializes the drift client object

Parameters:
  • connection (AsyncClient) –

    Solana RPC connection

  • wallet (Keypair | Wallet) –

    Wallet for transaction signing

  • env (DriftEnv | None, default: 'mainnet' ) –

    Drift environment. Defaults to "mainnet".

  • opts (TxOpts, default: DEFAULT_TX_OPTIONS ) –

    Transaction options. Defaults to DEFAULT_TX_OPTIONS.

  • authority (Pubkey | None, default: None ) –

    Authority for transactions. If None, defaults to wallet's public key.

  • account_subscription (AccountSubscriptionConfig, default: default() ) –

    Config for account subscriptions. Defaults to AccountSubscriptionConfig.default().

  • perp_market_indexes (list[int] | None, default: None ) –

    List of perp market indexes to subscribe to. Defaults to None.

  • spot_market_indexes (list[int] | None, default: None ) –

    List of spot market indexes to subscribe to. Defaults to None.

  • oracle_infos (list[OracleInfo] | None, default: None ) –

    List of oracle infos to subscribe to. Defaults to None.

  • tx_params (Optional[TxParams], default: None ) –

    Transaction parameters. Defaults to None.

  • tx_version (Optional[TransactionVersion], default: None ) –

    Transaction version. Defaults to None.

  • tx_sender (TxSender | None, default: None ) –

    Custom transaction sender. Defaults to None.

  • active_sub_account_id (Optional[int], default: None ) –

    Active sub-account ID. Defaults to None.

  • sub_account_ids (Optional[list[int]], default: None ) –

    List of sub-account IDs. Defaults to None.

  • market_lookup_table (Optional[Pubkey], default: None ) –

    Market lookup table pubkey (deprecated). Defaults to None.

  • market_lookup_tables (Optional[list[Pubkey]], default: None ) –

    List of market lookup table pubkeys. Defaults to None.

  • jito_params (Optional[JitoParams], default: None ) –

    Parameters for Jito MEV integration. Defaults to None.

  • tx_sender_blockhash_commitment (Commitment | None, default: None ) –

    Blockhash commitment for tx sender. Defaults to None.

  • enforce_tx_sequencing (bool, default: False ) –

    Whether to enforce transaction sequencing. Defaults to False.

Source code in src/driftpy/drift_client.py
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
def __init__(
    self,
    connection: AsyncClient,
    wallet: Keypair | Wallet,
    env: DriftEnv | None = "mainnet",
    opts: TxOpts = DEFAULT_TX_OPTIONS,
    authority: Pubkey | None = None,
    account_subscription: AccountSubscriptionConfig = AccountSubscriptionConfig.default(),
    perp_market_indexes: list[int] | None = None,
    spot_market_indexes: list[int] | None = None,
    oracle_infos: list[OracleInfo] | None = None,
    tx_params: Optional[TxParams] = None,
    tx_version: Optional[TransactionVersion] = None,
    tx_sender: TxSender | None = None,
    active_sub_account_id: Optional[int] = None,
    sub_account_ids: Optional[list[int]] = None,
    market_lookup_table: Optional[Pubkey] = None,
    market_lookup_tables: Optional[list[Pubkey]] = None,
    jito_params: Optional[JitoParams] = None,
    tx_sender_blockhash_commitment: Commitment | None = None,
    enforce_tx_sequencing: bool = False,
):
    """Initializes the drift client object

    Args:
        connection (AsyncClient): Solana RPC connection
        wallet (Keypair | Wallet): Wallet for transaction signing
        env (DriftEnv | None, optional): Drift environment. Defaults to "mainnet".
        opts (TxOpts, optional): Transaction options. Defaults to DEFAULT_TX_OPTIONS.
        authority (Pubkey | None, optional): Authority for transactions. If None, defaults to wallet's public key.
        account_subscription (AccountSubscriptionConfig, optional): Config for account subscriptions. Defaults to AccountSubscriptionConfig.default().
        perp_market_indexes (list[int] | None, optional): List of perp market indexes to subscribe to. Defaults to None.
        spot_market_indexes (list[int] | None, optional): List of spot market indexes to subscribe to. Defaults to None.
        oracle_infos (list[OracleInfo] | None, optional): List of oracle infos to subscribe to. Defaults to None.
        tx_params (Optional[TxParams], optional): Transaction parameters. Defaults to None.
        tx_version (Optional[TransactionVersion], optional): Transaction version. Defaults to None.
        tx_sender (TxSender | None, optional): Custom transaction sender. Defaults to None.
        active_sub_account_id (Optional[int], optional): Active sub-account ID. Defaults to None.
        sub_account_ids (Optional[list[int]], optional): List of sub-account IDs. Defaults to None.
        market_lookup_table (Optional[Pubkey], optional): Market lookup table pubkey (deprecated). Defaults to None.
        market_lookup_tables (Optional[list[Pubkey]], optional): List of market lookup table pubkeys. Defaults to None.
        jito_params (Optional[JitoParams], optional): Parameters for Jito MEV integration. Defaults to None.
        tx_sender_blockhash_commitment (Commitment | None, optional): Blockhash commitment for tx sender. Defaults to None.
        enforce_tx_sequencing (bool, optional): Whether to enforce transaction sequencing. Defaults to False.
    """
    self.connection = connection
    self.signer_public_key: Optional[Pubkey] = None

    file = Path(str(next(iter(driftpy.__path__))) + "/idl/drift.json")
    idl = Idl.from_json(file.read_text())

    if isinstance(wallet, Keypair):
        wallet = Wallet(wallet)

    provider = Provider(connection, wallet, opts)
    self.program_id = DRIFT_PROGRAM_ID
    self.program = Program(idl, self.program_id, provider)

    if authority is None:
        authority = wallet.public_key

    self.wallet: Wallet = wallet
    self.authority = authority

    self.active_sub_account_id = (
        active_sub_account_id if active_sub_account_id is not None else 0
    )
    self.sub_account_ids = (
        sub_account_ids
        if sub_account_ids is not None
        else [self.active_sub_account_id]
    )
    self.users: dict[int, DriftUser] = {}
    self.user_stats: dict[Pubkey, DriftUserStats] = {}

    self.last_perp_market_seen_cache = {}
    self.last_spot_market_seen_cache = {}

    self.account_subscriber = account_subscription.get_drift_client_subscriber(
        self.program, perp_market_indexes, spot_market_indexes, oracle_infos
    )
    if self.account_subscriber is None:
        raise ValueError("No account subscriber found")

    self.account_subscription_config = account_subscription

    # deprecated, use market_lookup_tables instead
    self.market_lookup_table = None
    if env is not None:
        self.market_lookup_table = (
            market_lookup_table
            if market_lookup_table is not None
            else configs[env].market_lookup_table
        )
    # deprecated, use market_lookup_table_accounts instead
    self.market_lookup_table_account: Optional[AddressLookupTableAccount] = None

    self.market_lookup_tables = None
    if env is not None and market_lookup_tables is not None:
        self.market_lookup_tables = market_lookup_tables
    else:
        self.market_lookup_tables = configs[env].market_lookup_tables

    self.market_lookup_table_accounts: list[AddressLookupTableAccount] = []

    if tx_params is None:
        tx_params = TxParams(600_000, 0)

    self.tx_params = tx_params

    self.tx_version = tx_version if tx_version is not None else 0

    self.enforce_tx_sequencing = enforce_tx_sequencing
    if self.enforce_tx_sequencing is True:
        file = Path(
            str(next(iter(driftpy.__path__))) + "/idl/sequence_enforcer.json"
        )
        idl = Idl.from_json(file.read_text())

        provider = Provider(connection, wallet, opts)
        self.sequence_enforcer_pid = (
            SEQUENCER_PROGRAM_ID
            if env == "mainnet"
            else DEVNET_SEQUENCER_PROGRAM_ID
        )
        self.sequence_enforcer_program = Program(
            idl,
            self.sequence_enforcer_pid,
            provider,
        )
        self.sequence_number_by_subaccount = {}
        self.sequence_bump_by_subaccount = {}
        self.sequence_initialized_by_subaccount = {}
        self.sequence_address_by_subaccount = {}
        self.resetting_sequence = False

    if jito_params is not None:
        from driftpy.tx.jito_tx_sender import JitoTxSender

        self.tx_sender = JitoTxSender(
            self,
            opts,
            jito_params.block_engine_url,
            jito_params.jito_keypair,
            blockhash_refresh_interval_secs=jito_params.blockhash_refresh_rate,
            tip_amount=jito_params.tip_amount,
        )
    else:
        self.tx_sender = (
            StandardTxSender(
                self.connection,
                opts,
                blockhash_commitment=(
                    tx_sender_blockhash_commitment
                    if tx_sender_blockhash_commitment is not None
                    else Commitment("finalized")
                ),
            )
            if tx_sender is None
            else tx_sender
        )

add_insurance_fund_stake(spot_market_index, amount, user_token_account=None) async

Source code in src/driftpy/drift_client.py
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
async def add_insurance_fund_stake(
    self, spot_market_index: int, amount: int, user_token_account: Pubkey = None
):
    return (
        await self.send_ixs(
            self.get_add_insurance_fund_stake_ix(
                spot_market_index, amount, user_token_account
            )
        )
    ).tx_sig

add_liquidity(amount, market_index, sub_account_id=None) async

mint LP tokens and add liquidity to the DAMM

Parameters:
  • amount (int) –

    amount of lp tokens to mint

  • market_index (int) –

    market you want to lp in

  • sub_account_id (int, default: None ) –

    subaccount id. Defaults to 0.

Returns:
  • Signature( Signature ) –

    tx sig

Source code in src/driftpy/drift_client.py
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
async def add_liquidity(
    self, amount: int, market_index: int, sub_account_id: int = None
) -> Signature:
    """mint LP tokens and add liquidity to the DAMM

    Args:
        amount (int): amount of lp tokens to mint
        market_index (int): market you want to lp in
        sub_account_id (int, optional): subaccount id. Defaults to 0.

    Returns:
        Signature: tx sig
    """
    tx_sig_and_slot = await self.send_ixs(
        [self.get_add_liquidity_ix(amount, market_index, sub_account_id)]
    )

    self.last_perp_market_seen_cache[market_index] = tx_sig_and_slot.slot

    return tx_sig_and_slot.tx_sig

add_perp_market_to_remaining_account_maps(market_index, writable, oracle_account_map, spot_market_account_map, perp_market_account_map)

Source code in src/driftpy/drift_client.py
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
def add_perp_market_to_remaining_account_maps(
    self,
    market_index: int,
    writable: bool,
    oracle_account_map: dict[str, AccountMeta],
    spot_market_account_map: dict[int, AccountMeta],
    perp_market_account_map: dict[int, AccountMeta],
) -> None:
    perp_market_account = self.get_perp_market_account(market_index)
    if not perp_market_account:
        raise ValueError(
            f"No perp market account found for market index {market_index}"
        )

    perp_market_account_map[market_index] = AccountMeta(
        pubkey=perp_market_account.pubkey, is_signer=False, is_writable=writable
    )

    oracle_writable = writable and is_variant(
        perp_market_account.amm.oracle_source, "Prelaunch"
    )
    oracle_account_map[str(perp_market_account.amm.oracle)] = AccountMeta(
        pubkey=perp_market_account.amm.oracle,
        is_signer=False,
        is_writable=oracle_writable,
    )

    self.add_spot_market_to_remaining_account_maps(
        perp_market_account.quote_spot_market_index,
        False,
        oracle_account_map,
        spot_market_account_map,
    )

add_phoenix_remaining_accounts(market_index, remaining_accounts, fulfillment_config)

Source code in src/driftpy/drift_client.py
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
def add_phoenix_remaining_accounts(
    self,
    market_index: int,
    remaining_accounts: list[AccountMeta],
    fulfillment_config: PhoenixV1FulfillmentConfigAccount,
) -> None:
    remaining_accounts.append(
        AccountMeta(fulfillment_config.pubkey, is_writable=False, is_signer=False)
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.phoenix_program_id,
            is_writable=False,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.phoenix_log_authority,
            is_writable=False,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.phoenix_market, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            self.get_signer_public_key(), is_writable=False, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.phoenix_base_vault, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.phoenix_quote_vault,
            is_writable=True,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(
            self.get_spot_market_account(market_index).vault,
            is_writable=True,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(
            self.get_spot_market_account(QUOTE_SPOT_MARKET_INDEX).vault,
            is_writable=True,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(TOKEN_PROGRAM_ID, is_writable=False, is_signer=False)
    )

add_serum_remaining_accounts(market_index, remaining_accounts, fulfillment_config)

Source code in src/driftpy/drift_client.py
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
def add_serum_remaining_accounts(
    self,
    market_index: int,
    remaining_accounts: list[AccountMeta],
    fulfillment_config: SerumV3FulfillmentConfigAccount,
) -> None:
    remaining_accounts.append(
        AccountMeta(fulfillment_config.pubkey, is_writable=False, is_signer=False)
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_program_id, is_writable=False, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_market, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_request_queue,
            is_writable=True,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_event_queue, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_bids, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_asks, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_base_vault, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_quote_vault, is_writable=True, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(
            fulfillment_config.serum_open_orders, is_writable=True, is_signer=False
        )
    )
    serum_signer_key = get_serum_signer_public_key(
        fulfillment_config.serum_program_id,
        fulfillment_config.serum_market,
        fulfillment_config.serum_signer_nonce,
    )
    remaining_accounts.append(
        AccountMeta(serum_signer_key, is_writable=False, is_signer=False)
    )
    remaining_accounts.append(
        AccountMeta(
            self.get_signer_public_key(), is_writable=False, is_signer=False
        )
    )
    remaining_accounts.append(
        AccountMeta(TOKEN_PROGRAM_ID, is_writable=False, is_signer=False)
    )
    remaining_accounts.append(
        AccountMeta(
            self.get_spot_market_account(market_index).vault,
            is_writable=True,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(
            self.get_spot_market_account(QUOTE_SPOT_MARKET_INDEX).vault,
            is_writable=True,
            is_signer=False,
        )
    )
    remaining_accounts.append(
        AccountMeta(
            self.get_state_account().srm_vault, is_writable=False, is_signer=False
        )
    )

add_spot_fulfillment_accounts(market_index, remaining_accounts, fulfillment_config=None)

Source code in src/driftpy/drift_client.py
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
def add_spot_fulfillment_accounts(
    self,
    market_index: int,
    remaining_accounts: list[AccountMeta],
    fulfillment_config: Optional[
        Union[SerumV3FulfillmentConfigAccount, PhoenixV1FulfillmentConfigAccount]
    ] = None,
) -> None:
    if fulfillment_config is not None:
        if isinstance(fulfillment_config, SerumV3FulfillmentConfigAccount):
            self.add_serum_remaining_accounts(
                market_index, remaining_accounts, fulfillment_config
            )
        elif isinstance(fulfillment_config, PhoenixV1FulfillmentConfigAccount):
            self.add_phoenix_remaining_accounts(
                market_index, remaining_accounts, fulfillment_config
            )
        else:
            raise Exception(
                f"unknown fulfillment config: {type(fulfillment_config)}"
            )
    else:
        remaining_accounts.append(
            AccountMeta(
                self.get_spot_market_account(market_index).vault,
                is_writable=False,
                is_signer=False,
            )
        )
        remaining_accounts.append(
            AccountMeta(
                self.get_spot_market_account(QUOTE_SPOT_MARKET_INDEX).vault,
                is_writable=False,
                is_signer=False,
            )
        )

add_spot_market_to_remaining_account_maps(market_index, writable, oracle_account_map, spot_market_account_map)

Source code in src/driftpy/drift_client.py
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def add_spot_market_to_remaining_account_maps(
    self,
    market_index: int,
    writable: bool,
    oracle_account_map: dict[str, AccountMeta],
    spot_market_account_map: dict[int, AccountMeta],
) -> None:
    spot_market_account = self.get_spot_market_account(market_index)

    spot_market_account_map[market_index] = AccountMeta(
        pubkey=spot_market_account.pubkey, is_signer=False, is_writable=writable
    )

    if spot_market_account.oracle != Pubkey.default():
        oracle_account_map[str(spot_market_account.oracle)] = AccountMeta(
            pubkey=spot_market_account.oracle, is_signer=False, is_writable=False
        )

add_user(sub_account_id) async

Source code in src/driftpy/drift_client.py
327
328
329
330
331
332
333
334
335
336
337
async def add_user(self, sub_account_id: int):
    if sub_account_id in self.users:
        return

    user = DriftUser(
        drift_client=self,
        user_public_key=self.get_user_account_public_key(sub_account_id),
        account_subscription=self.account_subscription_config,
    )
    await user.subscribe()
    self.users[sub_account_id] = user

add_user_stats(authority) async

Source code in src/driftpy/drift_client.py
339
340
341
342
343
344
345
346
347
348
349
350
async def add_user_stats(self, authority: Pubkey):
    if authority in self.user_stats:
        return

    self.user_stats[authority] = DriftUserStats(
        self,
        self.get_user_stats_public_key(),
        UserStatsSubscriptionConfig("confirmed"),
    )

    # don't subscribe because up to date UserStats is not required
    await self.user_stats[authority].fetch_accounts()

cancel_and_place_orders(cancel_params, place_order_params, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def cancel_and_place_orders(
    self,
    cancel_params: Tuple[
        Optional[MarketType],
        Optional[int],
        Optional[PositionDirection],
    ],
    place_order_params: List[OrderParams],
    sub_account_id: Optional[int] = None,
):
    tx_sig_and_slot = await self.send_ixs(
        self.get_cancel_and_place_orders_ix(
            cancel_params, place_order_params, sub_account_id
        ),
    )

    for order_param in place_order_params:
        if is_variant(order_param.market_type, "Perp"):
            self.last_perp_market_seen_cache[order_param.market_index] = (
                tx_sig_and_slot.slot
            )
        else:
            self.last_spot_market_seen_cache[order_param.market_index] = (
                tx_sig_and_slot.slot
            )

    return tx_sig_and_slot.tx_sig

cancel_order(order_id=None, sub_account_id=None) async

cancel specific order (if order_id=None will be most recent order)

Parameters:
  • order_id (Optional[int], default: None ) –

    Defaults to None.

  • sub_account_id (int, default: None ) –

    subaccount id which contains order. Defaults to 0.

Returns:
  • str( Signature ) –

    tx sig

Source code in src/driftpy/drift_client.py
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
async def cancel_order(
    self,
    order_id: Optional[int] = None,
    sub_account_id: int = None,
) -> Signature:
    """cancel specific order (if order_id=None will be most recent order)

    Args:
        order_id (Optional[int], optional): Defaults to None.
        sub_account_id (int, optional): subaccount id which contains order. Defaults to 0.

    Returns:
        str: tx sig
    """
    return (
        await self.send_ixs(
            self.get_cancel_order_ix(order_id, sub_account_id),
        )
    ).tx_sig

cancel_order_by_user_id(user_order_id, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
async def cancel_order_by_user_id(
    self,
    user_order_id: int,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    return (
        await self.send_ixs(
            self.get_cancel_order_by_user_id_ix(user_order_id, sub_account_id),
        )
    ).tx_sig

cancel_orders(market_type=None, market_index=None, direction=None, sub_account_id=None) async

cancel all existing orders on the book

Parameters:
  • market_type (MarketType, default: None ) –

    only cancel orders for single market, used with market_index

  • market_index (int, default: None ) –

    only cancel orders for single market, used with market_type

  • direction (PositionDirection, default: None ) –

    (PositionDirection, optional): only cancel bids or asks

  • sub_account_id (int, default: None ) –

    subaccount id. Defaults to 0.

Returns:
  • Signature( Signature ) –

    tx sig

Source code in src/driftpy/drift_client.py
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
async def cancel_orders(
    self,
    market_type: MarketType = None,
    market_index: int = None,
    direction: PositionDirection = None,
    sub_account_id: int = None,
) -> Signature:
    """cancel all existing orders on the book

    Args:
        market_type (MarketType, optional): only cancel orders for single market, used with market_index
        market_index (int, optional): only cancel orders for single market, used with market_type
        direction: (PositionDirection, optional): only cancel bids or asks
        sub_account_id (int, optional): subaccount id. Defaults to 0.

    Returns:
        Signature: tx sig
    """
    return (
        await self.send_ixs(
            self.get_cancel_orders_ix(
                market_type, market_index, direction, sub_account_id
            )
        )
    ).tx_sig

cancel_request_remove_insurance_fund_stake(spot_market_index) async

Source code in src/driftpy/drift_client.py
2955
2956
2957
2958
2959
2960
2961
2962
async def cancel_request_remove_insurance_fund_stake(self, spot_market_index: int):
    return (
        await self.send_ixs(
            self.get_cancel_request_remove_insurance_fund_stake_ix(
                spot_market_index
            )
        )
    ).tx_sig

close_position(market_index, limit_price=0, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
@deprecated
async def close_position(
    self, market_index: int, limit_price: int = 0, sub_account_id: int = None
):
    return (
        await self.send_ixs(
            self.get_close_position_ix(
                market_index, limit_price, sub_account_id=sub_account_id
            )
        )
    ).tx_sig

convert_to_perp_precision(amount)

Source code in src/driftpy/drift_client.py
496
497
def convert_to_perp_precision(self, amount: Union[int, float]) -> int:
    return int(amount * BASE_PRECISION)

convert_to_price_precision(amount)

Source code in src/driftpy/drift_client.py
499
500
def convert_to_price_precision(self, amount: Union[int, float]) -> int:
    return int(amount * PRICE_PRECISION)

convert_to_spot_precision(amount, market_index)

Source code in src/driftpy/drift_client.py
492
493
494
def convert_to_spot_precision(self, amount: Union[int, float], market_index) -> int:
    spot_market = self.get_spot_market_account(market_index)
    return cast_to_spot_precision(amount, spot_market)

create_associated_token_account_idempotent_instruction(account, payer, owner, mint)

Source code in src/driftpy/drift_client.py
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
def create_associated_token_account_idempotent_instruction(
    self, account: Pubkey, payer: Pubkey, owner: Pubkey, mint: Pubkey
):
    return Instruction(
        accounts=[
            AccountMeta(pubkey=payer, is_signer=True, is_writable=True),
            AccountMeta(pubkey=account, is_signer=False, is_writable=True),
            AccountMeta(pubkey=owner, is_signer=False, is_writable=False),
            AccountMeta(pubkey=mint, is_signer=False, is_writable=False),
            AccountMeta(pubkey=SYS_PROGRAM_ID, is_signer=False, is_writable=False),
            AccountMeta(
                pubkey=TOKEN_PROGRAM_ID, is_signer=False, is_writable=False
            ),
            AccountMeta(pubkey=RENT, is_signer=False, is_writable=False),
        ],
        program_id=ASSOCIATED_TOKEN_PROGRAM_ID,
        data=bytes([0x01]),
    )

decode_signed_msg_order_params_message(signed_msg_order_params_buf, is_delegate=False)

Source code in src/driftpy/drift_client.py
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
def decode_signed_msg_order_params_message(
    self, signed_msg_order_params_buf: bytes, is_delegate: bool = False
) -> Union[SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage]:
    payload = signed_msg_order_params_buf[8:]
    payload_with_padding = payload + bytes(128)
    if is_delegate:
        return self.program.coder.types.decode(
            "SignedMsgOrderParamsDelegateMessage", payload_with_padding
        )
    else:
        return self.program.coder.types.decode(
            "SignedMsgOrderParamsMessage", payload_with_padding
        )

deposit(amount, spot_market_index, user_token_account, sub_account_id=None, reduce_only=False, user_initialized=True) async

deposits collateral into protocol

Parameters:
  • amount (int) –

    amount to deposit

  • spot_market_index (int) –
  • user_token_account (Pubkey) –
  • sub_account_id (int, default: None ) –

    subaccount to deposit into. Defaults to 0.

  • reduce_only (bool, default: False ) –

    paying back borrow vs depositing new assets. Defaults to False.

  • user_initialized (bool, default: True ) –

    if need to initialize user account too set this to False. Defaults to True.

Returns:
  • TxSigAndSlot( TxSigAndSlot ) –

    tx sig and slot

Source code in src/driftpy/drift_client.py
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
async def deposit(
    self,
    amount: int,
    spot_market_index: int,
    user_token_account: Pubkey,
    sub_account_id: Optional[int] = None,
    reduce_only=False,
    user_initialized=True,
) -> TxSigAndSlot:
    """deposits collateral into protocol

    Args:
        amount (int): amount to deposit
        spot_market_index (int):
        user_token_account (Pubkey):
        sub_account_id (int, optional): subaccount to deposit into. Defaults to 0.
        reduce_only (bool, optional): paying back borrow vs depositing new assets. Defaults to False.
        user_initialized (bool, optional): if need to initialize user account too set this to False. Defaults to True.

    Returns:
        TxSigAndSlot: tx sig and slot
    """
    tx_sig_and_slot = await self.send_ixs(
        await self.get_deposit_collateral_ix(
            amount,
            spot_market_index,
            user_token_account,
            sub_account_id,
            reduce_only,
            user_initialized,
        )
    )
    self.last_spot_market_seen_cache[spot_market_index] = tx_sig_and_slot.slot
    return tx_sig_and_slot

encode_signed_msg_order_params_message(order_params_message, delegate_signer=False)

Borsh encode signedMsg order params message

Parameters:
  • order_params_message (Union[dict, SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage]) –

    The order params message to encode

  • delegate_signer (bool, default: False ) –

    Whether to use delegate message format

Returns:
  • bytes

    The encoded buffer

Source code in src/driftpy/drift_client.py
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
def encode_signed_msg_order_params_message(
    self,
    order_params_message: Union[
        dict, SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage
    ],
    delegate_signer: bool = False,
) -> bytes:
    """Borsh encode signedMsg order params message

    Args:
        order_params_message: The order params message to encode
        delegate_signer: Whether to use delegate message format

    Returns:
        The encoded buffer
    """

    anchor_ix_name = (
        "global:SignedMsgOrderParamsMessage"
        if not delegate_signer
        else "global:SignedMsgOrderParamsDelegateMessage"
    )
    prefix = bytes.fromhex(sha256(anchor_ix_name.encode()).hexdigest()[:16])

    # Convert Pubkey to bytes if it's a delegate message
    if delegate_signer and isinstance(
        order_params_message, SignedMsgOrderParamsDelegateMessage
    ):
        taker_pubkey_bytes = bytes(order_params_message.taker_pubkey)
        order_params_message = SignedMsgOrderParamsDelegateMessage(
            signed_msg_order_params=order_params_message.signed_msg_order_params,
            slot=order_params_message.slot,
            uuid=order_params_message.uuid,
            taker_pubkey=list(taker_pubkey_bytes),
            take_profit_order_params=order_params_message.take_profit_order_params,
            stop_loss_order_params=order_params_message.stop_loss_order_params,
        )

    encoded = self.program.coder.types.encode(
        "SignedMsgOrderParamsDelegateMessage"
        if delegate_signer
        else "SignedMsgOrderParamsMessage",
        order_params_message,
    )

    buf = prefix + encoded
    return buf

fetch_market_lookup_table() async

Source code in src/driftpy/drift_client.py
507
508
509
510
511
512
513
514
async def fetch_market_lookup_table(self) -> AddressLookupTableAccount:
    if self.market_lookup_table_account is not None:
        return self.market_lookup_table_account

    self.market_lookup_table_account = await get_address_lookup_table(
        self.connection, self.market_lookup_table
    )
    return self.market_lookup_table_account

fetch_market_lookup_table_accounts() async

Source code in src/driftpy/drift_client.py
305
306
307
308
309
310
311
312
313
314
315
316
async def fetch_market_lookup_table_accounts(self):
    if self.market_lookup_tables is None:
        raise ValueError("No market lookup tables found")
    self.market_lookup_table_accounts: list[
        AddressLookupTableAccount
    ] = await asyncio.gather(
        *[
            get_address_lookup_table(self.connection, table)
            for table in self.market_lookup_tables
        ]
    )
    return self.market_lookup_table_accounts

fill_perp_order(user_account_pubkey, user_account, order, maker_info, referrer_info) async

Source code in src/driftpy/drift_client.py
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
async def fill_perp_order(
    self,
    user_account_pubkey: Pubkey,
    user_account: UserAccount,
    order: Order,
    maker_info: Optional[Union[MakerInfo, list[MakerInfo]]],
    referrer_info: Optional[ReferrerInfo],
):
    return (
        await self.send_ixs(
            [
                await self.get_fill_perp_order_ix(
                    user_account_pubkey,
                    user_account,
                    order,
                    maker_info,
                    referrer_info,
                )
            ]
        )
    ).tx_sig

force_cancel_orders(user_account_pubkey, user_account, filler_pubkey=None) async

Source code in src/driftpy/drift_client.py
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
async def force_cancel_orders(
    self,
    user_account_pubkey: Pubkey,
    user_account: UserAccount,
    filler_pubkey: Optional[Pubkey] = None,
) -> Signature:
    tx_sig_and_slot = await self.send_ixs(
        self.get_force_cancel_orders_ix(
            user_account_pubkey, user_account, filler_pubkey
        )
    )

    return tx_sig_and_slot.tx_sig

get_add_insurance_fund_stake_ix(spot_market_index, amount, user_token_account=None)

Source code in src/driftpy/drift_client.py
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
def get_add_insurance_fund_stake_ix(
    self, spot_market_index: int, amount: int, user_token_account: Pubkey = None
):
    remaining_accounts = self.get_remaining_accounts(
        writable_spot_market_indexes=[spot_market_index],
    )

    user_token_account = (
        user_token_account
        if user_token_account is not None
        else self.get_associated_token_account_public_key(spot_market_index)
    )

    return self.program.instruction["add_insurance_fund_stake"](
        spot_market_index,
        amount,
        ctx=Context(
            accounts={
                "state": get_state_public_key(self.program_id),
                "spot_market": get_spot_market_public_key(
                    self.program_id, spot_market_index
                ),
                "insurance_fund_stake": get_insurance_fund_stake_public_key(
                    self.program_id, self.authority, spot_market_index
                ),
                "user_stats": get_user_stats_account_public_key(
                    self.program_id, self.authority
                ),
                "authority": self.wallet.public_key,
                "spot_market_vault": get_spot_market_vault_public_key(
                    self.program_id, spot_market_index
                ),
                "insurance_fund_vault": get_insurance_fund_vault_public_key(
                    self.program_id, spot_market_index
                ),
                "drift_signer": self.get_signer_public_key(self.program_id),
                "user_token_account": user_token_account,
                "token_program": TOKEN_PROGRAM_ID,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_add_liquidity_ix(amount, market_index, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
def get_add_liquidity_ix(
    self, amount: int, market_index: int, sub_account_id: int = None
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[market_index],
        user_accounts=[self.get_user_account(sub_account_id)],
    )
    user_account_public_key = get_user_account_public_key(
        self.program_id, self.authority, sub_account_id
    )

    return self.program.instruction["add_perp_lp_shares"](
        amount,
        market_index,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_account_public_key,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_associated_token_account_public_key(market_index)

Source code in src/driftpy/drift_client.py
409
410
411
412
def get_associated_token_account_public_key(self, market_index: int) -> Pubkey:
    spot_market = self.get_spot_market_account(market_index)
    mint = spot_market.mint
    return get_associated_token_address(self.wallet.public_key, mint)

get_cancel_and_place_orders_ix(cancel_params, place_order_params, sub_account_id=None)

Source code in src/driftpy/drift_client.py
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
def get_cancel_and_place_orders_ix(
    self,
    cancel_params: Tuple[
        Optional[MarketType],
        Optional[int],
        Optional[PositionDirection],
    ],
    place_order_params: List[OrderParams],
    sub_account_id: Optional[int] = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    market_type, market_index, direction = cancel_params

    cancel_orders_ix = self.get_cancel_orders_ix(
        market_type, market_index, direction, sub_account_id
    )
    place_orders_ix = self.get_place_orders_ix(place_order_params, sub_account_id)
    return [cancel_orders_ix, place_orders_ix]

get_cancel_order_by_user_id_ix(user_order_id, sub_account_id=None)

Source code in src/driftpy/drift_client.py
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
def get_cancel_order_by_user_id_ix(
    self, user_order_id: int, sub_account_id: int = None
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)]
    )

    return self.program.instruction["cancel_order_by_user_id"](
        user_order_id,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_cancel_order_ix(order_id=None, sub_account_id=None)

Source code in src/driftpy/drift_client.py
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
def get_cancel_order_ix(
    self, order_id: Optional[int] = None, sub_account_id: int = None
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)]
    )

    return self.program.instruction["cancel_order"](
        order_id,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_cancel_orders_ix(market_type=None, market_index=None, direction=None, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
def get_cancel_orders_ix(
    self,
    market_type: MarketType = None,
    market_index: int = None,
    direction: PositionDirection = None,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)]
    )

    return self.program.instruction["cancel_orders"](
        market_type,
        market_index,
        direction,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_cancel_request_remove_insurance_fund_stake_ix(spot_market_index, user_token_account=None)

Source code in src/driftpy/drift_client.py
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
def get_cancel_request_remove_insurance_fund_stake_ix(
    self, spot_market_index: int, user_token_account: Pubkey = None
):
    ra = self.get_remaining_accounts(
        writable_spot_market_indexes=[spot_market_index]
    )

    return self.program.instruction["cancel_request_remove_insurance_fund_stake"](
        spot_market_index,
        ctx=Context(
            accounts={
                "state": get_state_public_key(self.program_id),
                "spot_market": get_spot_market_public_key(
                    self.program_id, spot_market_index
                ),
                "insurance_fund_stake": get_insurance_fund_stake_public_key(
                    self.program_id, self.authority, spot_market_index
                ),
                "user_stats": get_user_stats_account_public_key(
                    self.program_id, self.authority
                ),
                "authority": self.wallet.public_key,
                "insurance_fund_vault": get_insurance_fund_vault_public_key(
                    self.program_id, spot_market_index
                ),
            },
            remaining_accounts=ra,
        ),
    )

get_check_and_set_sequence_number_ix(sequence_number=None, subaccount=0)

Source code in src/driftpy/drift_client.py
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
def get_check_and_set_sequence_number_ix(
    self, sequence_number: Optional[int] = None, subaccount: int = 0
):
    if self.enforce_tx_sequencing is False:
        raise ValueError("tx sequencing is disabled")
    sequence_number = (
        sequence_number or self.sequence_number_by_subaccount[subaccount]
    )

    if (
        sequence_number < self.sequence_number_by_subaccount[subaccount] - 1
    ):  # we increment after creating the ix, so we check - 1
        print(
            f"WARNING: sequence number {sequence_number} < last used {self.sequence_number_by_subaccount[subaccount] - 1}"
        )

    ix = self.sequence_enforcer_program.instruction[
        "check_and_set_sequence_number"
    ](
        sequence_number,
        ctx=Context(
            accounts={
                "sequence_account": self.sequence_address_by_subaccount[subaccount],
                "authority": self.wallet.public_key,
            }
        ),
    )

    self.sequence_number_by_subaccount[subaccount] += 1
    return ix

get_close_position_ix(market_index, limit_price=0, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
@deprecated
def get_close_position_ix(
    self, market_index: int, limit_price: int = 0, sub_account_id: int = None
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    position = self.get_perp_position(market_index, sub_account_id)
    if position is None or position.base_asset_amount == 0:
        print("=> user has no position to close...")
        return

    order_params = OrderParams(
        order_type=OrderType.Market(),
        market_index=market_index,
        base_asset_amount=abs(int(position.base_asset_amount)),
        direction=(
            PositionDirection.Long()
            if position.base_asset_amount < 0
            else PositionDirection.Short()
        ),
        price=limit_price,
        reduce_only=True,
    )

    ix = self.get_place_and_take_perp_order_ix(
        order_params, sub_account_id=sub_account_id
    )
    return ix

get_deposit_collateral_ix(amount, spot_market_index, user_token_account, sub_account_id=None, reduce_only=False, user_initialized=True) async

Source code in src/driftpy/drift_client.py
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
async def get_deposit_collateral_ix(
    self,
    amount: int,
    spot_market_index: int,
    user_token_account: Pubkey,
    sub_account_id: Optional[int] = None,
    reduce_only: Optional[bool] = False,
    user_initialized: Optional[bool] = True,
) -> List[Instruction]:
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
    spot_market_account = self.get_spot_market_account(spot_market_index)
    if not spot_market_account:
        raise Exception("Spot market account not found")

    is_sol_market = spot_market_account.mint == WRAPPED_SOL_MINT
    signer_authority = self.wallet.public_key

    create_WSOL_token_account = (
        is_sol_market and user_token_account == signer_authority
    )

    if user_initialized:
        remaining_accounts = self.get_remaining_accounts(
            writable_spot_market_indexes=[spot_market_index],
            user_accounts=[self.get_user_account(sub_account_id)],
        )
    else:
        raise Exception("not implemented...")

    instructions = []

    if create_WSOL_token_account:
        ixs, ata_pubkey = await self.get_wrapped_sol_account_creation_ixs(amount)
        instructions.extend(ixs)
        user_token_account = ata_pubkey

    user_token_account = (
        user_token_account
        if user_token_account is not None
        else self.get_associated_token_account_public_key(spot_market_index)
    )

    spot_market_pk = get_spot_market_public_key(self.program_id, spot_market_index)
    spot_vault_public_key = get_spot_market_vault_public_key(
        self.program_id, spot_market_index
    )
    user_account_public_key = get_user_account_public_key(
        self.program_id, self.authority, sub_account_id
    )
    deposit_ix = self.program.instruction["deposit"](
        spot_market_index,
        amount,
        reduce_only,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "spot_market": spot_market_pk,
                "spot_market_vault": spot_vault_public_key,
                "user": user_account_public_key,
                "user_stats": self.get_user_stats_public_key(),
                "user_token_account": user_token_account,
                "authority": self.wallet.public_key,
                "token_program": TOKEN_PROGRAM_ID,
            },
            remaining_accounts=remaining_accounts,
        ),
    )
    instructions.append(deposit_ix)
    if create_WSOL_token_account:
        close_account_params = CloseAccountParams(
            program_id=TOKEN_PROGRAM_ID,
            account=user_token_account,
            dest=signer_authority,
            owner=signer_authority,
        )
        close_account_ix = close_account(close_account_params)
        instructions.append(close_account_ix)
    return instructions

get_fill_perp_order_ix(user_account_pubkey, user_account, order, maker_info, referrer_info) async

Source code in src/driftpy/drift_client.py
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
async def get_fill_perp_order_ix(
    self,
    user_account_pubkey: Pubkey,
    user_account: UserAccount,
    order: Order,
    maker_info: Optional[Union[MakerInfo, list[MakerInfo]]],
    referrer_info: Optional[ReferrerInfo],
) -> Instruction:
    user_stats_pubkey = get_user_stats_account_public_key(
        self.program.program_id, user_account.authority
    )

    filler_pubkey = self.get_user_account_public_key()
    filler_stats_pubkey = self.get_user_stats_public_key()

    market_index = (
        order.market_index
        if order
        else next(
            (
                order.market_index
                for order in user_account.orders
                if order.order_id == user_account.next_order_id - 1
            ),
            None,
        )
    )

    maker_info = (
        maker_info
        if isinstance(maker_info, list)
        else [maker_info]
        if maker_info
        else []
    )

    user_accounts = [user_account]
    for maker in maker_info:
        user_accounts.append(maker.maker_user_account)

    remaining_accounts = self.get_remaining_accounts(user_accounts, [market_index])

    for maker in maker_info:
        remaining_accounts.append(
            AccountMeta(pubkey=maker.maker, is_writable=True, is_signer=False)
        )
        remaining_accounts.append(
            AccountMeta(pubkey=maker.maker_stats, is_writable=True, is_signer=False)
        )

    if referrer_info:
        referrer_is_maker = any(
            maker.maker == referrer_info.referrer for maker in maker_info
        )
        if not referrer_is_maker:
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer, is_writable=True, is_signer=False
                )
            )
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer_stats,
                    is_writable=True,
                    is_signer=False,
                )
            )

    order_id = order.order_id
    return self.program.instruction["fill_perp_order"](
        order_id,
        None,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "filler": filler_pubkey,
                "filler_stats": filler_stats_pubkey,
                "user": user_account_pubkey,
                "user_stats": user_stats_pubkey,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_force_cancel_orders_ix(user_account_pubkey, user_account, filler_pubkey=None)

Source code in src/driftpy/drift_client.py
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
def get_force_cancel_orders_ix(
    self,
    user_account_pubkey: Pubkey,
    user_account: UserAccount,
    filler_pubkey: Optional[Pubkey] = None,
):
    filler = filler_pubkey or self.get_user_account_public_key()

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[user_account],
        writable_spot_market_indexes=[QUOTE_SPOT_MARKET_INDEX],
    )

    return self.program.instruction["force_cancel_orders"](
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "filler": filler,
                "user": user_account_pubkey,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        )
    )

get_initialize_insurance_fund_stake_ix(spot_market_index)

Source code in src/driftpy/drift_client.py
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
def get_initialize_insurance_fund_stake_ix(
    self,
    spot_market_index: int,
):
    return self.program.instruction["initialize_insurance_fund_stake"](
        spot_market_index,
        ctx=Context(
            accounts={
                "spot_market": get_spot_market_public_key(
                    self.program_id, spot_market_index
                ),
                "insurance_fund_stake": get_insurance_fund_stake_public_key(
                    self.program_id, self.authority, spot_market_index
                ),
                "user_stats": get_user_stats_account_public_key(
                    self.program_id, self.authority
                ),
                "state": get_state_public_key(self.program_id),
                "authority": self.wallet.public_key,
                "payer": self.wallet.public_key,
                "rent": RENT,
                "system_program": ID,
            }
        ),
    )

get_initialize_user_instructions(sub_account_id=0, name=DEFAULT_USER_NAME, referrer_info=None)

Source code in src/driftpy/drift_client.py
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
def get_initialize_user_instructions(
    self,
    sub_account_id: int = 0,
    name: str = DEFAULT_USER_NAME,
    referrer_info: ReferrerInfo = None,
) -> Instruction:
    user_public_key = self.get_user_account_public_key(sub_account_id)
    state_public_key = self.get_state_public_key()
    user_stats_public_key = self.get_user_stats_public_key()

    encoded_name = encode_name(name)

    remaining_accounts = []
    if referrer_info is not None:
        remaining_accounts.append(
            AccountMeta(referrer_info.referrer, is_writable=True, is_signer=False)
        )
        remaining_accounts.append(
            AccountMeta(
                referrer_info.referrer_stats, is_writable=True, is_signer=False
            )
        )

    initialize_user_account_ix = self.program.instruction["initialize_user"](
        sub_account_id,
        encoded_name,
        ctx=Context(
            accounts={
                "user": user_public_key,
                "user_stats": user_stats_public_key,
                "state": state_public_key,
                "authority": self.wallet.public_key,
                "payer": self.wallet.public_key,
                "rent": RENT,
                "system_program": ID,
            },
            remaining_accounts=remaining_accounts,
        ),
    )
    return initialize_user_account_ix

get_initialize_user_stats()

Source code in src/driftpy/drift_client.py
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
def get_initialize_user_stats(
    self,
):
    state_public_key = self.get_state_public_key()
    user_stats_public_key = self.get_user_stats_public_key()

    return self.program.instruction["initialize_user_stats"](
        ctx=Context(
            accounts={
                "user_stats": user_stats_public_key,
                "state": state_public_key,
                "authority": self.wallet.public_key,
                "payer": self.wallet.public_key,
                "rent": RENT,
                "system_program": ID,
            },
        ),
    )

get_jupiter_swap_ix_v6(out_market_idx, in_market_idx, amount, out_ata=None, in_ata=None, slippage_bps=50, quote=None, reduce_only=None, user_account_public_key=None, swap_mode='ExactIn', fee_account=None, platform_fee_bps=None, only_direct_routes=False, max_accounts=50) async

Source code in src/driftpy/drift_client.py
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
async def get_jupiter_swap_ix_v6(
    self,
    out_market_idx: int,
    in_market_idx: int,
    amount: int,
    out_ata: Optional[Pubkey] = None,
    in_ata: Optional[Pubkey] = None,
    slippage_bps: int = 50,
    quote: Optional[dict] = None,
    reduce_only: Optional[SwapReduceOnly] = None,
    user_account_public_key: Optional[Pubkey] = None,
    swap_mode: str = "ExactIn",
    fee_account: Optional[Pubkey] = None,
    platform_fee_bps: Optional[int] = None,
    only_direct_routes: bool = False,
    max_accounts: int = 50,
) -> Tuple[list[Instruction], list[AddressLookupTableAccount]]:
    pre_instructions: list[Instruction] = []
    JUPITER_URL = os.getenv("JUPITER_URL", "https://lite-api.jup.ag/swap/v1")

    out_market = self.get_spot_market_account(out_market_idx)
    in_market = self.get_spot_market_account(in_market_idx)

    if not out_market or not in_market:
        raise Exception("Invalid market indexes")

    if quote is None:
        params = {
            "inputMint": str(in_market.mint),
            "outputMint": str(out_market.mint),
            "amount": str(amount),
            "slippageBps": slippage_bps,
            "swapMode": swap_mode,
            "maxAccounts": max_accounts,
        }
        if only_direct_routes:
            params["onlyDirectRoutes"] = "true"
        if platform_fee_bps:
            params["platformFeeBps"] = platform_fee_bps

        url = f"{JUPITER_URL}/quote?" + "&".join(
            f"{k}={v}" for k, v in params.items()
        )
        quote_resp = requests.get(url)

        if quote_resp.status_code != 200:
            raise Exception(f"Jupiter quote failed: {quote_resp.text}")

        quote = quote_resp.json()

    if out_ata is None:
        out_ata = self.get_associated_token_account_public_key(
            out_market.market_index
        )
        ai = await self.connection.get_account_info(out_ata)
        if not ai.value:
            pre_instructions.append(
                self.create_associated_token_account_idempotent_instruction(
                    out_ata,
                    self.wallet.public_key,
                    self.wallet.public_key,
                    out_market.mint,
                )
            )

    if in_ata is None:
        in_ata = self.get_associated_token_account_public_key(
            in_market.market_index
        )
        ai = await self.connection.get_account_info(in_ata)
        if not ai.value:
            pre_instructions.append(
                self.create_associated_token_account_idempotent_instruction(
                    in_ata,
                    self.wallet.public_key,
                    self.wallet.public_key,
                    in_market.mint,
                )
            )

    swap_data = {
        "quoteResponse": quote,
        "userPublicKey": str(self.wallet.public_key),
        "destinationTokenAccount": str(out_ata),
    }
    if fee_account:
        swap_data["feeAccount"] = str(fee_account)

    swap_ix_resp = requests.post(
        f"{JUPITER_URL}/swap-instructions",
        headers={"Accept": "application/json", "Content-Type": "application/json"},
        json=swap_data,
    )

    if swap_ix_resp.status_code != 200:
        raise Exception(f"Jupiter swap instructions failed: {swap_ix_resp.text}")

    swap_ix_json = swap_ix_resp.json()
    swap_ix = swap_ix_json.get("swapInstruction")
    address_table_lookups = swap_ix_json.get("addressLookupTableAddresses")

    address_table_lookup_accounts: list[AddressLookupTableAccount] = []

    for table_pubkey in address_table_lookups:
        address_table_lookup_account = await get_address_lookup_table(
            self.connection, Pubkey.from_string(table_pubkey)
        )
        address_table_lookup_accounts.append(address_table_lookup_account)

    drift_lookup_tables = await self.fetch_market_lookup_table_accounts()
    swap_ixs = [swap_ix]

    begin_swap_ix, end_swap_ix = await self.get_swap_flash_loan_ix(
        out_market_idx,
        in_market_idx,
        amount,
        in_ata,
        out_ata,
        None,
        reduce_only,
        user_account_public_key,
    )

    ixs = [*pre_instructions, begin_swap_ix, *swap_ixs, end_swap_ix]
    cleansed_ixs: list[Instruction] = []

    for ix in ixs:
        if isinstance(ix, list):
            for i in ix:
                if isinstance(i, dict):
                    cleansed_ixs.append(self._dict_to_instructions(i))
        elif isinstance(ix, dict):
            cleansed_ixs.append(self._dict_to_instructions(ix))
        else:
            cleansed_ixs.append(ix)

    lookup_tables = [
        *list(address_table_lookup_accounts),
        *list(drift_lookup_tables),
    ]
    return cleansed_ixs, lookup_tables

get_liquidate_perp_ix(user_authority, market_index, max_base_asset_amount, limit_price=None, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def get_liquidate_perp_ix(
    self,
    user_authority: Pubkey,
    market_index: int,
    max_base_asset_amount: int,
    limit_price: Optional[int] = None,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    user_pk = get_user_account_public_key(
        self.program_id, user_authority, user_sub_account_id
    )
    user_stats_pk = get_user_stats_account_public_key(
        self.program_id,
        user_authority,
    )

    liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
    liq_pk = self.get_user_account_public_key(liq_sub_account_id)
    liq_stats_pk = self.get_user_stats_public_key()

    user_account = await self.program.account["User"].fetch(user_pk)
    liq_user_account = self.get_user_account(liq_sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[market_index],
        user_accounts=[user_account, liq_user_account],
    )

    return self.program.instruction["liquidate_perp"](
        market_index,
        max_base_asset_amount,
        limit_price,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
                "user": user_pk,
                "user_stats": user_stats_pk,
                "liquidator": liq_pk,
                "liquidator_stats": liq_stats_pk,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_liquidate_perp_pnl_for_deposit_ix(user_authority, perp_market_index, spot_market_index, max_pnl_transfer, limit_price=None, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def get_liquidate_perp_pnl_for_deposit_ix(
    self,
    user_authority: Pubkey,
    perp_market_index: int,
    spot_market_index: int,
    max_pnl_transfer: int,
    limit_price: int = None,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    user_pk = get_user_account_public_key(
        self.program_id, user_authority, user_sub_account_id
    )
    user_stats_pk = get_user_stats_account_public_key(
        self.program_id,
        user_authority,
    )

    liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
    liq_pk = self.get_user_account_public_key(liq_sub_account_id)
    liq_stats_pk = self.get_user_stats_public_key()

    user_account = await self.program.account["User"].fetch(user_pk)
    liq_user_account = self.get_user_account(liq_sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[perp_market_index],
        writable_spot_market_indexes=[spot_market_index],
        user_accounts=[user_account, liq_user_account],
    )

    result = self.program.instruction["liquidate_perp_pnl_for_deposit"](
        perp_market_index,
        spot_market_index,
        max_pnl_transfer,
        limit_price,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
                "user": user_pk,
                "user_stats": user_stats_pk,
                "liquidator": liq_pk,
                "liquidator_stats": liq_stats_pk,
            },
            remaining_accounts=remaining_accounts,
        ),
    )
    return result

get_liquidate_spot_ix(user_authority, asset_market_index, liability_market_index, max_liability_transfer, limit_price=None, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def get_liquidate_spot_ix(
    self,
    user_authority: Pubkey,
    asset_market_index: int,
    liability_market_index: int,
    max_liability_transfer: int,
    limit_price: int = None,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    user_pk = get_user_account_public_key(
        self.program_id, user_authority, sub_account_id=user_sub_account_id
    )
    user_stats_pk = get_user_stats_account_public_key(
        self.program_id,
        user_authority,
    )

    liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
    liq_pk = self.get_user_account_public_key(liq_sub_account_id)
    liq_stats_pk = self.get_user_stats_public_key()

    user_account = await self.program.account["User"].fetch(user_pk)
    liq_user_account = self.get_user_account(liq_sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_spot_market_indexes=[liability_market_index, asset_market_index],
        user_accounts=[user_account, liq_user_account],
    )

    return self.program.instruction["liquidate_spot"](
        asset_market_index,
        liability_market_index,
        max_liability_transfer,
        limit_price,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
                "user": user_pk,
                "user_stats": user_stats_pk,
                "liquidator": liq_pk,
                "liquidator_stats": liq_stats_pk,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_market_index_and_type(name)

Returns the market index and type for a given market name

Returns None if the market name couldn't be matched

e.g. "SOL-PERP" -> (0, MarketType.Perp())

Source code in src/driftpy/drift_client.py
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
def get_market_index_and_type(
    self, name: str
) -> Union[Tuple[int, MarketType], None]:
    """
    Returns the market index and type for a given market name \n
    Returns `None` if the market name couldn't be matched \n
    e.g. "SOL-PERP" -> `(0, MarketType.Perp())`
    """
    name = name.upper()
    for perp_market_account in self.get_perp_market_accounts():
        if decode_name(perp_market_account.name).upper() == name:
            return (perp_market_account.market_index, MarketType.Perp())

    for spot_market_account in self.get_spot_market_accounts():
        if decode_name(spot_market_account.name).upper() == name:
            return (spot_market_account.market_index, MarketType.Spot())

    return None  # explicitly return None if no match is found

get_modify_order_by_user_id_ix(user_order_id, modify_order_params, sub_account_id=None)

Source code in src/driftpy/drift_client.py
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
def get_modify_order_by_user_id_ix(
    self,
    user_order_id: int,
    modify_order_params: ModifyOrderParams,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)],
    )

    return self.program.instruction["modify_order_by_user_id"](
        user_order_id,
        modify_order_params,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_modify_order_ix(order_id, modify_order_params, sub_account_id=None)

Source code in src/driftpy/drift_client.py
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
def get_modify_order_ix(
    self,
    order_id: int,
    modify_order_params: ModifyOrderParams,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)],
    )

    return self.program.instruction["modify_order"](
        order_id,
        modify_order_params,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_open_position_ix(direction, amount, market_index, sub_account_id=None, limit_price=0, ioc=False)

Source code in src/driftpy/drift_client.py
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
@deprecated
def get_open_position_ix(
    self,
    direction: PositionDirection,
    amount: int,
    market_index: int,
    sub_account_id: int = None,
    limit_price: int = 0,
    ioc: bool = False,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    order_params = OrderParams(
        order_type=OrderType.Market(),
        direction=direction,
        market_index=market_index,
        base_asset_amount=amount,
        price=limit_price,
    )

    ix = self.get_place_and_take_perp_order_ix(
        order_params, sub_account_id=sub_account_id
    )
    return ix

get_oracle_price_data(oracle_id)

Source code in src/driftpy/drift_client.py
438
439
440
441
442
443
444
445
446
447
448
449
def get_oracle_price_data(self, oracle_id: str) -> Optional[OraclePriceData]:
    if self.account_subscriber is None:
        return None

    data_and_slot = self.account_subscriber.get_oracle_price_data_and_slot(
        oracle_id
    )

    if data_and_slot is None:
        return None

    return getattr(data_and_slot, "data", None)

get_oracle_price_data_for_perp_market(market_index)

Source code in src/driftpy/drift_client.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def get_oracle_price_data_for_perp_market(
    self, market_index: int
) -> Optional[OraclePriceData]:
    if self.account_subscriber is None:
        raise ValueError("No account subscriber found")

    if isinstance(self.account_subscriber, DemoDriftClientAccountSubscriber):
        raise ValueError("Cannot get market for demo subscriber")

    data = self.account_subscriber.get_oracle_price_data_and_slot_for_perp_market(
        market_index
    )
    if isinstance(data, DataAndSlot):
        return getattr(
            data,
            "data",
            None,
        )

    return data

get_oracle_price_data_for_spot_market(market_index)

Source code in src/driftpy/drift_client.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def get_oracle_price_data_for_spot_market(
    self, market_index: int
) -> Optional[OraclePriceData]:
    if self.account_subscriber is None:
        return None
    if isinstance(self.account_subscriber, DemoDriftClientAccountSubscriber):
        raise ValueError("Cannot get market for demo subscriber")

    data = self.account_subscriber.get_oracle_price_data_and_slot_for_spot_market(
        market_index
    )
    if isinstance(data, DataAndSlot):
        return getattr(
            data,
            "data",
            None,
        )

    return data

get_perp_market_account(market_index)

Source code in src/driftpy/drift_client.py
418
419
420
421
422
423
424
def get_perp_market_account(self, market_index: int) -> Optional[PerpMarketAccount]:
    if self.account_subscriber is None:
        raise ValueError("No account subscriber found")
    perp_market_and_slot = self.account_subscriber.get_perp_market_and_slot(
        market_index
    )
    return getattr(perp_market_and_slot, "data", None)

get_perp_market_accounts()

Source code in src/driftpy/drift_client.py
3742
3743
3744
3745
3746
3747
def get_perp_market_accounts(self) -> list[PerpMarketAccount]:
    return [
        value.data
        for value in self.account_subscriber.get_market_accounts_and_slots()
        if value is not None
    ]

get_perp_position(market_index, sub_account_id=None)

Source code in src/driftpy/drift_client.py
2427
2428
2429
2430
2431
2432
2433
def get_perp_position(
    self,
    market_index: int,
    sub_account_id: int = None,
) -> Optional[PerpPosition]:
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
    return self.get_user(sub_account_id).get_perp_position(market_index)

get_place_and_make_signed_msg_perp_order_ixs(signed_msg_order_params, signed_msg_order_uuid, taker_info, order_params, referrer_info=None, sub_account_id=None, preceding_ixs=[], override_ix_count=None, include_high_leverage_mode_config=False) async

Source code in src/driftpy/drift_client.py
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
async def get_place_and_make_signed_msg_perp_order_ixs(
    self,
    signed_msg_order_params: SignedMsgOrderParams,
    signed_msg_order_uuid: bytes,
    taker_info: dict,
    order_params: OrderParams,
    referrer_info: Optional[ReferrerInfo] = None,
    sub_account_id: Optional[int] = None,
    preceding_ixs: list[Instruction] = [],
    override_ix_count: Optional[int] = None,
    include_high_leverage_mode_config: Optional[bool] = False,
) -> list[Instruction]:
    (
        signed_msg_order_signature_ix,
        place_taker_signed_msg_perp_order_ix,
    ) = await self.get_place_signed_msg_taker_perp_order_ixs(
        signed_msg_order_params,
        order_params.market_index,
        taker_info,
        None,
        preceding_ixs,
        override_ix_count,
    )

    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
    user_stats_public_key = self.get_user_stats_public_key()
    user = self.get_user_account_public_key(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[
            self.get_user_account(sub_account_id),
            taker_info["taker_user_account"],
        ],
        writable_perp_market_indexes=[order_params.market_index],
    )

    if include_high_leverage_mode_config:
        remaining_accounts.append(
            AccountMeta(
                pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                is_writable=True,
                is_signer=False,
            )
        )

    if referrer_info:
        remaining_accounts.append(
            AccountMeta(
                pubkey=referrer_info.referrer, is_writable=True, is_signer=False
            )
        )
        remaining_accounts.append(
            AccountMeta(
                pubkey=referrer_info.referrer_stats,
                is_writable=True,
                is_signer=False,
            )
        )

    place_and_make_ix = self.program.instruction[
        "place_and_make_signed_msg_perp_order"
    ](
        order_params,
        signed_msg_order_uuid,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user,
                "user_stats": user_stats_public_key,
                "taker": taker_info["taker"],
                "taker_stats": taker_info["taker_stats"],
                "authority": self.wallet.public_key,
                "taker_signed_msg_user_orders": get_signed_msg_user_account_public_key(
                    self.program_id, taker_info["taker_user_account"].authority
                ),
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return [
        signed_msg_order_signature_ix,
        place_taker_signed_msg_perp_order_ix,
        place_and_make_ix,
    ]

get_place_and_take_perp_order_ix(order_params, maker_info=None, referrer_info=None, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
def get_place_and_take_perp_order_ix(
    self,
    order_params: OrderParams,
    maker_info: Union[MakerInfo, List[MakerInfo]] = None,
    referrer_info: ReferrerInfo = None,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    order_params.set_perp()

    user_account_public_key = self.get_user_account_public_key(sub_account_id)

    maker_infos = (
        maker_info
        if isinstance(maker_info, list)
        else [maker_info]
        if maker_info
        else []
    )

    user_accounts = [self.get_user_account(sub_account_id)]
    for maker_info in maker_infos:
        user_accounts.append(maker_info.maker_user_account)

    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[order_params.market_index],
        user_accounts=user_accounts,
    )

    if OrderParamsBitFlag.is_update_high_leverage_mode(order_params.bit_flags):
        remaining_accounts.append(
            AccountMeta(
                pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                is_writable=True,
                is_signer=False,
            )
        )

    for maker_info in maker_infos:
        remaining_accounts.append(
            AccountMeta(pubkey=maker_info.maker, is_signer=False, is_writable=True)
        )
        remaining_accounts.append(
            AccountMeta(
                pubkey=maker_info.maker_stats, is_signer=False, is_writable=True
            )
        )

    if referrer_info is not None:
        referrer_is_maker = referrer_info.referrer in [
            maker_info.maker for maker_info in maker_infos
        ]
        if not referrer_is_maker:
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer, is_signer=False, is_writable=True
                )
            )
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer_stats,
                    is_signer=False,
                    is_writable=True,
                )
            )

    return self.program.instruction["place_and_take_perp_order"](
        order_params,
        None,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_account_public_key,
                "user_stats": self.get_user_stats_public_key(),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_place_and_take_spot_order_ix(order_params, fulfillment_config=None, maker_info=None, referrer_info=None, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
def get_place_and_take_spot_order_ix(
    self,
    order_params: OrderParams,
    fulfillment_config: Optional[
        Union[SerumV3FulfillmentConfigAccount, PhoenixV1FulfillmentConfigAccount]
    ] = None,
    maker_info: Union[MakerInfo, List[MakerInfo]] = None,
    referrer_info: ReferrerInfo = None,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    order_params.set_spot()

    user_account_public_key = self.get_user_account_public_key(sub_account_id)

    user_accounts = [self.get_user_account(sub_account_id)]
    maker_infos = (
        maker_info
        if isinstance(maker_info, list)
        else [maker_info]
        if maker_info
        else []
    )
    for maker_info in maker_infos:
        user_accounts.append(maker_info.maker_user_account)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=user_accounts,
        writable_spot_market_indexes=[
            order_params.market_index,
            QUOTE_SPOT_MARKET_INDEX,
        ],
    )

    for maker_info in maker_infos:
        remaining_accounts.append(
            AccountMeta(pubkey=maker_info.maker, is_signer=False, is_writable=True)
        )
        remaining_accounts.append(
            AccountMeta(
                pubkey=maker_info.maker_stats, is_signer=False, is_writable=True
            )
        )

    if referrer_info is not None:
        referrer_is_maker = (
            referrer_info.referrer == maker_info.maker if maker_info else False
        )
        if not referrer_is_maker:
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer, is_signer=False, is_writable=True
                )
            )
            remaining_accounts.append(
                AccountMeta(
                    pubkey=referrer_info.referrer_stats,
                    is_signer=False,
                    is_writable=True,
                )
            )

    self.add_spot_fulfillment_accounts(
        order_params.market_index, remaining_accounts, fulfillment_config
    )

    return self.program.instruction["place_and_take_spot_order"](
        order_params,
        fulfillment_config,
        None,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_account_public_key,
                "user_stats": self.get_user_stats_public_key(),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_place_orders_ix(order_params, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
def get_place_orders_ix(
    self,
    order_params: List[OrderParams],
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    user_account_public_key = self.get_user_account_public_key(sub_account_id)
    user_stats_public_key = self.get_user_stats_public_key()

    readable_perp_market_indexes = []
    readable_spot_market_indexes = []
    for order_param in order_params:
        order_param.check_market_type()

        if is_variant(order_param.market_type, "Perp"):
            readable_perp_market_indexes.append(order_param.market_index)
        else:
            if len(readable_spot_market_indexes) == 0:
                readable_spot_market_indexes.append(QUOTE_SPOT_MARKET_INDEX)

            readable_spot_market_indexes.append(order_param.market_index)

    remaining_accounts = self.get_remaining_accounts(
        readable_perp_market_indexes=readable_perp_market_indexes,
        readable_spot_market_indexes=readable_spot_market_indexes,
        user_accounts=[self.get_user_account(sub_account_id)],
    )

    ix = self.program.instruction["place_orders"](
        order_params,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_account_public_key,
                "userStats": user_stats_public_key,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return ix

get_place_perp_order_ix(order_params, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
def get_place_perp_order_ix(
    self,
    order_params: OrderParams,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    order_params.set_perp()
    user_account_public_key = self.get_user_account_public_key(sub_account_id)
    user_stats_public_key = self.get_user_stats_public_key()
    remaining_accounts = self.get_remaining_accounts(
        readable_perp_market_indexes=[order_params.market_index],
        user_accounts=[self.get_user_account(sub_account_id)],
    )

    if OrderParamsBitFlag.is_update_high_leverage_mode(order_params.bit_flags):
        remaining_accounts.append(
            AccountMeta(
                pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                is_writable=True,
                is_signer=False,
            )
        )

    ix = self.program.instruction["place_perp_order"](
        order_params,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_account_public_key,
                "userStats": user_stats_public_key,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return ix

get_place_signed_msg_taker_perp_order_ixs(signed_msg_order_params, market_index, taker_info, authority=None, preceding_ixs=[], override_ix_count=None, include_high_leverage_mode_config=False) async

Source code in src/driftpy/drift_client.py
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
async def get_place_signed_msg_taker_perp_order_ixs(
    self,
    signed_msg_order_params: Union[dict, SignedMsgOrderParams],
    market_index: int,
    taker_info: dict,
    authority: Optional[Pubkey] = None,
    preceding_ixs: list[Instruction] = [],
    override_ix_count: Optional[int] = None,
    include_high_leverage_mode_config: Optional[bool] = False,
):
    if not authority and not taker_info["taker_user_account"]:
        raise Exception("authority or taker_user_account must be provided")

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[taker_info["taker_user_account"]],
        readable_perp_market_indexes=[market_index],
    )

    if include_high_leverage_mode_config:
        remaining_accounts.append(
            AccountMeta(
                pubkey=get_high_leverage_mode_config_public_key(self.program_id),
                is_writable=True,
                is_signer=False,
            )
        )
    authority_to_use = authority or taker_info["taker_user_account"].authority

    print(f"Signed msg order params: {signed_msg_order_params}")
    if isinstance(signed_msg_order_params, SignedMsgOrderParams):
        signed_msg_order_params = {
            "signature": signed_msg_order_params.signature,
            "order_params": signed_msg_order_params.order_params,
        }

    message_length_buffer = int.to_bytes(
        len(signed_msg_order_params["order_params"]), 2, "little"
    )

    signed_msg_ix_data = b"".join(
        [
            signed_msg_order_params["signature"],
            bytes(authority_to_use),
            message_length_buffer,
            signed_msg_order_params["order_params"],
        ]
    )

    signed_msg_order_params_signature_ix = create_minimal_ed25519_verify_ix(
        override_ix_count or len(preceding_ixs) + 1,
        12,
        signed_msg_ix_data,
        0,
    )

    is_delegate_signer = False
    if (
        taker_info.get("signing_authority")
        and taker_info.get("taker_user_account")
        and taker_info["taker_user_account"].delegate
        and taker_info["signing_authority"]
        == taker_info["taker_user_account"].delegate
    ):
        is_delegate_signer = True

    sysvar_pubkey = Pubkey.from_string(
        "Sysvar1nstructions1111111111111111111111111"
    )

    place_taker_signed_msg_perp_order_ix = self.program.instruction[
        "place_signed_msg_taker_order"
    ](
        signed_msg_ix_data,
        is_delegate_signer,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": taker_info["taker"],
                "user_stats": taker_info["taker_stats"],
                "signed_msg_user_orders": get_signed_msg_user_account_public_key(
                    self.program_id,
                    taker_info["taker_user_account"].authority,
                ),
                "authority": self.wallet.public_key,
                "ix_sysvar": sysvar_pubkey,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return [
        signed_msg_order_params_signature_ix,
        place_taker_signed_msg_perp_order_ix,
    ]

get_place_spot_order_ix(order_params, sub_account_id=None)

Source code in src/driftpy/drift_client.py
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
def get_place_spot_order_ix(
    self,
    order_params: OrderParams,
    sub_account_id: int = None,
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    order_params.set_spot()
    user_account_public_key = self.get_user_account_public_key(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        readable_spot_market_indexes=[
            QUOTE_SPOT_MARKET_INDEX,
            order_params.market_index,
        ],
        user_accounts=[self.get_user_account(sub_account_id)],
    )

    ix = self.program.instruction["place_spot_order"](
        order_params,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_account_public_key,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return ix

get_quote_spot_market_account()

Source code in src/driftpy/drift_client.py
432
433
434
435
436
def get_quote_spot_market_account(self) -> Optional[SpotMarketAccount]:
    spot_market_and_slot = self.account_subscriber.get_spot_market_and_slot(
        QUOTE_SPOT_MARKET_INDEX
    )
    return getattr(spot_market_and_slot, "data", None)

get_remaining_accounts(user_accounts=(), writable_perp_market_indexes=(), writable_spot_market_indexes=(), readable_spot_market_indexes=(), readable_perp_market_indexes=())

Source code in src/driftpy/drift_client.py
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
def get_remaining_accounts(
    self,
    user_accounts: list[UserAccount] = (),
    writable_perp_market_indexes: list[int] = (),
    writable_spot_market_indexes: list[int] = (),
    readable_spot_market_indexes: list[int] = (),
    readable_perp_market_indexes: list[int] = (),
):
    (
        oracle_map,
        spot_market_map,
        perp_market_map,
    ) = self.get_remaining_accounts_for_users(user_accounts)

    last_user_slot = self.get_user().get_user_account_and_slot().slot
    for perp_market_index, slot in self.last_perp_market_seen_cache.items():
        if slot > last_user_slot:
            self.add_perp_market_to_remaining_account_maps(
                perp_market_index,
                False,
                oracle_map,
                spot_market_map,
                perp_market_map,
            )

    for spot_market_index, slot in self.last_spot_market_seen_cache.items():
        if slot > last_user_slot:
            self.add_spot_market_to_remaining_account_maps(
                spot_market_index, False, oracle_map, spot_market_map
            )

    for perp_market_index in readable_perp_market_indexes:
        self.add_perp_market_to_remaining_account_maps(
            perp_market_index, False, oracle_map, spot_market_map, perp_market_map
        )

    for spot_market_index in readable_spot_market_indexes:
        self.add_spot_market_to_remaining_account_maps(
            spot_market_index, False, oracle_map, spot_market_map
        )

    for perp_market_index in writable_perp_market_indexes:
        self.add_perp_market_to_remaining_account_maps(
            perp_market_index, True, oracle_map, spot_market_map, perp_market_map
        )

    for spot_market_index in writable_spot_market_indexes:
        self.add_spot_market_to_remaining_account_maps(
            spot_market_index, True, oracle_map, spot_market_map
        )

    remaining_accounts = [
        *oracle_map.values(),
        *spot_market_map.values(),
        *perp_market_map.values(),
    ]

    return remaining_accounts

get_remaining_accounts_for_users(user_accounts)

Source code in src/driftpy/drift_client.py
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
def get_remaining_accounts_for_users(
    self, user_accounts: list[UserAccount]
) -> (dict[str, AccountMeta], dict[int, AccountMeta], dict[int, AccountMeta]):
    oracle_map = {}
    spot_market_map = {}
    perp_market_map = {}

    for user_account in user_accounts:
        for spot_position in user_account.spot_positions:
            if not is_spot_position_available(spot_position):
                self.add_spot_market_to_remaining_account_maps(
                    spot_position.market_index, False, oracle_map, spot_market_map
                )

            if spot_position.open_asks != 0 or spot_position.open_bids != 0:
                self.add_spot_market_to_remaining_account_maps(
                    QUOTE_SPOT_MARKET_INDEX, False, oracle_map, spot_market_map
                )

        for position in user_account.perp_positions:
            if not is_available(position):
                self.add_perp_market_to_remaining_account_maps(
                    position.market_index,
                    False,
                    oracle_map,
                    spot_market_map,
                    perp_market_map,
                )

    return oracle_map, spot_market_map, perp_market_map

get_remove_insurance_fund_stake_ix(spot_market_index, user_token_account=None)

Source code in src/driftpy/drift_client.py
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
def get_remove_insurance_fund_stake_ix(
    self, spot_market_index: int, user_token_account: Pubkey = None
):
    ra = self.get_remaining_accounts(
        writable_spot_market_indexes=[spot_market_index],
    )

    user_token_account = (
        user_token_account
        if user_token_account is not None
        else self.get_associated_token_account_public_key(spot_market_index)
    )

    return self.program.instruction["remove_insurance_fund_stake"](
        spot_market_index,
        ctx=Context(
            accounts={
                "state": get_state_public_key(self.program_id),
                "spot_market": get_spot_market_public_key(
                    self.program_id, spot_market_index
                ),
                "insurance_fund_stake": get_insurance_fund_stake_public_key(
                    self.program_id, self.authority, spot_market_index
                ),
                "user_stats": get_user_stats_account_public_key(
                    self.program_id, self.authority
                ),
                "authority": self.wallet.public_key,
                "insurance_fund_vault": get_insurance_fund_vault_public_key(
                    self.program_id, spot_market_index
                ),
                "drift_signer": self.get_signer_public_key(self.program_id),
                "user_token_account": user_token_account,
                "token_program": TOKEN_PROGRAM_ID,
            },
            remaining_accounts=ra,
        ),
    )

get_remove_liquidity_ix(amount, market_index, sub_account_id=None)

Source code in src/driftpy/drift_client.py
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
def get_remove_liquidity_ix(
    self, amount: int, market_index: int, sub_account_id: int = None
):
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[market_index],
        user_accounts=[self.get_user_account(sub_account_id)],
    )
    user_account_public_key = self.get_user_account_public_key(sub_account_id)

    return self.program.instruction["remove_perp_lp_shares"](
        amount,
        market_index,
        ctx=Context(
            accounts={
                "state": get_state_public_key(self.program_id),
                "user": user_account_public_key,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_request_remove_insurance_fund_stake_ix(spot_market_index, amount)

Source code in src/driftpy/drift_client.py
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
def get_request_remove_insurance_fund_stake_ix(
    self,
    spot_market_index: int,
    amount: int,
):
    ra = self.get_remaining_accounts(
        writable_spot_market_indexes=[spot_market_index],
    )

    return self.program.instruction["request_remove_insurance_fund_stake"](
        spot_market_index,
        amount,
        ctx=Context(
            accounts={
                "spot_market": get_spot_market_public_key(
                    self.program_id, spot_market_index
                ),
                "insurance_fund_stake": get_insurance_fund_stake_public_key(
                    self.program_id, self.authority, spot_market_index
                ),
                "user_stats": get_user_stats_account_public_key(
                    self.program_id, self.authority
                ),
                "authority": self.wallet.public_key,
                "insurance_fund_vault": get_insurance_fund_vault_public_key(
                    self.program_id, spot_market_index
                ),
            },
            remaining_accounts=ra,
        ),
    )

get_reset_sequence_number_ix(sequence_number, subaccount=0)

Source code in src/driftpy/drift_client.py
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
def get_reset_sequence_number_ix(
    self, sequence_number: int, subaccount: int = 0
) -> Instruction:
    if self.enforce_tx_sequencing is False:
        raise ValueError("tx sequencing is disabled")
    return self.sequence_enforcer_program.instruction["reset_sequence_number"](
        sequence_number,
        ctx=Context(
            accounts={
                "sequence_account": self.sequence_address_by_subaccount[subaccount],
                "authority": self.wallet.public_key,
            }
        ),
    )

get_resolve_perp_bankruptcy_ix(user_authority, market_index, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def get_resolve_perp_bankruptcy_ix(
    self,
    user_authority: Pubkey,
    market_index: int,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    user_pk = get_user_account_public_key(
        self.program_id, user_authority, user_sub_account_id
    )
    user_stats_pk = get_user_stats_account_public_key(
        self.program_id,
        user_authority,
    )

    liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
    liq_pk = self.get_user_account_public_key(liq_sub_account_id)
    liq_stats_pk = self.get_user_stats_public_key()

    user_account = await self.program.account["User"].fetch(user_pk)
    liq_user_account = self.get_user_account(liq_sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[market_index],
        user_accounts=[user_account, liq_user_account],
    )

    if_vault = get_insurance_fund_vault_public_key(self.program_id, market_index)
    spot_vault = get_spot_market_vault_public_key(self.program_id, market_index)
    dc_signer = self.get_signer_public_key(self.program_id)

    return self.program.instruction["resolve_perp_bankruptcy"](
        QUOTE_SPOT_MARKET_INDEX,
        market_index,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
                "user": user_pk,
                "user_stats": user_stats_pk,
                "liquidator": liq_pk,
                "liquidator_stats": liq_stats_pk,
                "spot_market_vault": spot_vault,
                "insurance_fund_vault": if_vault,
                "drift_signer": dc_signer,
                "token_program": TOKEN_PROGRAM_ID,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_resolve_spot_bankruptcy_ix(user_authority, spot_market_index, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def get_resolve_spot_bankruptcy_ix(
    self,
    user_authority: Pubkey,
    spot_market_index: int,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    user_pk = get_user_account_public_key(
        self.program_id, user_authority, user_sub_account_id
    )
    user_stats_pk = get_user_stats_account_public_key(
        self.program_id,
        user_authority,
    )

    liq_sub_account_id = self.get_sub_account_id_for_ix(liq_sub_account_id)
    liq_pk = self.get_user_account_public_key(liq_sub_account_id)
    liq_stats_pk = self.get_user_stats_public_key()

    user_account = await self.program.account["User"].fetch(user_pk)
    liq_user_account = self.get_user_account(liq_sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_spot_market_indexes=[spot_market_index],
        user_accounts=[user_account, liq_user_account],
    )

    if_vault = get_insurance_fund_vault_public_key(
        self.program_id, spot_market_index
    )
    spot_vault = get_spot_market_vault_public_key(
        self.program_id, spot_market_index
    )
    dc_signer = self.get_signer_public_key(self.program_id)

    return self.program.instruction["resolve_spot_bankruptcy"](
        spot_market_index,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
                "user": user_pk,
                "user_stats": user_stats_pk,
                "liquidator": liq_pk,
                "liquidator_stats": liq_stats_pk,
                "spot_market_vault": spot_vault,
                "insurance_fund_vault": if_vault,
                "drift_signer": dc_signer,
                "token_program": TOKEN_PROGRAM_ID,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_revert_fill_ix()

Source code in src/driftpy/drift_client.py
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
def get_revert_fill_ix(self):
    filler_pubkey = self.get_user_account_public_key()
    filler_stats_pubkey = self.get_user_stats_public_key()

    return self.program.instruction["revert_fill"](
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "filler": filler_pubkey,
                "filler_stats": filler_stats_pubkey,
                "authority": self.wallet.public_key,
            }
        )
    )

get_sequence_init_ix(subaccount=0)

Source code in src/driftpy/drift_client.py
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
def get_sequence_init_ix(self, subaccount: int = 0) -> Instruction:
    if self.enforce_tx_sequencing is False:
        raise ValueError("tx sequencing is disabled")
    return self.sequence_enforcer_program.instruction["initialize"](
        self.sequence_bump_by_subaccount[subaccount],
        str(subaccount),
        ctx=Context(
            accounts={
                "sequence_account": self.sequence_address_by_subaccount[subaccount],
                "authority": self.wallet.public_key,
                "system_program": ID,
            }
        ),
    )

get_settle_expired_market_ix(market_index) async

Source code in src/driftpy/drift_client.py
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
async def get_settle_expired_market_ix(
    self,
    market_index: int,
):
    market = await get_perp_market_account(self.program, market_index)

    market_account_infos = [
        AccountMeta(
            pubkey=market.pubkey,
            is_writable=True,
            is_signer=False,
        )
    ]

    oracle_account_infos = [
        AccountMeta(
            pubkey=market.amm.oracle,
            is_writable=False,
            is_signer=False,
        )
    ]

    spot_pk = get_spot_market_public_key(self.program_id, QUOTE_SPOT_MARKET_INDEX)
    spot_account_infos = [
        AccountMeta(
            pubkey=spot_pk,
            is_writable=True,
            is_signer=False,
        )
    ]

    remaining_accounts = (
        oracle_account_infos + spot_account_infos + market_account_infos
    )

    return self.program.instruction["settle_expired_market"](
        market_index,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_settle_lp_ix(settlee_user_account_public_key, market_index) async

Source code in src/driftpy/drift_client.py
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
async def get_settle_lp_ix(
    self,
    settlee_user_account_public_key: Pubkey,
    market_index: int,
):
    settlee_user_account = await self.program.account["User"].fetch(
        settlee_user_account_public_key
    )

    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[market_index],
        user_accounts=[settlee_user_account],
    )

    return self.program.instruction["settle_lp"](
        market_index,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": settlee_user_account_public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_settle_pnl_ix(settlee_user_public_key, settlee_user_account, market_index)

Source code in src/driftpy/drift_client.py
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
def get_settle_pnl_ix(
    self,
    settlee_user_public_key: Pubkey,
    settlee_user_account: UserAccount,
    market_index: int,
):
    remaining_accounts = self.get_remaining_accounts(
        writable_perp_market_indexes=[market_index],
        writable_spot_market_indexes=[QUOTE_SPOT_MARKET_INDEX],
        user_accounts=[settlee_user_account],
    )

    instruction = self.program.instruction["settle_pnl"](
        market_index,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
                "user": settlee_user_public_key,
                "spot_market_vault": get_spot_market_vault_public_key(
                    self.program_id, QUOTE_SPOT_MARKET_INDEX
                ),
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return instruction

get_settle_pnl_ixs(users, market_indexes)

Source code in src/driftpy/drift_client.py
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
def get_settle_pnl_ixs(
    self, users: dict[Pubkey, UserAccount], market_indexes: list[int]
) -> list[Instruction]:
    ixs: list[Instruction] = []
    for pubkey, account in users.items():
        for market_index in market_indexes:
            ix = self.get_settle_pnl_ix(pubkey, account, market_index)
            ixs.append(ix)

    return ixs

get_signer_public_key()

Source code in src/driftpy/drift_client.py
393
394
395
396
397
398
def get_signer_public_key(self) -> Pubkey:
    if self.signer_public_key:
        return self.signer_public_key

    self.signer_public_key = get_drift_client_signer_public_key(self.program_id)
    return self.signer_public_key

get_spot_market_account(market_index)

Source code in src/driftpy/drift_client.py
426
427
428
429
430
def get_spot_market_account(self, market_index: int) -> Optional[SpotMarketAccount]:
    spot_market_and_slot = self.account_subscriber.get_spot_market_and_slot(
        market_index
    )
    return getattr(spot_market_and_slot, "data", None)

get_spot_market_accounts()

Source code in src/driftpy/drift_client.py
3749
3750
3751
3752
3753
3754
def get_spot_market_accounts(self) -> list[SpotMarketAccount]:
    return [
        value.data
        for value in self.account_subscriber.get_spot_market_accounts_and_slots()
        if value is not None
    ]

get_spot_position(market_index, sub_account_id=None)

Source code in src/driftpy/drift_client.py
2418
2419
2420
2421
2422
2423
2424
2425
def get_spot_position(
    self,
    market_index: int,
    sub_account_id: int = None,
) -> Optional[SpotPosition]:
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    return self.get_user(sub_account_id).get_spot_position(market_index)

get_state_account()

Source code in src/driftpy/drift_client.py
414
415
416
def get_state_account(self) -> Optional[StateAccount]:
    state_and_slot = self.account_subscriber.get_state_account_and_slot()
    return getattr(state_and_slot, "data", None)

get_state_public_key()

Source code in src/driftpy/drift_client.py
390
391
def get_state_public_key(self):
    return get_state_public_key(self.program_id)

get_sub_account_id_for_ix(sub_account_id=None)

Source code in src/driftpy/drift_client.py
502
503
504
505
def get_sub_account_id_for_ix(self, sub_account_id: Optional[int] = None):
    return (
        sub_account_id if sub_account_id is not None else self.active_sub_account_id
    )

get_swap_flash_loan_ix(out_market_index, in_market_index, amount_in, in_ata, out_ata, limit_price=0, reduce_only=None, user_account_public_key=None) async

Source code in src/driftpy/drift_client.py
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
async def get_swap_flash_loan_ix(
    self,
    out_market_index: int,
    in_market_index: int,
    amount_in: int,
    in_ata: Pubkey,
    out_ata: Pubkey,
    limit_price: Optional[int] = 0,
    reduce_only: Optional[SwapReduceOnly] = None,
    user_account_public_key: Optional[Pubkey] = None,
):
    user_public_key_to_use = (
        user_account_public_key
        if user_account_public_key
        else (self.get_user_account_public_key())
    )

    user_accounts = []

    try:
        user_accounts.append(self.get_user().get_user_account_and_slot().data)
    except:
        pass  # ignore

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=user_accounts,
        writable_spot_market_indexes=[out_market_index, in_market_index],
        readable_spot_market_indexes=[QUOTE_SPOT_MARKET_INDEX],
    )

    out_market = self.get_spot_market_account(out_market_index)
    in_market = self.get_spot_market_account(in_market_index)

    sysvar_pubkey = Pubkey.from_string(
        "Sysvar1nstructions1111111111111111111111111"
    )

    begin_swap_ix = self.program.instruction["begin_swap"](
        in_market_index,
        out_market_index,
        amount_in,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_public_key_to_use,
                "user_stats": self.get_user_stats_public_key(),
                "authority": self.wallet.public_key,
                "out_spot_market_vault": out_market.vault,
                "in_spot_market_vault": in_market.vault,
                "in_token_account": in_ata,
                "out_token_account": out_ata,
                "token_program": TOKEN_PROGRAM_ID,
                "drift_signer": self.get_state_account().signer,
                "instructions": sysvar_pubkey,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    end_swap_ix = self.program.instruction["end_swap"](
        in_market_index,
        out_market_index,
        limit_price,
        reduce_only,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": user_public_key_to_use,
                "user_stats": self.get_user_stats_public_key(),
                "authority": self.wallet.public_key,
                "out_spot_market_vault": out_market.vault,
                "in_spot_market_vault": in_market.vault,
                "in_token_account": in_ata,
                "out_token_account": out_ata,
                "token_program": TOKEN_PROGRAM_ID,
                "drift_signer": self.get_state_account().signer,
                "instructions": sysvar_pubkey,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return begin_swap_ix, end_swap_ix

get_transfer_deposit_ix(amount, market_index, from_sub_account_id, to_sub_account_id) async

Source code in src/driftpy/drift_client.py
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
async def get_transfer_deposit_ix(
    self,
    amount: int,
    market_index: int,
    from_sub_account_id: int,
    to_sub_account_id: int,
):
    from_user_public_key = self.get_user_account_public_key(from_sub_account_id)
    to_user_public_key = self.get_user_account_public_key(to_sub_account_id)

    if from_sub_account_id not in self.users:
        from_user_account = await self.program.account["User"].fetch(
            from_user_public_key
        )
    else:
        from_user_account = self.get_user_account(from_sub_account_id)

    if to_sub_account_id not in self.users:
        to_user_account = await self.program.account["User"].fetch(
            to_user_public_key
        )
    else:
        to_user_account = self.get_user_account(to_sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        writable_spot_market_indexes=[
            market_index,
        ],
        user_accounts=[from_user_account, to_user_account],
    )

    ix = self.program.instruction["transfer_deposit"](
        market_index,
        amount,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user_stats": self.get_user_stats_public_key(),
                "from_user": from_user_public_key,
                "to_user": to_user_public_key,
                "authority": self.wallet.public_key,
                "spot_market_vault": self.get_spot_market_account(
                    market_index
                ).vault,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

    return ix

get_trigger_order_ix(user_account_pubkey, user_account, order, filler_pubkey=None)

Source code in src/driftpy/drift_client.py
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
def get_trigger_order_ix(
    self,
    user_account_pubkey: Pubkey,
    user_account: UserAccount,
    order: Order,
    filler_pubkey: Optional[Pubkey] = None,
):
    filler = filler_pubkey or self.get_user_account_public_key()

    if is_variant(order.market_type, "Perp"):
        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[user_account],
            writable_perp_market_indexes=[order.market_index],
        )
    else:
        remaining_accounts = self.get_remaining_accounts(
            user_accounts=[user_account],
            writable_spot_market_indexes=[
                order.market_index,
                QUOTE_SPOT_MARKET_INDEX,
            ],
        )

    return self.program.instruction["trigger_order"](
        order.order_id,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "filler": filler,
                "user": user_account_pubkey,
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_update_amm_ix(market_indexs)

Source code in src/driftpy/drift_client.py
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
def get_update_amm_ix(
    self,
    market_indexs: list[int],
):
    n = len(market_indexs)
    for _ in range(5 - n):
        market_indexs.append(100)

    market_infos = []
    oracle_infos = []
    for idx in market_indexs:
        if idx != 100:
            market = self.get_perp_market_account(idx)
            market_infos.append(
                AccountMeta(
                    pubkey=market.pubkey,
                    is_signer=False,
                    is_writable=True,
                )
            )
            oracle_infos.append(
                AccountMeta(
                    pubkey=market.amm.oracle, is_signer=False, is_writable=False
                )
            )

    remaining_accounts = oracle_infos + market_infos

    return self.program.instruction["update_amms"](
        market_indexs,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_update_prelaunch_oracle_ix(market_index)

Source code in src/driftpy/drift_client.py
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
def get_update_prelaunch_oracle_ix(self, market_index: int):
    perp_market = self.get_perp_market_account(market_index)

    if not is_variant(perp_market.amm.oracle_source, "Prelaunch"):
        raise ValueError(f"wrong oracle source: {perp_market.amm.oracle_source}")

    return self.program.instruction["update_prelaunch_oracle"](
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "perp_market": perp_market.pubkey,
                "oracle": perp_market.amm.oracle,
            }
        )
    )

get_update_user_custom_margin_ratio_ix(margin_ratio, sub_account_id=None)

Source code in src/driftpy/drift_client.py
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
def get_update_user_custom_margin_ratio_ix(
    self,
    margin_ratio: int,
    sub_account_id: Optional[int] = None,
) -> Instruction:
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)],
    )

    return self.program.instruction["update_user_custom_margin_ratio"](
        sub_account_id,
        margin_ratio,
        ctx=Context(
            accounts={
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_update_user_margin_trading_enabled_ix(margin_trading_enabled, sub_account_id=None)

Source code in src/driftpy/drift_client.py
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
def get_update_user_margin_trading_enabled_ix(
    self,
    margin_trading_enabled: bool,
    sub_account_id: Optional[int] = None,
) -> Instruction:
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)],
    )

    return self.program.instruction["update_user_margin_trading_enabled"](
        sub_account_id,
        margin_trading_enabled,
        ctx=Context(
            accounts={
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
            },
            remaining_accounts=remaining_accounts,
        ),
    )

get_update_user_protected_maker_orders_ix(sub_account_id, protected_orders) async

Source code in src/driftpy/drift_client.py
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
async def get_update_user_protected_maker_orders_ix(
    self,
    sub_account_id: int,
    protected_orders: bool,
):
    return self.program.instruction["update_user_protected_maker_orders"](
        sub_account_id,
        protected_orders,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "user": self.get_user_account_public_key(sub_account_id),
                "authority": self.wallet.public_key,
                "protected_maker_mode_config": get_protected_maker_mode_config_public_key(
                    self.program_id
                ),
            }
        ),
    )

get_user(sub_account_id=None)

Source code in src/driftpy/drift_client.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def get_user(self, sub_account_id: int | None = None) -> DriftUser:
    sub_account_id = (
        sub_account_id if sub_account_id is not None else self.active_sub_account_id
    )
    if sub_account_id not in self.sub_account_ids:
        raise KeyError(
            f"No sub account id {sub_account_id} found, need to include in `sub_account_ids` when initializing DriftClient"
        )

    if sub_account_id not in self.users:
        raise KeyError(
            f"No sub account id {sub_account_id} found, need to call `await DriftClient.subscribe()` first"
        )

    return self.users[sub_account_id]

get_user_account(sub_account_id=None)

Source code in src/driftpy/drift_client.py
373
374
def get_user_account(self, sub_account_id=None) -> UserAccount:
    return self.get_user(sub_account_id).get_user_account()

get_user_account_public_key(sub_account_id=None)

Source code in src/driftpy/drift_client.py
400
401
402
403
404
def get_user_account_public_key(self, sub_account_id=None) -> Pubkey:
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)
    return get_user_account_public_key(
        self.program_id, self.authority, sub_account_id
    )

get_user_stats(authority=None)

Source code in src/driftpy/drift_client.py
376
377
378
379
380
381
382
383
384
385
def get_user_stats(self, authority=None) -> DriftUserStats:
    if authority is None:
        authority = self.authority

    if authority not in self.user_stats:
        raise KeyError(
            f"No UserStats for {authority} found, need to call `await DriftClient.subscribe()` first"
        )

    return self.user_stats[authority]

get_user_stats_public_key()

Source code in src/driftpy/drift_client.py
406
407
def get_user_stats_public_key(self):
    return get_user_stats_account_public_key(self.program_id, self.authority)

get_withdraw_collateral_ix(amount, market_index, user_token_account, reduce_only=False, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def get_withdraw_collateral_ix(
    self,
    amount: int,
    market_index: int,
    user_token_account: Pubkey,
    reduce_only: bool = False,
    sub_account_id: Optional[int] = None,
) -> List[Instruction]:
    sub_account_id = self.get_sub_account_id_for_ix(sub_account_id)

    spot_market = self.get_spot_market_account(market_index)
    if not spot_market:
        raise Exception("Spot market account not found")

    is_sol_market = spot_market.mint == WRAPPED_SOL_MINT
    signer_authority = self.wallet.public_key

    create_WSOL_token_account = (
        is_sol_market and user_token_account == signer_authority
    )

    remaining_accounts = self.get_remaining_accounts(
        user_accounts=[self.get_user_account(sub_account_id)],
        writable_spot_market_indexes=[market_index],
    )
    dc_signer = self.get_signer_public_key()

    instructions = []
    temp_wsol_account_pubkey = None

    if create_WSOL_token_account:
        # Withdraw SOL to main wallet - create temporary WSOL account
        # Pass include_rent=False as rent is not needed for withdrawal destination
        (
            ixs,
            temp_wsol_account_pubkey,
        ) = await self.get_wrapped_sol_account_creation_ixs(amount, False)
        instructions.extend(ixs)
        user_token_account_for_ix = temp_wsol_account_pubkey
    else:
        account_info = await self.connection.get_account_info(user_token_account)
        if not account_info.value:
            create_ata_ix = (
                self.create_associated_token_account_idempotent_instruction(
                    account=user_token_account,
                    payer=signer_authority,
                    owner=signer_authority,
                    mint=spot_market.mint,
                )
            )
            instructions.append(create_ata_ix)
        user_token_account_for_ix = user_token_account

    withdraw_ix = self.program.instruction[
        "withdraw"
    ](
        market_index,
        amount,
        reduce_only,
        ctx=Context(
            accounts={
                "state": self.get_state_public_key(),
                "spot_market": spot_market.pubkey,
                "spot_market_vault": spot_market.vault,
                "drift_signer": dc_signer,
                "user": self.get_user_account_public_key(sub_account_id),
                "user_stats": self.get_user_stats_public_key(),
                "user_token_account": user_token_account_for_ix,  # Use correct account
                "authority": signer_authority,
                "token_program": TOKEN_PROGRAM_ID,
            },
            remaining_accounts=remaining_accounts,
        ),
    )
    instructions.append(withdraw_ix)

    if create_WSOL_token_account and temp_wsol_account_pubkey:
        close_account_params = CloseAccountParams(
            program_id=TOKEN_PROGRAM_ID,
            account=temp_wsol_account_pubkey,
            dest=signer_authority,
            owner=signer_authority,
        )
        close_account_ix = close_account(close_account_params)
        instructions.append(close_account_ix)

    return instructions

get_wrapped_sol_account_creation_ixs(amount, include_rent=True) async

Source code in src/driftpy/drift_client.py
 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
async def get_wrapped_sol_account_creation_ixs(
    self, amount: int, include_rent: bool = True
) -> (List[Instruction], Pubkey):
    wallet_pubkey = self.wallet.public_key
    seed = self.random_string(32)
    wrapped_sol_account = Pubkey.create_with_seed(
        wallet_pubkey, seed, TOKEN_PROGRAM_ID
    )
    result = {"ixs": [], "pubkey": wrapped_sol_account}

    LAMPORTS_PER_SOL: int = 1_000_000_000
    rent_space_lamports = int(LAMPORTS_PER_SOL / 100)
    lamports = amount + rent_space_lamports if include_rent else rent_space_lamports

    create_params = system_program.CreateAccountWithSeedParams(
        from_pubkey=wallet_pubkey,
        to_pubkey=wrapped_sol_account,
        base=wallet_pubkey,
        seed=seed,
        lamports=lamports,
        space=165,
        owner=TOKEN_PROGRAM_ID,
    )

    result["ixs"].append(system_program.create_account_with_seed(create_params))

    initialize_params = InitializeAccountParams(
        program_id=TOKEN_PROGRAM_ID,
        account=wrapped_sol_account,
        mint=WRAPPED_SOL_MINT,
        owner=wallet_pubkey,
    )

    result["ixs"].append(initialize_account(initialize_params))

    return result["ixs"], result["pubkey"]

init_sequence(subaccount=0) async

Source code in src/driftpy/drift_client.py
3912
3913
3914
3915
3916
3917
3918
async def init_sequence(self, subaccount: int = 0) -> Signature:
    try:
        sig = (await self.send_ixs([self.get_sequence_init_ix(subaccount)])).tx_sig
        self.sequence_initialized_by_subaccount[subaccount] = True
        return sig
    except Exception as e:
        print(f"WARNING: failed to initialize sequence: {e}")

initialize_insurance_fund_stake(spot_market_index) async

Source code in src/driftpy/drift_client.py
3098
3099
3100
3101
3102
3103
3104
3105
3106
async def initialize_insurance_fund_stake(
    self,
    spot_market_index: int,
):
    return (
        await self.send_ixs(
            self.get_initialize_insurance_fund_stake_ix(spot_market_index)
        )
    ).tx_sig

initialize_user(sub_account_id=0, name=None, referrer_info=None) async

intializes a drift user

Parameters:
  • sub_account_id (int, default: 0 ) –

    subaccount id to initialize. Defaults to 0.

Returns:
  • str( Signature ) –

    tx signature

Source code in src/driftpy/drift_client.py
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
async def initialize_user(
    self,
    sub_account_id: int = 0,
    name: str = None,
    referrer_info: ReferrerInfo = None,
) -> Signature:
    """intializes a drift user

    Args:
        sub_account_id (int, optional): subaccount id to initialize. Defaults to 0.

    Returns:
        str: tx signature
    """
    ixs = []
    if sub_account_id == 0:
        ixs.append(self.get_initialize_user_stats())
        if name is None:
            name = DEFAULT_USER_NAME

    if name is None:
        name = "Subaccount " + str(sub_account_id + 1)

    ix = self.get_initialize_user_instructions(sub_account_id, name, referrer_info)
    ixs.append(ix)
    return (await self.send_ixs(ixs)).tx_sig

liquidate_perp(user_authority, market_index, max_base_asset_amount, limit_price=None, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
async def liquidate_perp(
    self,
    user_authority: Pubkey,
    market_index: int,
    max_base_asset_amount: int,
    limit_price: Optional[int] = None,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            await self.get_liquidate_perp_ix(
                user_authority,
                market_index,
                max_base_asset_amount,
                limit_price,
                user_sub_account_id,
                liq_sub_account_id,
            )
        ]
    )
    self.last_perp_market_seen_cache[market_index] = tx_sig_and_slot.slot
    return tx_sig_and_slot.tx_sig

liquidate_perp_pnl_for_deposit(user_authority, perp_market_index, spot_market_index, max_pnl_transfer, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
async def liquidate_perp_pnl_for_deposit(
    self,
    user_authority: Pubkey,
    perp_market_index: int,
    spot_market_index: int,
    max_pnl_transfer: int,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        await self.get_liquidate_perp_pnl_for_deposit_ix(
            user_authority,
            perp_market_index,
            spot_market_index,
            max_pnl_transfer,
            user_sub_account_id,
            liq_sub_account_id,
        )
    )
    self.last_spot_market_seen_cache[spot_market_index] = tx_sig_and_slot.slot
    self.last_perp_market_seen_cache[perp_market_index] = tx_sig_and_slot.slot
    return tx_sig_and_slot.tx_sig

liquidate_spot(user_authority, asset_market_index, liability_market_index, max_liability_transfer, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
async def liquidate_spot(
    self,
    user_authority: Pubkey,
    asset_market_index: int,
    liability_market_index: int,
    max_liability_transfer: int,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            await self.get_liquidate_spot_ix(
                user_authority,
                asset_market_index,
                liability_market_index,
                max_liability_transfer,
                user_sub_account_id,
                liq_sub_account_id,
            )
        ]
    )
    self.last_spot_market_seen_cache[asset_market_index] = tx_sig_and_slot.slot
    self.last_spot_market_seen_cache[liability_market_index] = tx_sig_and_slot.slot
    return tx_sig_and_slot.tx_sig

load_sequence_info() async

Source code in src/driftpy/drift_client.py
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
async def load_sequence_info(self):
    for subaccount in self.sub_account_ids:
        address, bump = get_sequencer_public_key_and_bump(
            self.sequence_enforcer_pid, self.wallet.public_key, subaccount
        )
        try:
            sequence_account_raw = await self.sequence_enforcer_program.account[
                "SequenceAccount"
            ].fetch(address)
        except anchorpy.error.AccountDoesNotExistError:
            self.sequence_address_by_subaccount[subaccount] = address
            self.sequence_number_by_subaccount[subaccount] = 1
            self.sequence_bump_by_subaccount[subaccount] = bump
            self.sequence_initialized_by_subaccount[subaccount] = False
            continue
        sequence_account = cast(SequenceAccount, sequence_account_raw)
        self.sequence_number_by_subaccount[subaccount] = (
            sequence_account.sequence_num + 1
        )
        self.sequence_bump_by_subaccount[subaccount] = bump
        self.sequence_initialized_by_subaccount[subaccount] = True
        self.sequence_address_by_subaccount[subaccount] = address

modify_order(order_id, modify_order_params, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
async def modify_order(
    self,
    order_id: int,
    modify_order_params: ModifyOrderParams,
    sub_account_id: Optional[int] = None,
) -> Signature:
    return (
        await self.send_ixs(
            [
                self.get_modify_order_ix(
                    order_id, modify_order_params, sub_account_id
                )
            ],
        )
    ).tx_sig

modify_order_by_user_id(user_order_id, modify_order_params, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
async def modify_order_by_user_id(
    self,
    user_order_id: int,
    modify_order_params: ModifyOrderParams,
    sub_account_id: int = None,
) -> Signature:
    return (
        await self.send_ixs(
            [
                self.get_modify_order_by_user_id_ix(
                    user_order_id, modify_order_params, sub_account_id
                )
            ],
        )
    ).tx_sig

open_position(direction, amount, market_index, sub_account_id=None, limit_price=0, ioc=False) async

Source code in src/driftpy/drift_client.py
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
@deprecated
async def open_position(
    self,
    direction: PositionDirection,
    amount: int,
    market_index: int,
    sub_account_id: int = None,
    limit_price: int = 0,
    ioc: bool = False,
):
    return (
        await self.send_ixs(
            self.get_open_position_ix(
                direction,
                amount,
                market_index,
                sub_account_id,
                limit_price,
                ioc,
            ),
        )
    ).tx_sig

place_and_make_signed_msg_perp_order(signed_msg_order_params, signed_msg_order_uuid, taker_info, order_params) async

Source code in src/driftpy/drift_client.py
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
async def place_and_make_signed_msg_perp_order(
    self,
    signed_msg_order_params: SignedMsgOrderParams,
    signed_msg_order_uuid: bytes,
    taker_info: dict,
    order_params: OrderParams,
):
    ixs = await self.get_place_and_make_signed_msg_perp_order_ixs(
        signed_msg_order_params,
        signed_msg_order_uuid,
        taker_info,
        order_params,
    )
    lookup_tables = await self.fetch_market_lookup_table_accounts()
    result = await self.send_ixs(ixs, lookup_tables=lookup_tables)
    self.last_perp_market_seen_cache[order_params.market_index] = result.slot
    return result.tx_sig

place_and_take_perp_order(order_params, maker_info=None, referrer_info=None, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
async def place_and_take_perp_order(
    self,
    order_params: OrderParams,
    maker_info: Union[MakerInfo, List[MakerInfo]] = None,
    referrer_info: ReferrerInfo = None,
    sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            self.get_place_and_take_perp_order_ix(
                order_params, maker_info, referrer_info, sub_account_id
            ),
        ]
    )
    self.last_perp_market_seen_cache[order_params.market_index] = (
        tx_sig_and_slot.slot
    )
    return tx_sig_and_slot.tx_sig

place_and_take_spot_order(order_params, fulfillment_config=None, maker_info=None, referrer_info=None, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
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
async def place_and_take_spot_order(
    self,
    order_params: OrderParams,
    fulfillment_config: Optional[
        Union[SerumV3FulfillmentConfigAccount, PhoenixV1FulfillmentConfigAccount]
    ] = None,
    maker_info: Union[MakerInfo, List[MakerInfo]] = None,
    referrer_info: ReferrerInfo = None,
    sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            self.get_place_and_take_spot_order_ix(
                order_params,
                fulfillment_config,
                maker_info,
                referrer_info,
                sub_account_id,
            ),
        ]
    )
    self.last_spot_market_seen_cache[order_params.market_index] = (
        tx_sig_and_slot.slot
    )
    return tx_sig_and_slot.tx_sig

place_orders(order_params, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
async def place_orders(
    self,
    order_params: List[OrderParams],
    sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            self.get_place_orders_ix(order_params, sub_account_id),
        ]
    )

    for order_param in order_params:
        if is_variant(order_param.market_type, "Perp"):
            self.last_perp_market_seen_cache[order_param.market_index] = (
                tx_sig_and_slot.slot
            )
        else:
            self.last_spot_market_seen_cache[order_param.market_index] = (
                tx_sig_and_slot.slot
            )

    return tx_sig_and_slot.tx_sig

place_perp_order(order_params, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
async def place_perp_order(
    self,
    order_params: OrderParams,
    sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            self.get_place_perp_order_ix(order_params, sub_account_id),
        ]
    )
    self.last_perp_market_seen_cache[order_params.market_index] = (
        tx_sig_and_slot.slot
    )
    return tx_sig_and_slot.tx_sig

place_signed_msg_taker_order(signed_msg_order_params, market_index, taker_info, preceding_ixs=[], override_ix_count=None, include_high_leverage_mode_config=False) async

Source code in src/driftpy/drift_client.py
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
async def place_signed_msg_taker_order(
    self,
    signed_msg_order_params: SignedMsgOrderParams,
    market_index: int,
    taker_info: dict,
    preceding_ixs: list[Instruction] = [],
    override_ix_count: Optional[int] = None,
    include_high_leverage_mode_config: Optional[bool] = False,
) -> TxSigAndSlot:
    ixs = await self.get_place_signed_msg_taker_perp_order_ixs(
        signed_msg_order_params,
        market_index,
        taker_info,
        None,
        preceding_ixs,
        override_ix_count,
        include_high_leverage_mode_config,
    )
    return await self.send_ixs(ixs)

place_spot_order(order_params, sub_account_id=None) async

Source code in src/driftpy/drift_client.py
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
async def place_spot_order(
    self,
    order_params: OrderParams,
    sub_account_id: int = None,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            self.get_place_spot_order_ix(order_params, sub_account_id),
        ]
    )
    self.last_spot_market_seen_cache[order_params.market_index] = (
        tx_sig_and_slot.slot
    )
    self.last_spot_market_seen_cache[QUOTE_SPOT_MARKET_INDEX] = tx_sig_and_slot.slot
    return tx_sig_and_slot.tx_sig

random_string(length)

Source code in src/driftpy/drift_client.py
989
990
def random_string(self, length: int) -> str:
    return "".join(random.choices(string.ascii_letters + string.digits, k=length))

remove_insurance_fund_stake(spot_market_index, user_token_account=None) async

Source code in src/driftpy/drift_client.py
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
async def remove_insurance_fund_stake(
    self, spot_market_index: int, user_token_account: Pubkey = None
):
    return (
        await self.send_ixs(
            self.get_remove_insurance_fund_stake_ix(
                spot_market_index, user_token_account
            )
        )
    ).tx_sig

remove_liquidity(amount, market_index, sub_account_id=None) async

burns LP tokens and removes liquidity to the DAMM

Parameters:
  • amount (int) –

    amount of lp tokens to burn

  • market_index (int) –
  • sub_account_id (int, default: None ) –

    subaccount id. Defaults to 0.

Returns:
  • Signature( Signature ) –

    tx sig

Source code in src/driftpy/drift_client.py
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
async def remove_liquidity(
    self, amount: int, market_index: int, sub_account_id: int = None
) -> Signature:
    """burns LP tokens and removes liquidity to the DAMM

    Args:
        amount (int): amount of lp tokens to burn
        market_index (int):
        sub_account_id (int, optional): subaccount id. Defaults to 0.

    Returns:
        Signature: tx sig
    """
    return (
        await self.send_ixs(
            [self.get_remove_liquidity_ix(amount, market_index, sub_account_id)]
        )
    ).tx_sig

request_remove_insurance_fund_stake(spot_market_index, amount) async

Source code in src/driftpy/drift_client.py
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
async def request_remove_insurance_fund_stake(
    self, spot_market_index: int, amount: int
):
    return (
        await self.send_ixs(
            self.get_request_remove_insurance_fund_stake_ix(
                spot_market_index, amount
            )
        )
    ).tx_sig

reset_sequence_number(sequence_number=0, subaccount=0) async

Source code in src/driftpy/drift_client.py
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
async def reset_sequence_number(
    self, sequence_number: int = 0, subaccount: int = 0
) -> Signature:
    try:
        ix = self.get_reset_sequence_number_ix(sequence_number)
        self.resetting_sequence = True
        sig = (await self.send_ixs(ix)).tx_sig
        self.resetting_sequence = False
        self.sequence_number_by_subaccount[subaccount] = sequence_number
        return sig
    except Exception as e:
        print(f"WARNING: failed to reset sequence number: {e}")

resolve_perp_bankruptcy(user_authority, market_index, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
async def resolve_perp_bankruptcy(
    self,
    user_authority: Pubkey,
    market_index: int,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    return (
        await self.send_ixs(
            [
                await self.get_resolve_perp_bankruptcy_ix(
                    user_authority,
                    market_index,
                    user_sub_account_id,
                    liq_sub_account_id,
                )
            ]
        )
    ).tx_sig

resolve_spot_bankruptcy(user_authority, spot_market_index, user_sub_account_id=0, liq_sub_account_id=None) async

Source code in src/driftpy/drift_client.py
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
async def resolve_spot_bankruptcy(
    self,
    user_authority: Pubkey,
    spot_market_index: int,
    user_sub_account_id: int = 0,
    liq_sub_account_id: int = None,
):
    return (
        await self.send_ixs(
            [
                await self.get_resolve_spot_bankruptcy_ix(
                    user_authority,
                    spot_market_index,
                    user_sub_account_id,
                    liq_sub_account_id,
                )
            ]
        )
    ).tx_sig

resurrect(spot_markets, perp_markets, spot_oracles, perp_oracles)

Source code in src/driftpy/drift_client.py
318
319
320
321
322
323
324
325
def resurrect(self, spot_markets, perp_markets, spot_oracles, perp_oracles):
    if not isinstance(self.account_subscriber, CachedDriftClientAccountSubscriber):
        raise ValueError(
            'You can only resurrect a DriftClient that was initialized with AccountSubscriptionConfig("cached")'
        )
    self.account_subscriber.resurrect(
        spot_markets, perp_markets, spot_oracles, perp_oracles
    )

send_ixs(ixs, signers=None, lookup_tables=None, tx_version=None, sequencer_subaccount=None) async

Source code in src/driftpy/drift_client.py
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
async def send_ixs(
    self,
    ixs: Union[Instruction, list[Instruction]],
    signers=None,
    lookup_tables: list[AddressLookupTableAccount] = None,
    tx_version: Optional[Union[Legacy, int]] = None,
    sequencer_subaccount: Optional[int] = None,
) -> TxSigAndSlot:
    if isinstance(ixs, Instruction):
        ixs = [ixs]

    if not tx_version:
        tx_version = self.tx_version

    compute_unit_instructions = []
    if self.tx_params.compute_units is not None:
        compute_unit_instructions.append(
            set_compute_unit_limit(self.tx_params.compute_units)
        )

    if self.tx_params.compute_units_price is not None:
        compute_unit_instructions.append(
            set_compute_unit_price(self.tx_params.compute_units_price)
        )

    ixs[0:0] = compute_unit_instructions

    subaccount = sequencer_subaccount or self.active_sub_account_id

    if (
        self.enforce_tx_sequencing
        and self.sequence_initialized_by_subaccount[subaccount]
        and not self.resetting_sequence
    ):
        sequence_instruction = self.get_check_and_set_sequence_number_ix(
            self.sequence_number_by_subaccount[subaccount], subaccount
        )
        ixs.insert(len(compute_unit_instructions), sequence_instruction)

    if tx_version == Legacy:
        tx = await self.tx_sender.get_legacy_tx(ixs, self.wallet.payer, signers)
    elif tx_version == 0:
        if lookup_tables is None:
            lookup_tables = await self.fetch_market_lookup_table_accounts()
        tx = await self.tx_sender.get_versioned_tx(
            ixs, self.wallet.payer, lookup_tables, signers
        )
    else:
        raise NotImplementedError("unknown tx version", self.tx_version)

    return await self.tx_sender.send(tx)

settle_expired_market(market_index) async

Source code in src/driftpy/drift_client.py
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
async def settle_expired_market(
    self,
    market_index: int,
):
    return (
        await self.send_ixs(
            [
                await self.get_settle_expired_market_ix(
                    market_index,
                ),
            ]
        )
    ).tx_sig

settle_lp(settlee_user_account_public_key, market_index) async

Source code in src/driftpy/drift_client.py
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
async def settle_lp(
    self,
    settlee_user_account_public_key: Pubkey,
    market_index: int,
) -> Signature:
    return (
        await self.send_ixs(
            [
                await self.get_settle_lp_ix(
                    settlee_user_account_public_key, market_index
                )
            ],
            signers=[],
        )
    ).tx_sig

settle_pnl(settlee_user_account_public_key, settlee_user_account, market_index) async

Source code in src/driftpy/drift_client.py
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
async def settle_pnl(
    self,
    settlee_user_account_public_key: Pubkey,
    settlee_user_account: UserAccount,
    market_index: int,
):
    lookup_tables = await self.fetch_market_lookup_table_accounts()
    return (
        await self.send_ixs(
            self.get_settle_pnl_ix(
                settlee_user_account_public_key, settlee_user_account, market_index
            ),
            lookup_tables=lookup_tables,
        )
    ).tx_sig

settle_revenue_to_insurance_fund(spot_market_index) async

Source code in src/driftpy/drift_client.py
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
async def settle_revenue_to_insurance_fund(self, spot_market_index: int):
    return await self.program.rpc["settle_revenue_to_insurance_fund"](
        spot_market_index,
        ctx=Context(
            accounts={
                "state": get_state_public_key(self.program_id),
                "spot_market": get_spot_market_public_key(
                    self.program_id, spot_market_index
                ),
                "spot_market_vault": get_spot_market_vault_public_key(
                    self.program_id, spot_market_index
                ),
                "drift_signer": self.get_signer_public_key(self.program_id),
                "insurance_fund_vault": get_insurance_fund_vault_public_key(
                    self.program_id,
                    spot_market_index,
                ),
                "token_program": TOKEN_PROGRAM_ID,
            }
        ),
    )

sign_message(message)

Sign a message with the wallet keypair.

Parameters:
  • message (bytes) –

    The message to sign

Returns:
  • bytes

    The signature

Source code in src/driftpy/drift_client.py
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
def sign_message(self, message: bytes) -> bytes:
    """Sign a message with the wallet keypair.

    Args:
        message: The message to sign

    Returns:
        The signature
    """

    return self.wallet.payer.sign_message(message).to_bytes()

sign_signed_msg_order_params_message(order_params_message, delegate_signer=False)

Sign a SignedMsgOrderParamsMessage

Parameters:
  • order_params_message (Union[dict, SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage]) –

    The order params message to sign

  • delegate_signer (bool, default: False ) –

    Whether to use delegate message format

Returns:
  • SignedMsgOrderParams

    The signed order params

Source code in src/driftpy/drift_client.py
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
def sign_signed_msg_order_params_message(
    self,
    order_params_message: Union[
        dict, SignedMsgOrderParamsMessage, SignedMsgOrderParamsDelegateMessage
    ],
    delegate_signer: bool = False,
) -> SignedMsgOrderParams:
    """Sign a SignedMsgOrderParamsMessage

    Args:
        order_params_message: The order params message to sign
        delegate_signer: Whether to use delegate message format

    Returns:
        The signed order params
    """
    borsh_buf = self.encode_signed_msg_order_params_message(
        order_params_message, delegate_signer
    )
    order_params = borsh_buf.hex().encode()

    return SignedMsgOrderParams(
        order_params=order_params, signature=self.sign_message(order_params)
    )

subscribe() async

Source code in src/driftpy/drift_client.py
295
296
297
298
299
300
301
302
303
async def subscribe(self):
    if self.account_subscriber is None:
        raise ValueError("No account subscriber found")
    await self.account_subscriber.subscribe()
    if self.enforce_tx_sequencing:
        await self.load_sequence_info()
    for sub_account_id in self.sub_account_ids:
        await self.add_user(sub_account_id)
    await self.add_user_stats(self.authority)

switch_active_user(sub_account_id)

Source code in src/driftpy/drift_client.py
387
388
def switch_active_user(self, sub_account_id: int):
    self.active_sub_account_id = sub_account_id

transfer_deposit(amount, market_index, from_sub_account_id, to_sub_account_id) async

Source code in src/driftpy/drift_client.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
async def transfer_deposit(
    self,
    amount: int,
    market_index: int,
    from_sub_account_id: int,
    to_sub_account_id: int,
):
    tx_sig_and_slot = await self.send_ixs(
        [
            await self.get_transfer_deposit_ix(
                amount,
                market_index,
                from_sub_account_id,
                to_sub_account_id,
            )
        ]
    )
    self.last_spot_market_seen_cache[market_index] = tx_sig_and_slot.slot
    return tx_sig_and_slot.tx_sig

unsubscribe() async

Source code in src/driftpy/drift_client.py
352
353
354
355
async def unsubscribe(self):
    if self.account_subscriber is None:
        raise ValueError("No account subscriber found")
    await self.account_subscriber.unsubscribe()

update_amm(market_indexs) async

Source code in src/driftpy/drift_client.py
3420
3421
async def update_amm(self, market_indexs: list[int]):
    return (await self.send_ixs(self.get_update_amm_ix(market_indexs))).tx_sig

update_prelaunch_oracle(market_index) async

Source code in src/driftpy/drift_client.py
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
async def update_prelaunch_oracle(
    self,
    market_index: int,
):
    return (
        await self.send_ixs(
            self.get_update_prelaunch_oracle_ix(
                market_index,
            ),
        )
    ).tx_sig

update_user_custom_margin_ratio(updates) async

Updates custom margin ratio for one or more subaccounts

Parameters:
  • updates (List[dict]) –

    List of dicts with 'margin_ratio' and 'sub_account_id' keys

Returns:
  • Signature( Signature ) –

    tx sig

Source code in src/driftpy/drift_client.py
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
async def update_user_custom_margin_ratio(
    self,
    updates: List[dict],
) -> Signature:
    """Updates custom margin ratio for one or more subaccounts

    Args:
        updates: List of dicts with 'margin_ratio' and 'sub_account_id' keys
        for example like this
        updates = [
            {
                "margin_ratio": 10000,
                "sub_account_id": 0,
            }
        ]

    Returns:
        Signature: tx sig
    """
    ixs = []
    for update in updates:
        margin_ratio = update.get("margin_ratio")
        sub_account_id = update.get("sub_account_id", 0)

        if margin_ratio is None:
            raise ValueError("margin_ratio is required in each update")

        await self.add_user(sub_account_id)
        ixs.append(
            self.get_update_user_custom_margin_ratio_ix(
                margin_ratio=margin_ratio,
                sub_account_id=sub_account_id,
            )
        )

    tx_sig = (await self.send_ixs(ixs)).tx_sig
    return tx_sig

update_user_margin_trading_enabled(margin_trading_enabled, sub_account_id=None) async

Toggles margin trading for a user

Parameters:
  • sub_account_id (int, default: None ) –

    subaccount id. Defaults to 0.

Returns:
  • Signature( Signature ) –

    tx sig

Source code in src/driftpy/drift_client.py
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
async def update_user_margin_trading_enabled(
    self, margin_trading_enabled: bool, sub_account_id: Optional[int] = None
) -> Signature:
    """Toggles margin trading for a user

    Args:
        sub_account_id (int, optional): subaccount id. Defaults to 0.

    Returns:
        Signature: tx sig
    """
    await self.add_user(sub_account_id)

    tx_sig = (
        await self.send_ixs(
            [
                self.get_update_user_margin_trading_enabled_ix(
                    margin_trading_enabled=margin_trading_enabled,
                    sub_account_id=sub_account_id,
                )
            ]
        )
    ).tx_sig
    return tx_sig

update_user_protected_maker_orders(sub_account_id, protected_orders) async

Source code in src/driftpy/drift_client.py
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
async def update_user_protected_maker_orders(
    self,
    sub_account_id: int,
    protected_orders: bool,
):
    return (
        await self.send_ixs(
            [
                await self.get_update_user_protected_maker_orders_ix(
                    sub_account_id, protected_orders
                )
            ]
        )
    ).tx_sig

withdraw(amount, market_index, user_token_account, reduce_only=False, sub_account_id=None) async

withdraws from drift protocol (can also allow borrowing)

Parameters:
  • amount (int) –

    amount to withdraw

  • market_index (int) –
  • user_token_account (Pubkey) –

    ata of the account to withdraw to

  • reduce_only (bool, default: False ) –

    if True will only withdraw existing funds else if False will allow taking out borrows. Defaults to False.

  • sub_account_id (int, default: None ) –

    subaccount. Defaults to 0.

Returns:
  • str( TxSigAndSlot ) –

    tx sig

Source code in src/driftpy/drift_client.py
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
async def withdraw(
    self,
    amount: int,
    market_index: int,
    user_token_account: Pubkey,
    reduce_only: bool = False,
    sub_account_id: int = None,
) -> TxSigAndSlot:
    """withdraws from drift protocol (can also allow borrowing)

    Args:
        amount (int): amount to withdraw
        market_index (int):
        user_token_account (Pubkey): ata of the account to withdraw to
        reduce_only (bool, optional): if True will only withdraw existing funds else if False will allow taking out borrows. Defaults to False.
        sub_account_id (int, optional): subaccount. Defaults to 0.

    Returns:
        str: tx sig
    """
    tx_sig_and_slot = await self.send_ixs(
        await self.get_withdraw_collateral_ix(
            amount,
            market_index,
            user_token_account,
            reduce_only,
            sub_account_id,
        )
    )
    self.last_spot_market_seen_cache[market_index] = tx_sig_and_slot.slot
    return tx_sig_and_slot

JitoParams dataclass

Source code in src/driftpy/drift_client.py
119
120
121
122
123
124
125
@dataclass
class JitoParams:
    jito_keypair: Keypair
    block_engine_url: str
    blockhash_refresh_rate: Optional[int] = None
    leader_refresh_rate: Optional[int] = None
    tip_amount: Optional[int] = None

block_engine_url instance-attribute

blockhash_refresh_rate = None class-attribute instance-attribute

jito_keypair instance-attribute

leader_refresh_rate = None class-attribute instance-attribute

tip_amount = None class-attribute instance-attribute

__init__(jito_keypair, block_engine_url, blockhash_refresh_rate=None, leader_refresh_rate=None, tip_amount=None)