1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
use anchor_client::ClientError::AnchorError;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use anchor_client::Cluster;

use anchor_lang::__private::bytemuck;
use anchor_lang::prelude::System;
use anchor_lang::{AccountDeserialize, AnchorDeserialize, Id};
use anchor_spl::associated_token::get_associated_token_address;
use anchor_spl::token::Token;

use fixed::types::I80F48;
use futures::{stream, StreamExt, TryFutureExt, TryStreamExt};
use itertools::Itertools;
use tracing::*;

use mango_v4::accounts_ix::{
    HealthCheckKind, Serum3OrderType, Serum3SelfTradeBehavior, Serum3Side,
};
use mango_v4::accounts_zerocopy::KeyedAccountSharedData;
use mango_v4::health::HealthCache;
use mango_v4::state::{
    Bank, Group, MangoAccountValue, OpenbookV2MarketIndex, OracleAccountInfos, PerpMarket,
    PerpMarketIndex, PlaceOrderType, SelfTradeBehavior, Serum3MarketIndex, Side, TokenIndex,
};

use crate::confirm_transaction::{wait_for_transaction_confirmation, RpcConfirmTransactionConfig};
use crate::context::MangoGroupContext;
use crate::gpa::{fetch_anchor_account, fetch_mango_accounts};
use crate::priority_fees::{FixedPriorityFeeProvider, PriorityFeeProvider};
use crate::util;
use crate::util::PreparedInstructions;
use crate::{account_fetcher::*, swap};
use crate::{health_cache, Serum3MarketContext, TokenContext};
use solana_address_lookup_table_program::state::AddressLookupTable;
use solana_client::nonblocking::rpc_client::RpcClient as RpcClientAsync;
use solana_client::rpc_client::SerializableTransaction;
use solana_client::rpc_config::RpcSendTransactionConfig;
use solana_client::rpc_response::RpcSimulateTransactionResult;
use solana_sdk::address_lookup_table_account::AddressLookupTableAccount;
use solana_sdk::commitment_config::CommitmentLevel;
use solana_sdk::compute_budget::ComputeBudgetInstruction;
use solana_sdk::hash::Hash;
use solana_sdk::signer::keypair;
use solana_sdk::transaction::TransactionError;

use anyhow::Context;
use mango_v4::error::{IsAnchorErrorWithCode, MangoError};
use solana_sdk::account::ReadableAccount;
use solana_sdk::instruction::{AccountMeta, Instruction};
use solana_sdk::signature::{Keypair, Signature};
use solana_sdk::sysvar;
use solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey, signer::Signer};

pub const MAX_ACCOUNTS_PER_TRANSACTION: usize = 64;

// very close to anchor_client::Client, which unfortunately has no accessors or Clone
#[derive(Clone, Builder)]
#[builder(name = "ClientBuilder", build_fn(name = "build_config"))]
pub struct ClientConfig {
    /// RPC url
    ///
    /// Defaults to Cluster::Mainnet, using the public crowded mainnet-beta rpc endpoint.
    /// Should usually be overridden with a custom rpc endpoint.
    #[builder(default = "Cluster::Mainnet")]
    pub cluster: Cluster,

    /// Transaction fee payer. Needs to be set to send transactions.
    pub fee_payer: Option<Arc<Keypair>>,

    /// Commitment for interacting with the chain. Defaults to processed.
    #[builder(default = "CommitmentConfig::processed()")]
    pub commitment: CommitmentConfig,

    /// Timeout, defaults to 60s
    ///
    /// This timeout applies to rpc requests. Note that the timeout for transaction
    /// confirmation is configured separately in rpc_confirm_transaction_config.
    #[builder(default = "Duration::from_secs(60)")]
    pub timeout: Duration,

    /// Jupiter Timeout, defaults to 30s
    ///
    /// This timeout applies to jupiter requests.
    #[builder(default = "Duration::from_secs(30)")]
    pub jupiter_timeout: Duration,

    #[builder(default)]
    pub transaction_builder_config: TransactionBuilderConfig,

    /// Defaults to a preflight check at processed commitment
    #[builder(default = "ClientBuilder::default_rpc_send_transaction_config()")]
    pub rpc_send_transaction_config: RpcSendTransactionConfig,

    /// Defaults to waiting up to 60s for confirmation
    #[builder(default = "ClientBuilder::default_rpc_confirm_transaction_config()")]
    pub rpc_confirm_transaction_config: RpcConfirmTransactionConfig,

    #[builder(default = "\"https://quote-api.jup.ag/v6\".into()")]
    pub jupiter_v6_url: String,

    #[builder(default = "\"\".into()")]
    pub jupiter_token: String,

    #[builder(default = "\"https://api.sanctum.so/v1\".into()")]
    pub sanctum_url: String,

    /// Sanctum Timeout, defaults to 30s
    ///
    /// This timeout applies to jupiter requests.
    #[builder(default = "Duration::from_secs(30)")]
    pub sanctum_timeout: Duration,

    /// Determines how fallback oracle accounts are provided to instructions. Defaults to Dynamic.
    #[builder(default = "FallbackOracleConfig::Dynamic")]
    pub fallback_oracle_config: FallbackOracleConfig,

    /// If set, don't use `cluster` for sending transactions and send to all
    /// addresses configured here instead.
    #[builder(default = "None")]
    pub override_send_transaction_urls: Option<Vec<String>>,
}

impl ClientBuilder {
    pub fn build(&self) -> Result<Client, ClientBuilderError> {
        let config = self.build_config()?;
        Ok(Client::new_from_config(config))
    }

    pub fn default_rpc_send_transaction_config() -> RpcSendTransactionConfig {
        RpcSendTransactionConfig {
            preflight_commitment: Some(CommitmentLevel::Processed),
            ..Default::default()
        }
    }

    pub fn default_rpc_confirm_transaction_config() -> RpcConfirmTransactionConfig {
        RpcConfirmTransactionConfig {
            timeout: Some(Duration::from_secs(60)),
            ..Default::default()
        }
    }
}

pub struct Client {
    config: ClientConfig,
    rpc_async: RpcClientAsync,
    send_transaction_rpc_asyncs: Vec<RpcClientAsync>,
}

impl Client {
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Prefer using the builder()
    pub fn new(
        cluster: Cluster,
        commitment: CommitmentConfig,
        fee_payer: Arc<Keypair>,
        timeout: Option<Duration>,
        transaction_builder_config: TransactionBuilderConfig,
    ) -> Self {
        Self::builder()
            .cluster(cluster)
            .commitment(commitment)
            .fee_payer(Some(fee_payer))
            .timeout(timeout.unwrap_or(Duration::from_secs(30)))
            .transaction_builder_config(transaction_builder_config)
            .build()
            .unwrap()
    }

    pub fn new_from_config(config: ClientConfig) -> Self {
        Self {
            rpc_async: RpcClientAsync::new_with_timeout_and_commitment(
                config.cluster.url().to_string(),
                config.timeout,
                config.commitment,
            ),
            send_transaction_rpc_asyncs: config
                .override_send_transaction_urls
                .clone()
                .unwrap_or_else(|| vec![config.cluster.url().to_string()])
                .into_iter()
                .map(|url| {
                    RpcClientAsync::new_with_timeout_and_commitment(
                        url,
                        config.timeout,
                        config.commitment,
                    )
                })
                .collect_vec(),
            config,
        }
    }

    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    pub fn rpc_async(&self) -> &RpcClientAsync {
        &self.rpc_async
    }

    /// Sometimes clients don't want to borrow the Client instance and just pass on RpcClientAsync
    pub fn new_rpc_async(&self) -> RpcClientAsync {
        let url = self.config.cluster.url().to_string();
        RpcClientAsync::new_with_timeout_and_commitment(
            url,
            self.config.timeout,
            self.config.commitment,
        )
    }

    // TODO: this function here is awkward, since it (intentionally) doesn't use MangoClient::account_fetcher
    pub async fn rpc_anchor_account<T: AccountDeserialize>(
        &self,
        address: &Pubkey,
    ) -> anyhow::Result<T> {
        fetch_anchor_account(self.rpc_async(), address).await
    }

    pub fn fee_payer(&self) -> Arc<Keypair> {
        self.config
            .fee_payer
            .as_ref()
            .expect("fee payer must be set")
            .clone()
    }

    /// Sends a transaction via the configured cluster (or all override_send_transaction_urls).
    ///
    /// Returns the tx signature if at least one send returned ok.
    /// Note that a success does not mean that the transaction is confirmed.
    pub async fn send_transaction(
        &self,
        tx: &impl SerializableTransaction,
    ) -> anyhow::Result<Signature> {
        let futures = self.send_transaction_rpc_asyncs.iter().map(|rpc| {
            rpc.send_transaction_with_config(tx, self.config.rpc_send_transaction_config)
                .map_err(prettify_solana_client_error)
        });
        let mut results = futures::future::join_all(futures).await;

        // If all fail, return the first
        let successful_sends = results.iter().filter(|r| r.is_ok()).count();
        if successful_sends == 0 {
            results.remove(0)?;
        }

        // Otherwise just log errors
        for (result, rpc) in results.iter().zip(self.send_transaction_rpc_asyncs.iter()) {
            if let Err(err) = result {
                info!(
                    rpc = rpc.url(),
                    successful_sends, "one of the transaction sends failed: {err:?}",
                )
            }
        }
        return Ok(*tx.get_signature());
    }
}

// todo: might want to integrate geyser, websockets, or simple http polling for keeping data fresh
pub struct MangoClient {
    pub client: Client,

    // todo: possibly this object should have cache-functions, so there can be one getMultipleAccounts
    // call to refresh banks etc -- if it's backed by websockets, these could just do nothing
    pub account_fetcher: Arc<dyn AccountFetcher>,

    pub authority: Arc<Keypair>,
    pub mango_account_address: Pubkey,

    pub context: MangoGroupContext,

    pub http_client: reqwest::Client,
}

// TODO: add retry framework for sending tx and rpc calls
// 1/ this works right now, but I think mid-term the MangoClient will want to interact with multiple mango accounts
// -- then we should probably specify accounts by owner+account_num / or pubkey
// 2/ pubkey, can be both owned, but also delegated accouns

impl MangoClient {
    pub fn group_for_admin(admin: Pubkey, num: u32) -> Pubkey {
        Pubkey::find_program_address(
            &["Group".as_ref(), admin.as_ref(), num.to_le_bytes().as_ref()],
            &mango_v4::ID,
        )
        .0
    }

    pub async fn find_accounts(
        client: &Client,
        group: Pubkey,
        owner: &Keypair,
    ) -> anyhow::Result<Vec<(Pubkey, MangoAccountValue)>> {
        fetch_mango_accounts(client.rpc_async(), mango_v4::ID, group, owner.pubkey()).await
    }

    pub async fn find_or_create_account(
        client: &Client,
        group: Pubkey,
        owner: Arc<Keypair>,
        payer: Arc<Keypair>, // pays the SOL for the new account
        mango_account_name: &str,
    ) -> anyhow::Result<Pubkey> {
        let rpc = client.rpc_async();
        let program = mango_v4::ID;
        let owner_pk = owner.pubkey();

        // Mango Account
        let mut mango_account_tuples = fetch_mango_accounts(&rpc, program, group, owner_pk).await?;
        let mango_account_opt = mango_account_tuples
            .iter()
            .find(|(_, account)| account.fixed.name() == mango_account_name);
        if mango_account_opt.is_none() {
            mango_account_tuples.sort_by(|a, b| {
                a.1.fixed
                    .account_num
                    .partial_cmp(&b.1.fixed.account_num)
                    .unwrap()
            });
            let account_num = match mango_account_tuples.last() {
                Some(tuple) => tuple.1.fixed.account_num + 1,
                None => 0u32,
            };
            Self::create_account(
                client,
                group,
                owner.clone(),
                payer,
                account_num,
                mango_account_name,
            )
            .await
            .context("Failed to create account...")?;
        }
        let mango_account_tuples = fetch_mango_accounts(&rpc, program, group, owner_pk).await?;
        let index = mango_account_tuples
            .iter()
            .position(|tuple| tuple.1.fixed.name() == mango_account_name)
            .unwrap();
        Ok(mango_account_tuples[index].0)
    }

    pub async fn create_account(
        client: &Client,
        group: Pubkey,
        owner: Arc<Keypair>,
        payer: Arc<Keypair>, // pays the SOL for the new account
        account_num: u32,
        mango_account_name: &str,
    ) -> anyhow::Result<(Pubkey, Signature)> {
        let account = Pubkey::find_program_address(
            &[
                b"MangoAccount".as_ref(),
                group.as_ref(),
                owner.pubkey().as_ref(),
                &account_num.to_le_bytes(),
            ],
            &mango_v4::id(),
        )
        .0;
        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: anchor_lang::ToAccountMetas::to_account_metas(
                &mango_v4::accounts::AccountCreate {
                    group,
                    owner: owner.pubkey(),
                    account,
                    payer: payer.pubkey(),
                    system_program: System::id(),
                },
                None,
            ),
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::AccountCreate {
                account_num,
                name: mango_account_name.to_owned(),
                token_count: 8,
                serum3_count: 4,
                perp_count: 4,
                perp_oo_count: 8,
            }),
        };

        let txsig = TransactionBuilder {
            instructions: vec![ix],
            address_lookup_tables: vec![],
            payer: payer.pubkey(),
            signers: vec![owner, payer],
            config: client.config.transaction_builder_config.clone(),
        }
        .send_and_confirm(&client)
        .await?;

        Ok((account, txsig))
    }

    /// Conveniently creates a RPC based client
    pub async fn new_for_existing_account(
        client: Client,
        account: Pubkey,
        authority: Arc<Keypair>,
    ) -> anyhow::Result<Self> {
        let rpc = client.new_rpc_async();
        let account_fetcher = Arc::new(CachedAccountFetcher::new(Arc::new(RpcAccountFetcher {
            rpc,
        })));
        let mango_account =
            account_fetcher_fetch_mango_account(&*account_fetcher, &account).await?;
        let group = mango_account.fixed.group;
        if mango_account.fixed.owner != authority.pubkey() {
            anyhow::bail!(
                "bad owner for account: expected {} got {}",
                mango_account.fixed.owner,
                authority.pubkey()
            );
        }

        let rpc = client.rpc_async();
        let group_context = MangoGroupContext::new_from_rpc(&rpc, group).await?;

        Self::new_detail(client, account, authority, group_context, account_fetcher)
    }

    /// Allows control of AccountFetcher and externally created MangoGroupContext
    pub fn new_detail(
        client: Client,
        account: Pubkey,
        authority: Arc<Keypair>,
        // future: maybe pass Arc<MangoGroupContext>, so it can be extenally updated?
        group_context: MangoGroupContext,
        account_fetcher: Arc<dyn AccountFetcher>,
    ) -> anyhow::Result<Self> {
        Ok(Self {
            client,
            account_fetcher,
            authority,
            mango_account_address: account,
            context: group_context,
            http_client: reqwest::Client::new(),
        })
    }

    pub fn authority(&self) -> Pubkey {
        self.authority.pubkey()
    }

    pub fn group(&self) -> Pubkey {
        self.context.group
    }

    pub async fn mango_account(&self) -> anyhow::Result<MangoAccountValue> {
        account_fetcher_fetch_mango_account(&*self.account_fetcher, &self.mango_account_address)
            .await
    }

    pub async fn first_bank(&self, token_index: TokenIndex) -> anyhow::Result<Bank> {
        let bank_address = self.context.token(token_index).first_bank();
        account_fetcher_fetch_anchor_account(&*self.account_fetcher, &bank_address).await
    }

    pub async fn derive_health_check_remaining_account_metas(
        &self,
        account: &MangoAccountValue,
        affected_tokens: Vec<TokenIndex>,
        writable_banks: Vec<TokenIndex>,
        affected_perp_markets: Vec<PerpMarketIndex>,
    ) -> anyhow::Result<(Vec<AccountMeta>, u32)> {
        let fallback_contexts = self
            .context
            .derive_fallback_oracle_keys(
                &self.client.config.fallback_oracle_config,
                &*self.account_fetcher,
            )
            .await?;
        self.context.derive_health_check_remaining_account_metas(
            &account,
            affected_tokens,
            writable_banks,
            affected_perp_markets,
            fallback_contexts,
        )
    }

    pub async fn derive_health_check_remaining_account_metas_two_accounts(
        &self,
        account_1: &MangoAccountValue,
        account_2: &MangoAccountValue,
        affected_tokens: &[TokenIndex],
        writable_banks: &[TokenIndex],
    ) -> anyhow::Result<(Vec<AccountMeta>, u32)> {
        let fallback_contexts = self
            .context
            .derive_fallback_oracle_keys(
                &self.client.config.fallback_oracle_config,
                &*self.account_fetcher,
            )
            .await?;

        self.context
            .derive_health_check_remaining_account_metas_two_accounts(
                account_1,
                account_2,
                affected_tokens,
                writable_banks,
                fallback_contexts,
            )
    }

    pub async fn health_cache(
        &self,
        mango_account: &MangoAccountValue,
    ) -> anyhow::Result<HealthCache> {
        health_cache::new(
            &self.context,
            &self.client.config.fallback_oracle_config,
            &*self.account_fetcher,
            mango_account,
        )
        .await
    }

    pub async fn token_deposit(
        &self,
        mint: Pubkey,
        amount: u64,
        reduce_only: bool,
    ) -> anyhow::Result<Signature> {
        let token = self.context.token_by_mint(&mint)?;
        let token_index = token.token_index;
        let mango_account = &self.mango_account().await?;

        let (health_check_metas, health_cu) = self
            .derive_health_check_remaining_account_metas(
                mango_account,
                vec![token_index],
                vec![],
                vec![],
            )
            .await?;

        let ixs = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::TokenDeposit {
                            group: self.group(),
                            account: self.mango_account_address,
                            owner: self.authority(),
                            bank: token.first_bank(),
                            vault: token.first_vault(),
                            oracle: token.oracle,
                            token_account: get_associated_token_address(
                                &self.authority(),
                                &token.mint,
                            ),
                            token_authority: self.authority(),
                            token_program: Token::id(),
                        },
                        None,
                    );
                    ams.extend(health_check_metas.into_iter());
                    ams
                },
                data: anchor_lang::InstructionData::data(&mango_v4::instruction::TokenDeposit {
                    amount,
                    reduce_only,
                }),
            },
            self.instruction_cu(health_cu),
        );
        self.send_and_confirm_authority_tx(ixs.to_instructions())
            .await
    }

    /// Assert that health of account is > N
    pub async fn health_check_instruction(
        &self,
        account: &MangoAccountValue,
        min_health_value: f64,
        affected_tokens: Vec<TokenIndex>,
        affected_perp_markets: Vec<PerpMarketIndex>,
        check_kind: HealthCheckKind,
    ) -> anyhow::Result<PreparedInstructions> {
        let (health_check_metas, health_cu) = self
            .derive_health_check_remaining_account_metas(
                account,
                affected_tokens,
                vec![],
                affected_perp_markets,
            )
            .await?;

        let ixs = PreparedInstructions::from_vec(
            vec![Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::HealthCheck {
                            group: self.group(),
                            account: self.mango_account_address,
                        },
                        None,
                    );
                    ams.extend(health_check_metas.into_iter());
                    ams
                },
                data: anchor_lang::InstructionData::data(&mango_v4::instruction::HealthCheck {
                    min_health_value,
                    check_kind,
                }),
            }],
            self.instruction_cu(health_cu),
        );
        Ok(ixs)
    }

    /// Avoid executing same instruction multiple time
    pub async fn sequence_check_instruction(
        &self,
        mango_account_address: &Pubkey,
        mango_account: &MangoAccountValue,
    ) -> anyhow::Result<PreparedInstructions> {
        let ixs = PreparedInstructions::from_vec(
            vec![Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::SequenceCheck {
                            group: self.group(),
                            account: *mango_account_address,
                            owner: mango_account.fixed.owner,
                        },
                        None,
                    )
                },
                data: anchor_lang::InstructionData::data(&mango_v4::instruction::SequenceCheck {
                    expected_sequence_number: mango_account.fixed.sequence_number,
                }),
            }],
            self.context.compute_estimates.cu_for_sequence_check,
        );
        Ok(ixs)
    }

    /// Creates token withdraw instructions for the MangoClient's account/owner.
    /// The `account` state is passed in separately so changes during the tx can be
    /// accounted for when deriving health accounts.
    pub async fn token_withdraw_instructions(
        &self,
        account: &MangoAccountValue,
        mint: Pubkey,
        amount: u64,
        allow_borrow: bool,
    ) -> anyhow::Result<PreparedInstructions> {
        let token = self.context.token_by_mint(&mint)?;
        let token_index = token.token_index;

        let (health_check_metas, health_cu) = self
            .derive_health_check_remaining_account_metas(account, vec![token_index], vec![], vec![])
            .await?;

        let ixs = PreparedInstructions::from_vec(
            vec![
                spl_associated_token_account::instruction::create_associated_token_account_idempotent(
                    &self.authority(),
                    &account.fixed.owner,
                    &mint,
                    &Token::id(),
                ),
                Instruction {
                    program_id: mango_v4::id(),
                    accounts: {
                        let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                            &mango_v4::accounts::TokenWithdraw {
                                group: self.group(),
                                account: self.mango_account_address,
                                owner: self.authority(),
                                bank: token.first_bank(),
                                vault: token.first_vault(),
                                oracle: token.oracle,
                                token_account: get_associated_token_address(
                                    &account.fixed.owner,
                                    &token.mint,
                                ),
                                token_program: Token::id(),
                            },
                            None,
                        );
                        ams.extend(health_check_metas.into_iter());
                        ams
                    },
                    data: anchor_lang::InstructionData::data(&mango_v4::instruction::TokenWithdraw {
                        amount,
                        allow_borrow,
                    }),
                },
            ],
            self.instruction_cu(health_cu) + self.context.compute_estimates.cu_per_associated_token_account_creation,
        );
        Ok(ixs)
    }

    pub async fn token_withdraw(
        &self,
        mint: Pubkey,
        amount: u64,
        allow_borrow: bool,
    ) -> anyhow::Result<Signature> {
        let account = self.mango_account().await?;
        let ixs = self
            .token_withdraw_instructions(&account, mint, amount, allow_borrow)
            .await?;
        self.send_and_confirm_authority_tx(ixs.to_instructions())
            .await
    }

    pub async fn bank_oracle_price(&self, token_index: TokenIndex) -> anyhow::Result<I80F48> {
        let bank = self.first_bank(token_index).await?;
        let mint_info = self.context.token(token_index);
        let oracle = self
            .account_fetcher
            .fetch_raw_account(&mint_info.oracle)
            .await?;
        let oracle_acc = &KeyedAccountSharedData::new(mint_info.oracle, oracle.into());
        let price = bank.oracle_price(&OracleAccountInfos::from_reader(oracle_acc), None)?;
        Ok(price)
    }

    pub async fn perp_oracle_price(
        &self,
        perp_market_index: PerpMarketIndex,
    ) -> anyhow::Result<I80F48> {
        let perp = self.context.perp(perp_market_index);
        let perp_market: PerpMarket =
            account_fetcher_fetch_anchor_account(&*self.account_fetcher, &perp.address).await?;
        let oracle = self.account_fetcher.fetch_raw_account(&perp.oracle).await?;
        let oracle_acc = &KeyedAccountSharedData::new(perp.oracle, oracle.into());
        let price = perp_market.oracle_price(&OracleAccountInfos::from_reader(oracle_acc), None)?;
        Ok(price)
    }

    //
    // Serum3
    //

    pub fn serum3_close_open_orders_instruction(
        &self,
        market_index: Serum3MarketIndex,
    ) -> PreparedInstructions {
        let account_pubkey = self.mango_account_address;
        let s3 = self.context.serum3(market_index);

        let open_orders = self.serum3_create_open_orders_address(market_index);

        PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::Serum3CloseOpenOrders {
                        group: self.group(),
                        account: account_pubkey,
                        serum_market: s3.address,
                        serum_program: s3.serum_program,
                        serum_market_external: s3.serum_market_external,
                        open_orders,
                        owner: self.authority(),
                        sol_destination: self.authority(),
                    },
                    None,
                ),
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::Serum3CloseOpenOrders {},
                ),
            },
            self.context.compute_estimates.cu_per_mango_instruction,
        )
    }

    pub async fn serum3_close_open_orders(&self, name: &str) -> anyhow::Result<Signature> {
        let market_index = self.context.serum3_market_index(name);
        let ix = self.serum3_close_open_orders_instruction(market_index);
        self.send_and_confirm_authority_tx(ix.to_instructions())
            .await
    }

    pub fn serum3_create_open_orders_instruction(
        &self,
        market_index: Serum3MarketIndex,
    ) -> Instruction {
        let account_pubkey = self.mango_account_address;
        let s3 = self.context.serum3(market_index);

        let open_orders = self.serum3_create_open_orders_address(market_index);

        Instruction {
            program_id: mango_v4::id(),
            accounts: anchor_lang::ToAccountMetas::to_account_metas(
                &mango_v4::accounts::Serum3CreateOpenOrders {
                    group: self.group(),
                    account: account_pubkey,
                    serum_market: s3.address,
                    serum_program: s3.serum_program,
                    serum_market_external: s3.serum_market_external,
                    open_orders,
                    owner: self.authority(),
                    payer: self.authority(),
                    system_program: System::id(),
                    rent: sysvar::rent::id(),
                },
                None,
            ),
            data: anchor_lang::InstructionData::data(
                &mango_v4::instruction::Serum3CreateOpenOrders {},
            ),
        }
    }

    fn serum3_create_open_orders_address(&self, market_index: Serum3MarketIndex) -> Pubkey {
        let account_pubkey = self.mango_account_address;
        let s3 = self.context.serum3(market_index);

        let open_orders = Pubkey::find_program_address(
            &[
                b"Serum3OO".as_ref(),
                account_pubkey.as_ref(),
                s3.address.as_ref(),
            ],
            &mango_v4::ID,
        )
        .0;

        open_orders
    }

    pub async fn serum3_create_open_orders(&self, name: &str) -> anyhow::Result<Signature> {
        let market_index = self.context.serum3_market_index(name);
        let ix = self.serum3_create_open_orders_instruction(market_index);
        self.send_and_confirm_authority_tx(vec![ix]).await
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn serum3_place_order_instruction(
        &self,
        account: &MangoAccountValue,
        market_index: Serum3MarketIndex,
        side: Serum3Side,
        limit_price: u64,
        max_base_qty: u64,
        max_native_quote_qty_including_fees: u64,
        self_trade_behavior: Serum3SelfTradeBehavior,
        order_type: Serum3OrderType,
        client_order_id: u64,
        limit: u16,
    ) -> anyhow::Result<PreparedInstructions> {
        let s3 = self.context.serum3(market_index);
        let base = self.context.serum3_base_token(market_index);
        let quote = self.context.serum3_quote_token(market_index);
        let (payer_token, receiver_token) = match side {
            Serum3Side::Bid => (&quote, &base),
            Serum3Side::Ask => (&base, &quote),
        };

        let open_orders = account.serum3_orders(market_index).map(|x| x.open_orders)?;

        let (health_check_metas, health_cu) = self
            .derive_health_check_remaining_account_metas(
                &account,
                vec![],
                vec![receiver_token.token_index],
                vec![],
            )
            .await?;

        let ixs = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::Serum3PlaceOrder {
                            group: self.group(),
                            account: self.mango_account_address,
                            open_orders,
                            payer_bank: payer_token.first_bank(),
                            payer_vault: payer_token.first_vault(),
                            payer_oracle: payer_token.oracle,
                            serum_market: s3.address,
                            serum_program: s3.serum_program,
                            serum_market_external: s3.serum_market_external,
                            market_bids: s3.bids,
                            market_asks: s3.asks,
                            market_event_queue: s3.event_q,
                            market_request_queue: s3.req_q,
                            market_base_vault: s3.coin_vault,
                            market_quote_vault: s3.pc_vault,
                            market_vault_signer: s3.vault_signer,
                            owner: self.authority(),
                            token_program: Token::id(),
                        },
                        None,
                    );
                    ams.extend(health_check_metas.into_iter());
                    ams
                },
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::Serum3PlaceOrderV2 {
                        side,
                        limit_price,
                        max_base_qty,
                        max_native_quote_qty_including_fees,
                        self_trade_behavior,
                        order_type,
                        client_order_id,
                        limit,
                    },
                ),
            },
            self.instruction_cu(health_cu)
                + self.context.compute_estimates.cu_per_serum3_order_match * limit as u32,
        );

        Ok(ixs)
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn serum3_create_or_replace_account_instruction(
        &self,
        mut account: &mut MangoAccountValue,
        market_index: Serum3MarketIndex,
        side: Serum3Side,
    ) -> anyhow::Result<PreparedInstructions> {
        let mut ixs = PreparedInstructions::new();

        let base = self.context.serum3_base_token(market_index);
        let quote = self.context.serum3_quote_token(market_index);
        let (payer_token, receiver_token) = match side {
            Serum3Side::Bid => (&quote, &base),
            Serum3Side::Ask => (&base, &quote),
        };

        let open_orders_opt = account
            .serum3_orders(market_index)
            .map(|x| x.open_orders)
            .ok();

        let mut missing_tokens = false;

        let token_replace_ixs = self
            .find_existing_or_try_to_replace_token_positions(
                &mut account,
                &[payer_token.token_index, receiver_token.token_index],
            )
            .await;
        match token_replace_ixs {
            Ok(res) => {
                ixs.append(res);
            }
            Err(_) => missing_tokens = true,
        }

        if open_orders_opt.is_none() {
            let has_available_slot = account.all_serum3_orders().any(|p| !p.is_active());
            let should_close_one_open_orders_account = !has_available_slot || missing_tokens;

            if should_close_one_open_orders_account {
                ixs.append(
                    self.deactivate_first_active_unused_serum3_orders(&mut account)
                        .await?,
                );
            }

            // in case of missing token slots
            // try again to create, as maybe deactivating the market slot resulted in some token being now unused
            // but this time, in case of error, propagate to caller
            if missing_tokens {
                ixs.append(
                    self.find_existing_or_try_to_replace_token_positions(
                        &mut account,
                        &[payer_token.token_index, receiver_token.token_index],
                    )
                    .await?,
                );
            }

            ixs.push(
                self.serum3_create_open_orders_instruction(market_index),
                self.context.compute_estimates.cu_per_mango_instruction,
            );

            let created_open_orders = self.serum3_create_open_orders_address(market_index);

            account.create_serum3_orders(market_index)?.open_orders = created_open_orders;
        }

        Ok(ixs)
    }

    async fn deactivate_first_active_unused_serum3_orders(
        &self,
        account: &mut MangoAccountValue,
    ) -> anyhow::Result<PreparedInstructions> {
        let mut serum3_closable_order_market_index = None;

        for p in account.all_serum3_orders() {
            let open_orders_acc = self
                .account_fetcher
                .fetch_raw_account(&p.open_orders)
                .await?;
            let open_orders_bytes = open_orders_acc.data();
            let open_orders_data: &serum_dex::state::OpenOrders = bytemuck::from_bytes(
                &open_orders_bytes[5..5 + std::mem::size_of::<serum_dex::state::OpenOrders>()],
            );

            let is_closable = open_orders_data.free_slot_bits == u128::MAX
                && open_orders_data.native_coin_total == 0
                && open_orders_data.native_pc_total == 0;

            if is_closable {
                serum3_closable_order_market_index = Some(p.market_index);
                break;
            }
        }

        let first_closable_slot =
            serum3_closable_order_market_index.expect("couldn't find any serum3 slot available");

        let ixs = self.serum3_close_open_orders_instruction(first_closable_slot);

        let first_closable_market = account.serum3_orders(first_closable_slot)?;
        let (tk1, tk2) = (
            first_closable_market.base_token_index,
            first_closable_market.quote_token_index,
        );
        account.token_position_mut(tk1)?.0.decrement_in_use();
        account.token_position_mut(tk2)?.0.decrement_in_use();
        account.deactivate_serum3_orders(first_closable_slot)?;

        Ok(ixs)
    }

    async fn find_existing_or_try_to_replace_token_positions(
        &self,
        account: &mut MangoAccountValue,
        token_indexes: &[TokenIndex],
    ) -> anyhow::Result<PreparedInstructions> {
        let mut ixs = PreparedInstructions::new();

        for token_index in token_indexes {
            let result = self
                .find_existing_or_try_to_replace_token_position(account, *token_index)
                .await?;
            if let Some(ix) = result {
                ixs.append(ix);
            }
        }

        Ok(ixs)
    }

    async fn find_existing_or_try_to_replace_token_position(
        &self,
        account: &mut MangoAccountValue,
        token_index: TokenIndex,
    ) -> anyhow::Result<Option<PreparedInstructions>> {
        let token_position_missing = account
            .ensure_token_position(token_index)
            .is_anchor_error_with_code(MangoError::NoFreeTokenPositionIndex.error_code());

        if !token_position_missing {
            return Ok(None);
        }

        let ixs = self.deactivate_first_active_unused_token(account).await?;
        account.ensure_token_position(token_index)?;

        Ok(Some(ixs))
    }

    async fn deactivate_first_active_unused_token(
        &self,
        account: &mut MangoAccountValue,
    ) -> anyhow::Result<PreparedInstructions> {
        let closable_tokens = account
            .all_token_positions()
            .enumerate()
            .filter(|(_, p)| p.is_active() && !p.is_in_use());

        let mut closable_token_position_raw_index_opt = None;
        let mut closable_token_bank_opt = None;

        for (closable_token_position_raw_index, closable_token_position) in closable_tokens {
            let bank = self.first_bank(closable_token_position.token_index).await?;
            let native_balance = closable_token_position.native(&bank);

            if native_balance < I80F48::ZERO {
                continue;
            }
            if native_balance > I80F48::ONE {
                continue;
            }

            closable_token_position_raw_index_opt = Some(closable_token_position_raw_index);
            closable_token_bank_opt = Some(bank);
            break;
        }

        if closable_token_bank_opt.is_none() {
            return Err(AnchorError(MangoError::NoFreeTokenPositionIndex.into()).into());
        }

        let withdraw_ixs = self
            .token_withdraw_instructions(
                &account,
                closable_token_bank_opt.unwrap().mint,
                u64::MAX,
                false,
            )
            .await?;

        account.deactivate_token_position(closable_token_position_raw_index_opt.unwrap());
        return Ok(withdraw_ixs);
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn serum3_place_order(
        &self,
        name: &str,
        side: Serum3Side,
        limit_price: u64,
        max_base_qty: u64,
        max_native_quote_qty_including_fees: u64,
        self_trade_behavior: Serum3SelfTradeBehavior,
        order_type: Serum3OrderType,
        client_order_id: u64,
        limit: u16,
    ) -> anyhow::Result<Signature> {
        let mut account = self.mango_account().await?.clone();
        let market_index = self.context.serum3_market_index(name);
        let create_or_replace_ixs = self
            .serum3_create_or_replace_account_instruction(&mut account, market_index, side)
            .await?;
        let place_order_ixs = self
            .serum3_place_order_instruction(
                &account,
                market_index,
                side,
                limit_price,
                max_base_qty,
                max_native_quote_qty_including_fees,
                self_trade_behavior,
                order_type,
                client_order_id,
                limit,
            )
            .await?;

        let mut ixs = PreparedInstructions::new();
        ixs.append(create_or_replace_ixs);
        ixs.append(place_order_ixs);
        self.send_and_confirm_authority_tx(ixs.to_instructions())
            .await
    }

    pub async fn serum3_settle_funds(&self, name: &str) -> anyhow::Result<Signature> {
        let market_index = self.context.serum3_market_index(name);
        let s3 = self.context.serum3(market_index);
        let base = self.context.serum3_base_token(market_index);
        let quote = self.context.serum3_quote_token(market_index);

        let account = self.mango_account().await?;
        let open_orders = account.serum3_orders(market_index).unwrap().open_orders;

        let ix = self.serum3_settle_funds_instruction(s3, base, quote, open_orders);
        self.send_and_confirm_authority_tx(ix.to_instructions())
            .await
    }

    pub fn serum3_settle_funds_instruction(
        &self,
        s3: &Serum3MarketContext,
        base: &TokenContext,
        quote: &TokenContext,
        open_orders: Pubkey,
    ) -> PreparedInstructions {
        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: anchor_lang::ToAccountMetas::to_account_metas(
                &mango_v4::accounts::Serum3SettleFundsV2 {
                    v1: mango_v4::accounts::Serum3SettleFunds {
                        group: self.group(),
                        account: self.mango_account_address,
                        open_orders,
                        quote_bank: quote.first_bank(),
                        quote_vault: quote.first_vault(),
                        base_bank: base.first_bank(),
                        base_vault: base.first_vault(),
                        serum_market: s3.address,
                        serum_program: s3.serum_program,
                        serum_market_external: s3.serum_market_external,
                        market_base_vault: s3.coin_vault,
                        market_quote_vault: s3.pc_vault,
                        market_vault_signer: s3.vault_signer,
                        owner: self.authority(),
                        token_program: Token::id(),
                    },
                    v2: mango_v4::accounts::Serum3SettleFundsV2Extra {
                        quote_oracle: quote.oracle,
                        base_oracle: base.oracle,
                    },
                },
                None,
            ),
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::Serum3SettleFundsV2 {
                fees_to_dao: true,
            }),
        };

        PreparedInstructions::from_single(
            ix,
            self.context.compute_estimates.cu_per_mango_instruction,
        )
    }

    pub fn serum3_cancel_all_orders_instruction(
        &self,
        account: &MangoAccountValue,
        market_index: Serum3MarketIndex,
        limit: u8,
    ) -> anyhow::Result<PreparedInstructions> {
        let s3 = self.context.serum3(market_index);
        let open_orders = account.serum3_orders(market_index)?.open_orders;

        let ixs = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::Serum3CancelAllOrders {
                        group: self.group(),
                        account: self.mango_account_address,
                        open_orders,
                        market_bids: s3.bids,
                        market_asks: s3.asks,
                        market_event_queue: s3.event_q,
                        serum_market: s3.address,
                        serum_program: s3.serum_program,
                        serum_market_external: s3.serum_market_external,
                        owner: self.authority(),
                    },
                    None,
                ),
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::Serum3CancelAllOrders { limit },
                ),
            },
            self.instruction_cu(0)
                + self.context.compute_estimates.cu_per_serum3_order_cancel * limit as u32,
        );

        Ok(ixs)
    }

    pub async fn serum3_cancel_all_orders(
        &self,
        market_name: &str,
    ) -> Result<Vec<u128>, anyhow::Error> {
        let market_index = self.context.serum3_market_index(market_name);
        let account = self.mango_account().await?;
        let open_orders = account.serum3_orders(market_index).unwrap().open_orders;
        let open_orders_acc = self.account_fetcher.fetch_raw_account(&open_orders).await?;
        let open_orders_bytes = open_orders_acc.data();
        let open_orders_data: &serum_dex::state::OpenOrders = bytemuck::from_bytes(
            &open_orders_bytes[5..5 + std::mem::size_of::<serum_dex::state::OpenOrders>()],
        );

        let mut orders = vec![];
        for order_id in open_orders_data.orders {
            if order_id != 0 {
                // TODO: find side for order_id, and only cancel the relevant order
                self.serum3_cancel_order(market_name, Serum3Side::Bid, order_id)
                    .await
                    .ok();
                self.serum3_cancel_order(market_name, Serum3Side::Ask, order_id)
                    .await
                    .ok();

                orders.push(order_id);
            }
        }

        Ok(orders)
    }

    pub async fn serum3_liq_force_cancel_orders_instruction(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        market_index: Serum3MarketIndex,
        open_orders: &Pubkey,
    ) -> anyhow::Result<PreparedInstructions> {
        let s3 = self.context.serum3(market_index);
        let base = self.context.serum3_base_token(market_index);
        let quote = self.context.serum3_quote_token(market_index);
        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas(liqee.1, vec![], vec![], vec![])
            .await
            .unwrap();

        let limit = 5;
        let ix = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::Serum3LiqForceCancelOrders {
                            group: self.group(),
                            account: *liqee.0,
                            open_orders: *open_orders,
                            serum_market: s3.address,
                            serum_program: s3.serum_program,
                            serum_market_external: s3.serum_market_external,
                            market_bids: s3.bids,
                            market_asks: s3.asks,
                            market_event_queue: s3.event_q,
                            market_base_vault: s3.coin_vault,
                            market_quote_vault: s3.pc_vault,
                            market_vault_signer: s3.vault_signer,
                            quote_bank: quote.first_bank(),
                            quote_vault: quote.first_vault(),
                            base_bank: base.first_bank(),
                            base_vault: base.first_vault(),
                            token_program: Token::id(),
                        },
                        None,
                    );
                    ams.extend(health_remaining_ams.into_iter());
                    ams
                },
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::Serum3LiqForceCancelOrders { limit },
                ),
            },
            self.instruction_cu(health_cu)
                + self.context.compute_estimates.cu_per_serum3_order_cancel * limit as u32,
        );
        Ok(ix)
    }

    pub async fn openbook_v2_liq_force_cancel_orders_instruction(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        market_index: OpenbookV2MarketIndex,
        open_orders: &Pubkey,
    ) -> anyhow::Result<PreparedInstructions> {
        let openbook_v2_market = self.context.openbook_v2(market_index);
        let base = self.context.token(openbook_v2_market.base_token_index);
        let quote = self.context.token(openbook_v2_market.quote_token_index);
        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas(liqee.1, vec![], vec![], vec![])
            .await
            .unwrap();

        let limit = 5;
        let ix = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::OpenbookV2LiqForceCancelOrders {
                            payer: self.authority(),
                            group: self.group(),
                            account: *liqee.0,
                            open_orders: *open_orders,
                            openbook_v2_market: openbook_v2_market.address,
                            openbook_v2_program: openbook_v2_market.openbook_v2_program,
                            openbook_v2_market_external: openbook_v2_market.market_external,
                            bids: openbook_v2_market.bids,
                            asks: openbook_v2_market.asks,
                            event_heap: openbook_v2_market.event_heap,
                            market_base_vault: openbook_v2_market.market_base_vault,
                            market_quote_vault: openbook_v2_market.market_quote_vault,
                            market_vault_signer: openbook_v2_market.market_authority,
                            quote_bank: quote.first_bank(),
                            quote_vault: quote.first_vault(),
                            base_bank: base.first_bank(),
                            base_vault: base.first_vault(),
                            token_program: Token::id(),
                            system_program: System::id(),
                        },
                        None,
                    );
                    ams.extend(health_remaining_ams.into_iter());
                    ams
                },
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::OpenbookV2LiqForceCancelOrders { limit },
                ),
            },
            self.instruction_cu(health_cu)
                + self.context.compute_estimates.cu_per_serum3_order_cancel * limit as u32,
        );
        Ok(ix)
    }

    pub async fn serum3_liq_force_cancel_orders(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        market_index: Serum3MarketIndex,
        open_orders: &Pubkey,
    ) -> anyhow::Result<Signature> {
        let ixs = self
            .serum3_liq_force_cancel_orders_instruction(liqee, market_index, open_orders)
            .await?;
        self.send_and_confirm_permissionless_tx(ixs.to_instructions())
            .await
    }

    pub async fn serum3_cancel_order(
        &self,
        market_name: &str,
        side: Serum3Side,
        order_id: u128,
    ) -> anyhow::Result<Signature> {
        let market_index = self.context.serum3_market_index(market_name);
        let s3 = self.context.serum3(market_index);

        let account = self.mango_account().await?;
        let open_orders = account.serum3_orders(market_index).unwrap().open_orders;

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::Serum3CancelOrder {
                        group: self.group(),
                        account: self.mango_account_address,
                        serum_market: s3.address,
                        serum_program: s3.serum_program,
                        serum_market_external: s3.serum_market_external,
                        open_orders,
                        market_bids: s3.bids,
                        market_asks: s3.asks,
                        market_event_queue: s3.event_q,
                        owner: self.authority(),
                    },
                    None,
                )
            },
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::Serum3CancelOrder {
                side,
                order_id,
            }),
        };
        self.send_and_confirm_authority_tx(vec![ix]).await
    }

    //
    // Perps
    //

    #[allow(clippy::too_many_arguments)]
    pub async fn perp_place_order_instruction(
        &self,
        account: &MangoAccountValue,
        market_index: PerpMarketIndex,
        side: Side,
        price_lots: i64,
        max_base_lots: i64,
        max_quote_lots: i64,
        client_order_id: u64,
        order_type: PlaceOrderType,
        reduce_only: bool,
        expiry_timestamp: u64,
        limit: u8,
        self_trade_behavior: SelfTradeBehavior,
    ) -> anyhow::Result<PreparedInstructions> {
        let mut ixs = PreparedInstructions::new();

        let perp = self.context.perp(market_index);
        let mut account = account.clone();

        let close_perp_ixs_opt = self
            .replace_perp_market_if_needed(&account, market_index)
            .await?;

        if let Some((close_perp_ixs, modified_account)) = close_perp_ixs_opt {
            account = modified_account;
            ixs.append(close_perp_ixs);
        }

        let (health_remaining_metas, health_cu) = self
            .derive_health_check_remaining_account_metas(
                &account,
                vec![],
                vec![],
                vec![market_index],
            )
            .await?;

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::PerpPlaceOrder {
                        group: self.group(),
                        account: self.mango_account_address,
                        owner: self.authority(),
                        perp_market: perp.address,
                        bids: perp.bids,
                        asks: perp.asks,
                        event_queue: perp.event_queue,
                        oracle: perp.oracle,
                    },
                    None,
                );
                ams.extend(health_remaining_metas.into_iter());
                ams
            },
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::PerpPlaceOrderV2 {
                side,
                price_lots,
                max_base_lots,
                max_quote_lots,
                client_order_id,
                order_type,
                reduce_only,
                expiry_timestamp,
                limit,
                self_trade_behavior,
            }),
        };

        ixs.push(
            ix,
            self.instruction_cu(health_cu)
                + self.context.compute_estimates.cu_per_perp_order_match * limit as u32,
        );

        Ok(ixs)
    }

    async fn replace_perp_market_if_needed(
        &self,
        account: &MangoAccountValue,
        perk_market_index: PerpMarketIndex,
    ) -> anyhow::Result<Option<(PreparedInstructions, MangoAccountValue)>> {
        let context = &self.context;
        let settle_token_index = context.perp(perk_market_index).settle_token_index;

        let mut account = account.clone();
        let enforce_position_result =
            account.ensure_perp_position(perk_market_index, settle_token_index);

        if !enforce_position_result
            .is_anchor_error_with_code(MangoError::NoFreePerpPositionIndex.error_code())
        {
            return Ok(None);
        }

        let perp_position_to_close_opt = account.find_first_active_unused_perp_position();
        match perp_position_to_close_opt {
            Some(perp_position_to_close) => {
                let close_ix = self
                    .perp_deactivate_position_instruction(perp_position_to_close.market_index)
                    .await?;

                let previous_market = context.perp(perp_position_to_close.market_index);
                account.deactivate_perp_position(
                    perp_position_to_close.market_index,
                    previous_market.settle_token_index,
                )?;
                account.ensure_perp_position(perk_market_index, settle_token_index)?;

                Ok(Some((close_ix, account)))
            }
            None => anyhow::bail!("No perp market slot available"),
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn perp_place_order(
        &self,
        market_index: PerpMarketIndex,
        side: Side,
        price_lots: i64,
        max_base_lots: i64,
        max_quote_lots: i64,
        client_order_id: u64,
        order_type: PlaceOrderType,
        reduce_only: bool,
        expiry_timestamp: u64,
        limit: u8,
        self_trade_behavior: SelfTradeBehavior,
    ) -> anyhow::Result<Signature> {
        let account = self.mango_account().await?;
        let ixs = self
            .perp_place_order_instruction(
                &account,
                market_index,
                side,
                price_lots,
                max_base_lots,
                max_quote_lots,
                client_order_id,
                order_type,
                reduce_only,
                expiry_timestamp,
                limit,
                self_trade_behavior,
            )
            .await?;
        self.send_and_confirm_authority_tx(ixs.to_instructions())
            .await
    }

    pub fn perp_cancel_all_orders_instruction(
        &self,
        market_index: PerpMarketIndex,
        limit: u8,
    ) -> anyhow::Result<PreparedInstructions> {
        let perp = self.context.perp(market_index);

        let ixs = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::PerpCancelAllOrders {
                            group: self.group(),
                            account: self.mango_account_address,
                            owner: self.authority(),
                            perp_market: perp.address,
                            bids: perp.bids,
                            asks: perp.asks,
                        },
                        None,
                    )
                },
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::PerpCancelAllOrders { limit },
                ),
            },
            self.instruction_cu(0)
                + self.context.compute_estimates.cu_per_perp_order_cancel * limit as u32,
        );
        Ok(ixs)
    }

    pub async fn perp_deactivate_position(
        &self,
        market_index: PerpMarketIndex,
    ) -> anyhow::Result<Signature> {
        let ixs = self
            .perp_deactivate_position_instruction(market_index)
            .await?;
        self.send_and_confirm_authority_tx(ixs.to_instructions())
            .await
    }

    async fn perp_deactivate_position_instruction(
        &self,
        market_index: PerpMarketIndex,
    ) -> anyhow::Result<PreparedInstructions> {
        let perp = self.context.perp(market_index);

        let ixs = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::PerpDeactivatePosition {
                            group: self.group(),
                            account: self.mango_account_address,
                            owner: self.authority(),
                            perp_market: perp.address,
                        },
                        None,
                    );
                    ams
                },
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::PerpDeactivatePosition {},
                ),
            },
            self.context.compute_estimates.cu_per_mango_instruction,
        );
        Ok(ixs)
    }

    pub async fn perp_settle_pnl_instruction(
        &self,
        market_index: PerpMarketIndex,
        account_a: (&Pubkey, &MangoAccountValue),
        account_b: (&Pubkey, &MangoAccountValue),
    ) -> anyhow::Result<PreparedInstructions> {
        let perp = self.context.perp(market_index);
        let settlement_token = self.context.token(perp.settle_token_index);

        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas_two_accounts(
                account_a.1,
                account_b.1,
                &[],
                &[],
            )
            .await
            .unwrap();

        let ixs = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::PerpSettlePnl {
                            group: self.group(),
                            settler: self.mango_account_address,
                            settler_owner: self.authority(),
                            perp_market: perp.address,
                            account_a: *account_a.0,
                            account_b: *account_b.0,
                            oracle: perp.oracle,
                            settle_bank: settlement_token.first_bank(),
                            settle_oracle: settlement_token.oracle,
                        },
                        None,
                    );
                    ams.extend(health_remaining_ams.into_iter());
                    ams
                },
                data: anchor_lang::InstructionData::data(&mango_v4::instruction::PerpSettlePnl {}),
            },
            self.instruction_cu(health_cu),
        );
        Ok(ixs)
    }

    pub async fn perp_settle_pnl(
        &self,
        market_index: PerpMarketIndex,
        account_a: (&Pubkey, &MangoAccountValue),
        account_b: (&Pubkey, &MangoAccountValue),
    ) -> anyhow::Result<Signature> {
        let ixs = self
            .perp_settle_pnl_instruction(market_index, account_a, account_b)
            .await?;
        self.send_and_confirm_permissionless_tx(ixs.to_instructions())
            .await
    }

    pub async fn perp_liq_force_cancel_orders(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        market_index: PerpMarketIndex,
    ) -> anyhow::Result<Signature> {
        let perp = self.context.perp(market_index);

        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas(liqee.1, vec![], vec![], vec![])
            .await
            .unwrap();

        let limit = 5;
        let ixs = PreparedInstructions::from_single(
            Instruction {
                program_id: mango_v4::id(),
                accounts: {
                    let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                        &mango_v4::accounts::PerpLiqForceCancelOrders {
                            group: self.group(),
                            account: *liqee.0,
                            perp_market: perp.address,
                            bids: perp.bids,
                            asks: perp.asks,
                        },
                        None,
                    );
                    ams.extend(health_remaining_ams.into_iter());
                    ams
                },
                data: anchor_lang::InstructionData::data(
                    &mango_v4::instruction::PerpLiqForceCancelOrders { limit },
                ),
            },
            self.instruction_cu(health_cu)
                + self.context.compute_estimates.cu_per_perp_order_cancel * limit as u32,
        );
        self.send_and_confirm_permissionless_tx(ixs.to_instructions())
            .await
    }

    pub async fn perp_liq_base_or_positive_pnl_instruction(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        market_index: PerpMarketIndex,
        max_base_transfer: i64,
        max_pnl_transfer: u64,
    ) -> anyhow::Result<PreparedInstructions> {
        let perp = self.context.perp(market_index);
        let settle_token_info = self.context.token(perp.settle_token_index);
        let mango_account = &self.mango_account().await?;

        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas_two_accounts(
                mango_account,
                liqee.1,
                &[],
                &[],
            )
            .await
            .unwrap();

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::PerpLiqBaseOrPositivePnl {
                        group: self.group(),
                        perp_market: perp.address,
                        oracle: perp.oracle,
                        liqor: self.mango_account_address,
                        liqor_owner: self.authority(),
                        liqee: *liqee.0,
                        settle_bank: settle_token_info.first_bank(),
                        settle_vault: settle_token_info.first_vault(),
                        settle_oracle: settle_token_info.oracle,
                    },
                    None,
                );
                ams.extend(health_remaining_ams.into_iter());
                ams
            },
            data: anchor_lang::InstructionData::data(
                &mango_v4::instruction::PerpLiqBaseOrPositivePnl {
                    max_base_transfer,
                    max_pnl_transfer,
                },
            ),
        };
        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(health_cu),
        ))
    }

    pub async fn perp_liq_negative_pnl_or_bankruptcy_instruction(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        market_index: PerpMarketIndex,
        max_liab_transfer: u64,
    ) -> anyhow::Result<PreparedInstructions> {
        let group = account_fetcher_fetch_anchor_account::<Group>(
            &*self.account_fetcher,
            &self.context.group,
        )
        .await?;

        let mango_account = &self.mango_account().await?;
        let perp = self.context.perp(market_index);
        let settle_token_info = self.context.token(perp.settle_token_index);
        let insurance_token_info = self.context.token_by_mint(&group.insurance_mint)?;

        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas_two_accounts(
                mango_account,
                liqee.1,
                &[insurance_token_info.token_index],
                &[],
            )
            .await
            .unwrap();

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::PerpLiqNegativePnlOrBankruptcyV2 {
                        group: self.group(),
                        perp_market: perp.address,
                        oracle: perp.oracle,
                        liqor: self.mango_account_address,
                        liqor_owner: self.authority(),
                        liqee: *liqee.0,
                        settle_bank: settle_token_info.first_bank(),
                        settle_vault: settle_token_info.first_vault(),
                        settle_oracle: settle_token_info.oracle,
                        insurance_vault: group.insurance_vault,
                        insurance_bank: insurance_token_info.first_bank(),
                        insurance_bank_vault: insurance_token_info.first_vault(),
                        insurance_oracle: insurance_token_info.oracle,
                        token_program: Token::id(),
                    },
                    None,
                );
                ams.extend(health_remaining_ams.into_iter());
                ams
            },
            data: anchor_lang::InstructionData::data(
                &mango_v4::instruction::PerpLiqNegativePnlOrBankruptcyV2 { max_liab_transfer },
            ),
        };
        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(health_cu),
        ))
    }

    pub async fn token_charge_collateral_fees_instruction(
        &self,
        account: (&Pubkey, &MangoAccountValue),
    ) -> anyhow::Result<PreparedInstructions> {
        let (mut health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas(account.1, vec![], vec![], vec![])
            .await
            .unwrap();

        // The instruction requires mutable banks
        for am in &mut health_remaining_ams[0..account.1.active_token_positions().count()] {
            am.is_writable = true;
        }

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::TokenChargeCollateralFees {
                        group: self.group(),
                        account: *account.0,
                    },
                    None,
                );
                ams.extend(health_remaining_ams);
                ams
            },
            data: anchor_lang::InstructionData::data(
                &mango_v4::instruction::TokenChargeCollateralFees {},
            ),
        };

        let mut chargeable_token_positions = 0;
        for tp in account.1.active_token_positions() {
            let bank = self.first_bank(tp.token_index).await?;
            let native = tp.native(&bank);
            if native.is_positive()
                && bank.maint_asset_weight.is_positive()
                && bank.collateral_fee_per_day > 0.0
            {
                chargeable_token_positions += 1;
            }
        }

        let cu_est = &self.context.compute_estimates;
        let cu = cu_est.cu_per_charge_collateral_fees
            + cu_est.cu_per_charge_collateral_fees_token * chargeable_token_positions
            + health_cu;

        Ok(PreparedInstructions::from_single(ix, cu))
    }

    //
    // Liquidation
    //

    pub async fn token_liq_with_token_instruction(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        asset_token_index: TokenIndex,
        liab_token_index: TokenIndex,
        max_liab_transfer: I80F48,
    ) -> anyhow::Result<PreparedInstructions> {
        let mango_account = &self.mango_account().await?;
        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas_two_accounts(
                mango_account,
                liqee.1,
                &[],
                &[asset_token_index, liab_token_index],
            )
            .await
            .unwrap();

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::TokenLiqWithToken {
                        group: self.group(),
                        liqee: *liqee.0,
                        liqor: self.mango_account_address,
                        liqor_owner: self.authority(),
                    },
                    None,
                );
                ams.extend(health_remaining_ams);
                ams
            },
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::TokenLiqWithToken {
                asset_token_index,
                liab_token_index,
                max_liab_transfer,
            }),
        };
        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(health_cu),
        ))
    }

    pub async fn token_liq_bankruptcy_instruction(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        liab_token_index: TokenIndex,
        max_liab_transfer: I80F48,
    ) -> anyhow::Result<PreparedInstructions> {
        let group = account_fetcher_fetch_anchor_account::<Group>(
            &*self.account_fetcher,
            &self.context.group,
        )
        .await?;

        let mango_account = &self.mango_account().await?;

        let insurance_info = self.context.token_by_mint(&group.insurance_mint)?;
        let liab_info = self.context.token(liab_token_index);

        let bank_remaining_ams = liab_info
            .banks()
            .iter()
            .map(|bank_pubkey| util::to_writable_account_meta(*bank_pubkey))
            .collect::<Vec<_>>();

        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas_two_accounts(
                mango_account,
                liqee.1,
                &[insurance_info.token_index],
                &[insurance_info.token_index, liab_token_index],
            )
            .await
            .unwrap();

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::TokenLiqBankruptcy {
                        group: self.group(),
                        liqee: *liqee.0,
                        liqor: self.mango_account_address,
                        liqor_owner: self.authority(),
                        liab_mint_info: liab_info.mint_info_address,
                        quote_vault: insurance_info.first_vault(),
                        insurance_vault: group.insurance_vault,
                        token_program: Token::id(),
                    },
                    None,
                );
                ams.extend(bank_remaining_ams);
                ams.extend(health_remaining_ams);
                ams
            },
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::TokenLiqBankruptcy {
                max_liab_transfer,
            }),
        };
        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(health_cu),
        ))
    }

    pub async fn token_conditional_swap_trigger_instruction(
        &self,
        liqee: (&Pubkey, &MangoAccountValue),
        token_conditional_swap_id: u64,
        max_buy_token_to_liqee: u64,
        max_sell_token_to_liqor: u64,
        min_buy_token: u64,
        min_taker_price: f32,
        extra_affected_tokens: &[TokenIndex],
    ) -> anyhow::Result<PreparedInstructions> {
        let mango_account = &self.mango_account().await?;
        let (tcs_index, tcs) = liqee
            .1
            .token_conditional_swap_by_id(token_conditional_swap_id)?;

        let affected_tokens = extra_affected_tokens
            .iter()
            .chain(&[tcs.buy_token_index, tcs.sell_token_index])
            .copied()
            .collect_vec();
        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas_two_accounts(
                mango_account,
                liqee.1,
                &affected_tokens,
                &[tcs.buy_token_index, tcs.sell_token_index],
            )
            .await
            .unwrap();

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::TokenConditionalSwapTrigger {
                        group: self.group(),
                        liqee: *liqee.0,
                        liqor: self.mango_account_address,
                        liqor_authority: self.authority(),
                    },
                    None,
                );
                ams.extend(health_remaining_ams);
                ams
            },
            data: anchor_lang::InstructionData::data(
                &mango_v4::instruction::TokenConditionalSwapTriggerV2 {
                    token_conditional_swap_id,
                    token_conditional_swap_index: tcs_index.try_into().unwrap(),
                    max_buy_token_to_liqee,
                    max_sell_token_to_liqor,
                    min_buy_token,
                    min_taker_price,
                },
            ),
        };
        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(health_cu),
        ))
    }

    pub async fn token_conditional_swap_start_instruction(
        &self,
        account: (&Pubkey, &MangoAccountValue),
        token_conditional_swap_id: u64,
    ) -> anyhow::Result<PreparedInstructions> {
        let (tcs_index, tcs) = account
            .1
            .token_conditional_swap_by_id(token_conditional_swap_id)?;

        let affected_tokens = vec![tcs.buy_token_index, tcs.sell_token_index];
        let (health_remaining_ams, health_cu) = self
            .derive_health_check_remaining_account_metas(account.1, vec![], affected_tokens, vec![])
            .await
            .unwrap();

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::TokenConditionalSwapStart {
                        group: self.group(),
                        liqee: *account.0,
                        liqor: self.mango_account_address,
                        liqor_authority: self.authority(),
                    },
                    None,
                );
                ams.extend(health_remaining_ams);
                ams
            },
            data: anchor_lang::InstructionData::data(
                &mango_v4::instruction::TokenConditionalSwapStart {
                    token_conditional_swap_id,
                    token_conditional_swap_index: tcs_index.try_into().unwrap(),
                },
            ),
        };
        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(health_cu),
        ))
    }

    // health region

    pub async fn health_region_begin_instruction(
        &self,
        account: &MangoAccountValue,
        affected_tokens: Vec<TokenIndex>,
        writable_banks: Vec<TokenIndex>,
        affected_perp_markets: Vec<PerpMarketIndex>,
    ) -> anyhow::Result<PreparedInstructions> {
        let (health_remaining_metas, _health_cu) = self
            .derive_health_check_remaining_account_metas(
                account,
                affected_tokens,
                writable_banks,
                affected_perp_markets,
            )
            .await?;

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::HealthRegionBegin {
                        group: self.group(),
                        account: self.mango_account_address,
                        instructions: solana_sdk::sysvar::instructions::id(),
                    },
                    None,
                );
                ams.extend(health_remaining_metas.into_iter());
                ams
            },
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::HealthRegionBegin {}),
        };

        // There's only a single health computation in End
        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(0),
        ))
    }

    pub async fn health_region_end_instruction(
        &self,
        account: &MangoAccountValue,
        affected_tokens: Vec<TokenIndex>,
        writable_banks: Vec<TokenIndex>,
        affected_perp_markets: Vec<PerpMarketIndex>,
    ) -> anyhow::Result<PreparedInstructions> {
        let (health_remaining_metas, health_cu) = self
            .derive_health_check_remaining_account_metas(
                account,
                affected_tokens,
                writable_banks,
                affected_perp_markets,
            )
            .await?;

        let ix = Instruction {
            program_id: mango_v4::id(),
            accounts: {
                let mut ams = anchor_lang::ToAccountMetas::to_account_metas(
                    &mango_v4::accounts::HealthRegionEnd {
                        account: self.mango_account_address,
                    },
                    None,
                );
                ams.extend(health_remaining_metas.into_iter());
                ams
            },
            data: anchor_lang::InstructionData::data(&mango_v4::instruction::HealthRegionEnd {}),
        };

        Ok(PreparedInstructions::from_single(
            ix,
            self.instruction_cu(health_cu),
        ))
    }

    // Swap (jupiter, sanctum)
    pub fn swap(&self) -> swap::Swap {
        swap::Swap { mango_client: self }
    }

    pub fn jupiter_v6(&self) -> swap::jupiter_v6::JupiterV6 {
        swap::jupiter_v6::JupiterV6 {
            mango_client: self,
            timeout_duration: self.client.config.jupiter_timeout,
        }
    }

    pub fn sanctum(&self) -> swap::sanctum::Sanctum {
        swap::sanctum::Sanctum {
            mango_client: self,
            timeout_duration: self.client.config.sanctum_timeout,
        }
    }

    pub(crate) async fn deserialize_instructions_and_alts(
        &self,
        message: &solana_sdk::message::VersionedMessage,
    ) -> anyhow::Result<(Vec<Instruction>, Vec<AddressLookupTableAccount>)> {
        let lookups = message.address_table_lookups().unwrap_or_default();
        let address_lookup_tables = self
            .fetch_address_lookup_tables(lookups.iter().map(|a| &a.account_key))
            .await?;

        let mut account_keys = message.static_account_keys().to_vec();
        for (lookups, table) in lookups.iter().zip(address_lookup_tables.iter()) {
            account_keys.extend(
                lookups
                    .writable_indexes
                    .iter()
                    .map(|&index| table.addresses[index as usize]),
            );
        }
        for (lookups, table) in lookups.iter().zip(address_lookup_tables.iter()) {
            account_keys.extend(
                lookups
                    .readonly_indexes
                    .iter()
                    .map(|&index| table.addresses[index as usize]),
            );
        }

        let compiled_ix = message
            .instructions()
            .iter()
            .map(|ci| solana_sdk::instruction::Instruction {
                program_id: *ci.program_id(&account_keys),
                accounts: ci
                    .accounts
                    .iter()
                    .map(|&index| AccountMeta {
                        pubkey: account_keys[index as usize],
                        is_signer: message.is_signer(index.into()),
                        is_writable: message.is_maybe_writable(index.into()),
                    })
                    .collect(),
                data: ci.data.clone(),
            })
            .collect();

        Ok((compiled_ix, address_lookup_tables))
    }

    pub async fn fetch_address_lookup_table(
        &self,
        address: Pubkey,
    ) -> anyhow::Result<AddressLookupTableAccount> {
        let raw = self
            .account_fetcher
            .fetch_raw_account_lookup_table(&address)
            .await?;
        let data = AddressLookupTable::deserialize(&raw.data())?;
        Ok(AddressLookupTableAccount {
            key: address,
            addresses: data.addresses.to_vec(),
        })
    }

    pub async fn fetch_address_lookup_tables(
        &self,
        alts: impl Iterator<Item = &Pubkey>,
    ) -> anyhow::Result<Vec<AddressLookupTableAccount>> {
        stream::iter(alts)
            .then(|a| self.fetch_address_lookup_table(*a))
            .try_collect::<Vec<_>>()
            .await
    }

    pub async fn mango_address_lookup_tables(
        &self,
    ) -> anyhow::Result<Vec<AddressLookupTableAccount>> {
        stream::iter(self.context.address_lookup_tables.iter())
            .then(|&k| self.fetch_address_lookup_table(k))
            .try_collect::<Vec<_>>()
            .await
    }

    fn instruction_cu(&self, health_cu: u32) -> u32 {
        self.context.compute_estimates.cu_per_mango_instruction + health_cu
    }

    pub async fn send_and_confirm_authority_tx(
        &self,
        instructions: Vec<Instruction>,
    ) -> anyhow::Result<Signature> {
        let mut tx_builder = TransactionBuilder {
            instructions,
            ..self.transaction_builder().await?
        };
        tx_builder.signers.push(self.authority.clone());
        tx_builder.send_and_confirm(&self.client).await
    }

    pub async fn send_and_confirm_permissionless_tx(
        &self,
        instructions: Vec<Instruction>,
    ) -> anyhow::Result<Signature> {
        TransactionBuilder {
            instructions,
            ..self.transaction_builder().await?
        }
        .send_and_confirm(&self.client)
        .await
    }

    pub async fn transaction_builder(&self) -> anyhow::Result<TransactionBuilder> {
        let fee_payer = self.client.fee_payer();
        Ok(TransactionBuilder {
            instructions: vec![],
            address_lookup_tables: self.mango_address_lookup_tables().await?,
            payer: fee_payer.pubkey(),
            signers: vec![fee_payer],
            config: self.client.config.transaction_builder_config.clone(),
        })
    }

    pub async fn simulate(
        &self,
        instructions: Vec<Instruction>,
    ) -> anyhow::Result<SimulateTransactionResponse> {
        let fee_payer = self.client.fee_payer();
        TransactionBuilder {
            instructions,
            address_lookup_tables: vec![],
            payer: fee_payer.pubkey(),
            signers: vec![fee_payer],
            config: self.client.config.transaction_builder_config.clone(),
        }
        .simulate(&self.client)
        .await
    }

    pub async fn loop_check_for_context_changes_and_abort(
        mango_client: Arc<MangoClient>,
        interval: Duration,
    ) {
        let mut delay = crate::delay_interval(interval);
        let rpc_async = mango_client.client.rpc_async();
        loop {
            delay.tick().await;

            let new_context =
                match MangoGroupContext::new_from_rpc(&rpc_async, mango_client.group()).await {
                    Ok(v) => v,
                    Err(e) => {
                        warn!("could not fetch context to check for changes: {e:?}");
                        continue;
                    }
                };

            if mango_client.context.changed_significantly(&new_context) {
                std::process::abort();
            }
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum MangoClientError {
    #[error("Transaction simulation error. Error: {err:?}, Logs: {}",
    .logs.iter().join("; ")
    )]
    SendTransactionPreflightFailure {
        err: Option<TransactionError>,
        logs: Vec<String>,
    },
}

#[derive(Copy, Clone, Debug, Default)]
pub struct TransactionSize {
    pub accounts: usize,
    pub length: usize,
}

impl TransactionSize {
    pub fn is_within_limit(&self) -> bool {
        let limit = Self::limit();
        self.length <= limit.length && self.accounts <= limit.accounts
    }

    pub fn limit() -> Self {
        Self {
            accounts: MAX_ACCOUNTS_PER_TRANSACTION,
            length: solana_sdk::packet::PACKET_DATA_SIZE,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FallbackOracleConfig {
    /// No fallback oracles
    Never,
    /// Only provided fallback oracles are used
    Fixed(Vec<Pubkey>),
    /// The account_fetcher checks for stale oracles and uses fallbacks only for stale oracles
    Dynamic,
    /// Every possible fallback oracle (may cause serious issues with the 64 accounts-per-tx limit)
    All,
}

impl Default for FallbackOracleConfig {
    fn default() -> Self {
        FallbackOracleConfig::Dynamic
    }
}

#[derive(Clone, Default, Builder)]
pub struct TransactionBuilderConfig {
    /// adds a SetComputeUnitPrice instruction in front if none exists
    pub priority_fee_provider: Option<Arc<dyn PriorityFeeProvider>>,
    /// adds a SetComputeUnitBudget instruction if none exists
    pub compute_budget_per_instruction: Option<u32>,
}

impl TransactionBuilderConfig {
    pub fn builder() -> TransactionBuilderConfigBuilder {
        TransactionBuilderConfigBuilder::default()
    }
}

impl TransactionBuilderConfigBuilder {
    pub fn prioritization_micro_lamports(&mut self, cu: Option<u64>) -> &mut Self {
        self.priority_fee_provider(
            cu.map(|cu| {
                Arc::new(FixedPriorityFeeProvider::new(cu)) as Arc<dyn PriorityFeeProvider>
            }),
        )
    }
}

pub struct TransactionBuilder {
    pub instructions: Vec<Instruction>,
    pub address_lookup_tables: Vec<AddressLookupTableAccount>,
    pub signers: Vec<Arc<Keypair>>,
    pub payer: Pubkey,
    pub config: TransactionBuilderConfig,
}

pub type SimulateTransactionResponse =
    solana_client::rpc_response::Response<RpcSimulateTransactionResult>;

impl TransactionBuilder {
    pub async fn transaction(
        &self,
        rpc: &RpcClientAsync,
    ) -> anyhow::Result<solana_sdk::transaction::VersionedTransaction> {
        let (latest_blockhash, _) = rpc
            .get_latest_blockhash_with_commitment(CommitmentConfig::finalized())
            .await?;
        self.transaction_with_blockhash(latest_blockhash)
    }

    fn instructions_with_cu_budget(&self) -> Vec<Instruction> {
        let mut ixs = self.instructions.clone();

        let mut has_compute_unit_price = false;
        let mut has_compute_unit_limit = false;
        let mut cu_instructions = 0;
        for ix in ixs.iter() {
            if ix.program_id != solana_sdk::compute_budget::id() {
                continue;
            }
            cu_instructions += 1;
            match ComputeBudgetInstruction::try_from_slice(&ix.data) {
                Ok(ComputeBudgetInstruction::SetComputeUnitLimit(_)) => {
                    has_compute_unit_limit = true
                }
                Ok(ComputeBudgetInstruction::SetComputeUnitPrice(_)) => {
                    has_compute_unit_price = true
                }
                _ => {}
            }
        }

        let cu_per_ix = self.config.compute_budget_per_instruction.unwrap_or(0);
        if !has_compute_unit_limit && cu_per_ix > 0 {
            let ix_count: u32 = (ixs.len() - cu_instructions).try_into().unwrap();
            ixs.insert(
                0,
                ComputeBudgetInstruction::set_compute_unit_limit(cu_per_ix * ix_count),
            );
        }

        let cu_prio = self
            .config
            .priority_fee_provider
            .as_ref()
            .map(|provider| provider.compute_unit_fee_microlamports())
            .unwrap_or(0);
        if !has_compute_unit_price && cu_prio > 0 {
            ixs.insert(0, ComputeBudgetInstruction::set_compute_unit_price(cu_prio));
        }

        ixs
    }

    pub fn transaction_with_blockhash(
        &self,
        blockhash: Hash,
    ) -> anyhow::Result<solana_sdk::transaction::VersionedTransaction> {
        let ixs = self.instructions_with_cu_budget();
        let v0_message = solana_sdk::message::v0::Message::try_compile(
            &self.payer,
            &ixs,
            &self.address_lookup_tables,
            blockhash,
        )?;
        let versioned_message = solana_sdk::message::VersionedMessage::V0(v0_message);
        let signers = self
            .signers
            .iter()
            .unique_by(|s| s.pubkey())
            .map(|v| v.deref())
            .collect::<Vec<_>>();
        let tx =
            solana_sdk::transaction::VersionedTransaction::try_new(versioned_message, &signers)?;
        Ok(tx)
    }

    // These two send() functions don't really belong into the transaction builder!

    pub async fn send(&self, client: &Client) -> anyhow::Result<Signature> {
        let rpc = client.rpc_async();
        let tx = self.transaction(&rpc).await?;
        client.send_transaction(&tx).await
    }

    pub async fn simulate(&self, client: &Client) -> anyhow::Result<SimulateTransactionResponse> {
        let rpc = client.rpc_async();
        let tx = self.transaction(&rpc).await?;
        Ok(rpc.simulate_transaction(&tx).await?)
    }

    pub async fn send_and_confirm(&self, client: &Client) -> anyhow::Result<Signature> {
        let rpc = client.rpc_async();
        let tx = self.transaction(&rpc).await?;
        let recent_blockhash = tx.message.recent_blockhash();
        let signature = client.send_transaction(&tx).await?;
        wait_for_transaction_confirmation(
            &rpc,
            &signature,
            recent_blockhash,
            &client.config.rpc_confirm_transaction_config,
        )
        .await?;
        Ok(signature)
    }

    pub fn transaction_size(&self) -> anyhow::Result<TransactionSize> {
        let tx = self.transaction_with_blockhash(solana_sdk::hash::Hash::default())?;
        let bytes = bincode::serialize(&tx)?;
        let accounts = tx.message.static_account_keys().len()
            + tx.message
                .address_table_lookups()
                .map(|alts| {
                    alts.iter()
                        .map(|alt| alt.readonly_indexes.len() + alt.writable_indexes.len())
                        .sum()
                })
                .unwrap_or(0);
        Ok(TransactionSize {
            accounts,
            length: bytes.len(),
        })
    }

    pub fn append(&mut self, prepared_instructions: PreparedInstructions) {
        self.instructions
            .extend(prepared_instructions.to_instructions());
    }
}

/// Do some manual unpacking on some ClientErrors
///
/// Unfortunately solana's RpcResponseError will very unhelpfully print [N log messages]
/// instead of showing the actual log messages. This unpacks the error to provide more useful
/// output.
pub fn prettify_client_error(err: anchor_client::ClientError) -> anyhow::Error {
    match err {
        anchor_client::ClientError::SolanaClientError(c) => prettify_solana_client_error(c),
        _ => err.into(),
    }
}

pub fn prettify_solana_client_error(
    err: solana_client::client_error::ClientError,
) -> anyhow::Error {
    use solana_client::client_error::ClientErrorKind;
    use solana_client::rpc_request::{RpcError, RpcResponseErrorData};
    match err.kind() {
        ClientErrorKind::RpcError(RpcError::RpcResponseError { data, .. }) => match data {
            RpcResponseErrorData::SendTransactionPreflightFailure(s) => {
                return MangoClientError::SendTransactionPreflightFailure {
                    err: s.err.clone(),
                    logs: s.logs.clone().unwrap_or_default(),
                }
                .into();
            }
            _ => {}
        },
        _ => {}
    };
    err.into()
}

#[derive(Clone, Copy)]
pub enum JupiterSwapMode {
    ExactIn,
    ExactOut,
}

pub fn keypair_from_cli(keypair: &str) -> Keypair {
    let maybe_keypair = keypair::read_keypair(&mut keypair.as_bytes());
    match maybe_keypair {
        Ok(keypair) => keypair,
        Err(_) => {
            let path = std::path::PathBuf::from_str(&*shellexpand::tilde(keypair)).unwrap();
            keypair::read_keypair_file(path)
                .unwrap_or_else(|_| panic!("Failed to read keypair from {}", keypair))
        }
    }
}

pub fn pubkey_from_cli(pubkey: &str) -> Pubkey {
    match Pubkey::from_str(pubkey) {
        Ok(p) => p,
        Err(_) => keypair_from_cli(pubkey).pubkey(),
    }
}