multiliquid-svm-sdk 0.1.2

Unsigned transaction builders, account codecs, and quoting for Multiliquid on Solana
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
// Generated by scripts/generate-rust-clients.mjs. Do not edit by hand.
//! swap_program: exact ABI from src/idl.json.

use borsh::{BorshDeserialize, BorshSerialize};
use solana_sdk::{instruction::{AccountMeta, Instruction}, pubkey::Pubkey};

pub const PROGRAM_ID: Pubkey = solana_sdk::pubkey!("HaWDr94LKJQT2fXuHJGsSGeQf6M7S68FXpEQLcE5RYs6");
pub const IDL: &str = include_str!("../../idl/swap.json");

pub const GLOBAL_CONFIG_PREFIX: &[u8] = &[103, 108, 111, 98, 97, 108, 95, 99, 111, 110, 102, 105, 103];

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct AdminChanged {
    pub old_admin: Pubkey,
    pub new_admin: Pubkey,
}

impl AdminChanged {
    pub const DISCRIMINATOR: [u8; 8] = [232, 34, 31, 226, 62, 18, 19, 114];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

/// State that tracks configurations related to a specific asset (RWA or stable).
/// PDA seeds [b"asset", asset_mint_address]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct AssetConfig {
    /// asset mint address
    pub mint_address: Pubkey,
    /// NAV data
    pub nav_data: Vec<NavData>,
    /// the max and min prices fetched with the vec above should not have
    /// a bigger difference than this BPS
    pub price_difference_bps: u16,
    /// whether this asset is paused at a program level
    pub paused: bool,
    /// version of the NavData struct
    pub version: u8,
    /// type of the asset
    pub asset_type: AssetType,
    /// how many times this asset is set in a pair
    pub used_in_pairs_count: u16,
    /// bump
    pub bump: u8,
    /// padding in case we need to add more fields in the future (128 bytes for each NavData)
    pub padding: Vec<[u8; 128]>,
}

impl AssetConfig {
    pub const DISCRIMINATOR: [u8; 8] = [57, 112, 247, 166, 247, 64, 140, 23];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

impl AssetConfig {
    /// Fetches and decodes account data without imposing a particular program owner.
    pub async fn fetch_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Option<Self>> {
        rpc.get_account(address).await?
            .map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from))
            .transpose()
    }

    pub async fn fetch<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Self> {
        Self::fetch_maybe(rpc, address).await?
            .ok_or(crate::error::SdkError::AccountNotFound(*address))
    }

    pub async fn fetch_all_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Option<Self>>> {
        let accounts = rpc.get_multiple_accounts(addresses).await?;
        if accounts.len() != addresses.len() {
            return Err(crate::error::SdkError::Rpc("get_multiple_accounts returned an unexpected account count".into()));
        }
        accounts.into_iter().map(|account| {
            account.map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from)).transpose()
        }).collect()
    }

    pub async fn fetch_all<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Self>> {
        Self::fetch_all_maybe(rpc, addresses).await?.into_iter().zip(addresses)
            .map(|(account, address)| account.ok_or(crate::error::SdkError::AccountNotFound(*address)))
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct AssetConfigInitialized {
    pub asset_config: Pubkey,
    pub mint: Pubkey,
    pub asset_type: AssetType,
    pub price_difference_bps: u16,
    pub nav_data: Vec<NavData>,
}

impl AssetConfigInitialized {
    pub const DISCRIMINATOR: [u8; 8] = [155, 228, 155, 62, 174, 164, 61, 147];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct AssetConfigUpdated {
    pub asset_config: Pubkey,
    pub mint: Pubkey,
    pub asset_type: AssetType,
    pub price_difference_bps: u16,
    pub nav_data: Vec<NavData>,
}

impl AssetConfigUpdated {
    pub const DISCRIMINATOR: [u8; 8] = [12, 97, 64, 94, 123, 177, 111, 10];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct AssetPauseChanged {
    pub mint: Pubkey,
    pub paused: bool,
}

impl AssetPauseChanged {
    pub const DISCRIMINATOR: [u8; 8] = [30, 56, 152, 180, 133, 188, 179, 249];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Copy)]
pub enum AssetType {
    Rwa,
    Stable,
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Copy)]
pub enum ExactMode {
    ExactIn,
    ExactOut,
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct FeesClaimed {
    pub fee_wallet: Pubkey,
    pub fee_mint: Pubkey,
    pub amount: u64,
}

impl FeesClaimed {
    pub const DISCRIMINATOR: [u8; 8] = [22, 104, 110, 222, 38, 157, 14, 62];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

/// Multiliquid swap program global configration
/// PDA seeds [b"global_config"]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct GlobalConfig {
    /// MultiLiquid admin
    pub admin: Pubkey,
    /// Wallet address that has the ability to withdraw the fees
    pub fee_wallet: Pubkey,
    /// Protocol fee in basis points (0-10000)
    pub protocol_fees_bps: u16,
    /// whether the whole app is paused
    pub paused: bool,
    /// the new admin that is pending to be set
    pub pending_new_admin: Option<Pubkey>,
    /// bump
    pub bump: u8,
    /// This would be the token that every LP has to maintain a balance of, to pay protocol fees.
    pub fee_token_mint: Pubkey,
    /// Protocol fee in basis points charged on spread fees (0-10000)
    pub spread_protocol_fees_bps: u16,
    /// add some padding
    pub padding: [u8; 94],
}

impl GlobalConfig {
    pub const DISCRIMINATOR: [u8; 8] = [149, 8, 156, 202, 160, 252, 176, 217];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

impl GlobalConfig {
    /// Fetches and decodes account data without imposing a particular program owner.
    pub async fn fetch_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Option<Self>> {
        rpc.get_account(address).await?
            .map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from))
            .transpose()
    }

    pub async fn fetch<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Self> {
        Self::fetch_maybe(rpc, address).await?
            .ok_or(crate::error::SdkError::AccountNotFound(*address))
    }

    pub async fn fetch_all_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Option<Self>>> {
        let accounts = rpc.get_multiple_accounts(addresses).await?;
        if accounts.len() != addresses.len() {
            return Err(crate::error::SdkError::Rpc("get_multiple_accounts returned an unexpected account count".into()));
        }
        accounts.into_iter().map(|account| {
            account.map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from)).transpose()
        }).collect()
    }

    pub async fn fetch_all<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Self>> {
        Self::fetch_all_maybe(rpc, addresses).await?.into_iter().zip(addresses)
            .map(|(account, address)| account.ok_or(crate::error::SdkError::AccountNotFound(*address)))
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct GlobalConfigInitialized {
    pub admin: Pubkey,
    pub fee_wallet: Pubkey,
    pub protocol_fees_bps: u16,
    pub spread_protocol_fees_bps: u16,
    pub fee_token_mint: Pubkey,
    pub paused: bool,
}

impl GlobalConfigInitialized {
    pub const DISCRIMINATOR: [u8; 8] = [5, 221, 172, 158, 77, 87, 157, 113];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct GlobalConfigUpdated {
    pub fee_wallet: Pubkey,
    pub paused: bool,
    pub protocol_fees_bps: u16,
    pub spread_protocol_fees_bps: u16,
    pub fee_token_mint: Pubkey,
}

impl GlobalConfigUpdated {
    pub const DISCRIMINATOR: [u8; 8] = [232, 238, 158, 123, 210, 172, 159, 46];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LiquidityAdded {
    pub liquidity_provider: Pubkey,
    pub mint_address: Pubkey,
    /// tokens pulled from the LP into the vault
    pub amount: u64,
    /// vault balance swept into the treasury, 0 when no sweep happened
    pub treasury_deposit_amount: u64,
}

impl LiquidityAdded {
    pub const DISCRIMINATOR: [u8; 8] = [154, 26, 221, 108, 238, 64, 217, 161];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LiquidityRemoved {
    pub liquidity_provider: Pubkey,
    pub mint_address: Pubkey,
    /// the raw `amount` argument, interpreted per `exact_mode`
    pub amount: u64,
    /// asset tokens actually sent back to the LP
    pub amount_transferred: u64,
    /// whether the withdrawal was served by redeeming from the treasury
    pub treasury_backed: bool,
}

impl LiquidityRemoved {
    pub const DISCRIMINATOR: [u8; 8] = [225, 105, 216, 39, 124, 116, 169, 189];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LpFeeAccountClosed {
    pub liquidity_provider: Pubkey,
    pub fee_token_mint: Pubkey,
    /// remaining fee balance swept back to the LP before the account was closed
    pub amount_returned: u64,
}

impl LpFeeAccountClosed {
    pub const DISCRIMINATOR: [u8; 8] = [103, 159, 170, 253, 58, 140, 131, 138];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

/// LP-specific protocol fee overrides.
/// PDA seeds [b"lp_protocol_fee_config", liquidity_provider]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LpProtocolFeeConfig {
    /// liquidity provider address
    pub liquidity_provider: Pubkey,
    /// Protocol fee in basis points charged on the issuer fee basis
    pub protocol_fees_bps: u16,
    /// Protocol fee in basis points charged on spread fees
    pub spread_protocol_fees_bps: u16,
    pub bump: u8,
    pub treasury_enabled: bool,
    pub padding: [u8; 128],
}

impl LpProtocolFeeConfig {
    pub const DISCRIMINATOR: [u8; 8] = [135, 75, 123, 10, 42, 109, 206, 172];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

impl LpProtocolFeeConfig {
    /// Fetches and decodes account data without imposing a particular program owner.
    pub async fn fetch_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Option<Self>> {
        rpc.get_account(address).await?
            .map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from))
            .transpose()
    }

    pub async fn fetch<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Self> {
        Self::fetch_maybe(rpc, address).await?
            .ok_or(crate::error::SdkError::AccountNotFound(*address))
    }

    pub async fn fetch_all_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Option<Self>>> {
        let accounts = rpc.get_multiple_accounts(addresses).await?;
        if accounts.len() != addresses.len() {
            return Err(crate::error::SdkError::Rpc("get_multiple_accounts returned an unexpected account count".into()));
        }
        accounts.into_iter().map(|account| {
            account.map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from)).transpose()
        }).collect()
    }

    pub async fn fetch_all<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Self>> {
        Self::fetch_all_maybe(rpc, addresses).await?.into_iter().zip(addresses)
            .map(|(account, address)| account.ok_or(crate::error::SdkError::AccountNotFound(*address)))
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LpProtocolFeeConfigUpdated {
    pub liquidity_provider: Pubkey,
    pub protocol_fees_bps: u16,
    pub spread_protocol_fees_bps: u16,
}

impl LpProtocolFeeConfigUpdated {
    pub const DISCRIMINATOR: [u8; 8] = [58, 157, 1, 126, 238, 158, 141, 180];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

/// State that tracks LP configuration for a quote token.
/// PDA seeds [b"lp_stable_config", quote_token, liquidity_provider]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LpStableConfig {
    /// mint address of the quote token
    pub quote_token_mint_address: Pubkey,
    /// whether this LP quote token is paused (for all pairs)
    pub paused: bool,
    /// liquidity provider address
    pub liquidity_provider: Pubkey,
    /// bump
    pub bump: u8,
    /// add some padding
    pub padding: [u8; 128],
}

impl LpStableConfig {
    pub const DISCRIMINATOR: [u8; 8] = [178, 48, 23, 140, 152, 86, 22, 226];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

impl LpStableConfig {
    /// Fetches and decodes account data without imposing a particular program owner.
    pub async fn fetch_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Option<Self>> {
        rpc.get_account(address).await?
            .map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from))
            .transpose()
    }

    pub async fn fetch<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Self> {
        Self::fetch_maybe(rpc, address).await?
            .ok_or(crate::error::SdkError::AccountNotFound(*address))
    }

    pub async fn fetch_all_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Option<Self>>> {
        let accounts = rpc.get_multiple_accounts(addresses).await?;
        if accounts.len() != addresses.len() {
            return Err(crate::error::SdkError::Rpc("get_multiple_accounts returned an unexpected account count".into()));
        }
        accounts.into_iter().map(|account| {
            account.map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from)).transpose()
        }).collect()
    }

    pub async fn fetch_all<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Self>> {
        Self::fetch_all_maybe(rpc, addresses).await?.into_iter().zip(addresses)
            .map(|(account, address)| account.ok_or(crate::error::SdkError::AccountNotFound(*address)))
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LpStableConfigPauseChanged {
    pub liquidity_provider: Pubkey,
    pub mint: Pubkey,
    pub paused: bool,
}

impl LpStableConfigPauseChanged {
    pub const DISCRIMINATOR: [u8; 8] = [127, 23, 108, 124, 24, 91, 232, 50];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct LpTreasuryEnabledChanged {
    pub liquidity_provider: Pubkey,
    pub enabled: bool,
}

impl LpTreasuryEnabledChanged {
    pub const DISCRIMINATOR: [u8; 8] = [105, 98, 154, 187, 217, 205, 205, 126];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

/// NavData is used to store info about the methods to retrieve the NAV data for a specific asset.
/// Currently we support 4 methods:
/// 1. U64FixedAddress: read the price from an onchain account with a fixed address.
/// 2. Hardcoded: read the price from a hardcoded value.
/// 3. PythPush: read the price from a pyth push account.
/// 4. RedstonePush: read the price from a Redstone PriceData account.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub enum NavData {
    U64FixedAddress {
        /// fixed account address
        nav_account_address: Pubkey,
        /// Byte offset of the NAV
        nav_price_offset: u16,
        /// price decimals
        price_decimals: u8,
    },
    Hardcoded {
        /// hardcoded price
        hardcoded_price: u64,
        /// price decimals
        price_decimals: u8,
    },
    PythPush {
        /// Pyth push account address
        pyth_push_account_address: Pubkey,
        /// Pyth feed id
        feed_id: [u8; 32],
        /// Maximum accepted age for the price update
        max_age_secs: u64,
        /// Maximum accepted confidence ratio in basis points
        max_conf_bps: u16,
    },
    RedstonePush {
        /// Redstone PriceData account address
        price_feed_account: Pubkey,
        /// Expected feed id (32 bytes)
        feed_id: [u8; 32],
        /// Maximum accepted age in seconds
        max_age_secs: u64,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct NewAdminProposed {
    pub current_admin: Pubkey,
    pub pending_admin: Pubkey,
}

impl NewAdminProposed {
    pub const DISCRIMINATOR: [u8; 8] = [28, 150, 26, 229, 207, 97, 30, 242];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

/// Account that maintains state for a given quote/base token pairing.
/// PDA seeds [b"pair", liquidity_provider, quote_token_mint_address, base_token_mint_address]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct Pair {
    /// Fee applied when swapping quote to base
    pub redemption_fee_bps: u16,
    /// Fee applied when swapping base to quote
    pub discount_rate_bps: u16,
    /// Mint address of the quote token
    pub quote_token_mint_address: Pubkey,
    /// Mint address of the base token
    pub base_token_mint_address: Pubkey,
    /// liquidiy ptovider (pair owner)
    pub liquidity_provider: Pubkey,
    /// if this pair is paused
    pub paused: bool,
    /// bump
    pub bump: u8,
    /// add some padding
    pub padding: [u8; 128],
}

impl Pair {
    pub const DISCRIMINATOR: [u8; 8] = [85, 72, 49, 176, 182, 228, 141, 82];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

impl Pair {
    /// Fetches and decodes account data without imposing a particular program owner.
    pub async fn fetch_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Option<Self>> {
        rpc.get_account(address).await?
            .map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from))
            .transpose()
    }

    pub async fn fetch<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Self> {
        Self::fetch_maybe(rpc, address).await?
            .ok_or(crate::error::SdkError::AccountNotFound(*address))
    }

    pub async fn fetch_all_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Option<Self>>> {
        let accounts = rpc.get_multiple_accounts(addresses).await?;
        if accounts.len() != addresses.len() {
            return Err(crate::error::SdkError::Rpc("get_multiple_accounts returned an unexpected account count".into()));
        }
        accounts.into_iter().map(|account| {
            account.map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from)).transpose()
        }).collect()
    }

    pub async fn fetch_all<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Self>> {
        Self::fetch_all_maybe(rpc, addresses).await?.into_iter().zip(addresses)
            .map(|(account, address)| account.ok_or(crate::error::SdkError::AccountNotFound(*address)))
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct PairClosed {
    pub pair: Pubkey,
    pub liquidity_provider: Pubkey,
    pub quote_token_mint_address: Pubkey,
    pub base_token_mint_address: Pubkey,
    /// quote tokens sent back to the LP, 0 when the vault stays open for another pair
    pub quote_amount_returned: u64,
    /// base tokens sent back to the LP, 0 when the vault stays open for another pair
    pub base_amount_returned: u64,
}

impl PairClosed {
    pub const DISCRIMINATOR: [u8; 8] = [44, 133, 115, 118, 95, 41, 87, 136];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct PairInitialized {
    pub pair: Pubkey,
    pub liquidity_provider: Pubkey,
    pub quote_token_mint_address: Pubkey,
    pub base_token_mint_address: Pubkey,
    pub redemption_fee_bps: u16,
    pub discount_rate_bps: u16,
}

impl PairInitialized {
    pub const DISCRIMINATOR: [u8; 8] = [32, 143, 168, 185, 98, 225, 71, 148];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct PairUpdated {
    pub pair: Pubkey,
    pub liquidity_provider: Pubkey,
    pub redemption_fee_bps: u16,
    pub discount_rate_bps: u16,
    pub paused: bool,
}

impl PairUpdated {
    pub const DISCRIMINATOR: [u8; 8] = [208, 67, 143, 117, 86, 212, 167, 194];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Copy)]
pub enum SwapDirection {
    QuoteToBase,
    BaseToQuote,
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SwapExecuted {
    /// the trader
    pub requestor: Pubkey,
    /// the amount in
    pub amount_in: u64,
    /// the protocol fee amount
    pub protocol_fee_amount: u64,
    /// the effective pair fee bps applied to this swap
    pub discount_bps: u16,
    /// the amount out
    pub amount_out: u64,
    /// the pair pubkey
    pub pair: Pubkey,
    pub swap_direction: SwapDirection,
    pub swap_type: SwapType,
    /// raw pair redemption fee bps
    pub redemption_fee_bps: u16,
    /// raw pair discount rate bps
    pub discount_rate_bps: u16,
}

impl SwapExecuted {
    pub const DISCRIMINATOR: [u8; 8] = [150, 166, 26, 225, 28, 89, 38, 79];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Copy)]
pub enum SwapType {
    ExactIn,
    ExactOut,
}

#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct TreasuryPositionClosed {
    pub liquidity_provider: Pubkey,
    pub lp_vault_authority: Pubkey,
    pub treasury_user_position: Pubkey,
    /// rent lamports swept from the vault authority back to the LP
    pub lamports_returned: u64,
}

impl TreasuryPositionClosed {
    pub const DISCRIMINATOR: [u8; 8] = [180, 80, 87, 94, 238, 17, 237, 43];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

/// Vaults are shared between multiple pairs
/// We use this state to track how many pairs include a specific vault
/// PDA seeds [b"user_vault_info", asset_mint_address, liquidity_provider]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct UserVaultInfo {
    /// LP wallet address
    pub user: Pubkey,
    /// Mint address of the vault's token
    pub mint_address: Pubkey,
    /// Counter for how many pairs include this vault (for the same LP)
    pub used: u16,
    /// bump
    pub bump: u8,
    /// add some padding
    pub padding: [u8; 128],
}

impl UserVaultInfo {
    pub const DISCRIMINATOR: [u8; 8] = [100, 30, 4, 32, 178, 226, 105, 0];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

impl UserVaultInfo {
    /// Fetches and decodes account data without imposing a particular program owner.
    pub async fn fetch_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Option<Self>> {
        rpc.get_account(address).await?
            .map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from))
            .transpose()
    }

    pub async fn fetch<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        address: &Pubkey,
    ) -> crate::error::Result<Self> {
        Self::fetch_maybe(rpc, address).await?
            .ok_or(crate::error::SdkError::AccountNotFound(*address))
    }

    pub async fn fetch_all_maybe<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Option<Self>>> {
        let accounts = rpc.get_multiple_accounts(addresses).await?;
        if accounts.len() != addresses.len() {
            return Err(crate::error::SdkError::Rpc("get_multiple_accounts returned an unexpected account count".into()));
        }
        accounts.into_iter().map(|account| {
            account.map(|account| Self::decode(&account.data).map_err(crate::error::SdkError::from)).transpose()
        }).collect()
    }

    pub async fn fetch_all<R: crate::rpc::Rpc + ?Sized>(
        rpc: &R,
        addresses: &[Pubkey],
    ) -> crate::error::Result<Vec<Self>> {
        Self::fetch_all_maybe(rpc, addresses).await?.into_iter().zip(addresses)
            .map(|(account, address)| account.ok_or(crate::error::SdkError::AccountNotFound(*address)))
            .collect()
    }
}

/// Deposits tokens from the LP into the vault, optionally routing through the treasury program.
///
/// Flow:
/// - Checks the program pause state, the asset pause state and, for stable assets, the LP's
///   stable pause state.
/// - Transfers `amount` tokens from the LP's token account into the vault ATA.
/// - If treasury is enabled, CPIs into the treasury `deposit` instruction so vault tokens are
///   put to work earning yield.
///
/// Parameters:
/// - `amount`: Number of tokens to deposit.
/// - `treasury_nav_account_count`: Number of NAV accounts in `remaining_accounts` for the treasury CPI.
/// - `treasury_apy_account_count`: Number of APY accounts in `remaining_accounts` for the treasury CPI.
/// - `amount_threshold`: Optional floor on the treasury tokens minted. The deposit is always
///   `ExactIn`, and this is ignored when there is no deposit to make.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct AddLiquidityArgs {
    pub amount: u64,
    pub treasury_nav_account_count: u8,
    pub treasury_apy_account_count: u8,
    pub amount_threshold: Option<u64>,
}

impl AddLiquidityArgs {
    pub const DISCRIMINATOR: [u8; 8] = [181, 157, 89, 67, 143, 182, 52, 72];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddLiquidityAccounts {
    /// the liquidity provider that provides the tokens
    pub liquidity_provider: Pubkey,
    /// the mint address of the token
    pub mint_address: Pubkey,
    /// the token account of the liquidity provider
    pub lp_token_account: Pubkey,
    /// the vault token account (for the program)
    pub vault_token_account: Pubkey,
    /// the LP-specific vault authority used in vault ATA constraints
    pub lp_vault_authority: Pubkey,
    /// the global config, used to check if the program is paused
    pub global_config: Pubkey,
    /// LP-specific treasury toggle and protocol fee overrides.
    pub lp_protocol_fee_config: Pubkey,
    /// the asset config of the deposited mint, used to check the per-asset pause flag
    pub asset_config: Pubkey,
    /// LP stable config for the deposited mint — Some only when the mint is Stable, None for RWA
    pub lp_stable_config: Option<Pubkey>,
    pub treasury_program: Option<Pubkey>,
    pub treasury_global_config: Option<Pubkey>,
    pub treasury_asset_config: Option<Pubkey>,
    pub treasury_user_position: Option<Pubkey>,
    pub treasury_vault_authority: Option<Pubkey>,
    pub treasury_mint: Option<Pubkey>,
    pub treasury_asset_vault: Option<Pubkey>,
    pub treasury_user_treasury_token_account: Option<Pubkey>,
    pub treasury_token_program: Option<Pubkey>,
    pub treasury_associated_token_program: Option<Pubkey>,
    pub treasury_system_program: Option<Pubkey>,
    /// the token program, could be either the token2022 or the legacy token program
    pub token_program: Pubkey,
}

impl AddLiquidityAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &AddLiquidityArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(21 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.liquidity_provider, true));
        accounts.push(AccountMeta::new_readonly(self.mint_address, false));
        accounts.push(AccountMeta::new(self.lp_token_account, false));
        accounts.push(AccountMeta::new(self.vault_token_account, false));
        accounts.push(AccountMeta::new(self.lp_vault_authority, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.lp_protocol_fee_config, false));
        accounts.push(AccountMeta::new_readonly(self.asset_config, false));
        accounts.push(match self.lp_stable_config {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_program {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_global_config {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_asset_config {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_user_position {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_vault_authority {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_mint {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_asset_vault {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_user_treasury_token_account {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_token_program {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_associated_token_program {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_system_program {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(AccountMeta::new_readonly(self.token_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedAddLiquidityInstruction {
    pub program_id: Pubkey,
    pub accounts: AddLiquidityAccounts,
    pub args: AddLiquidityArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_add_liquidity_instruction(instruction: &Instruction) -> std::io::Result<ParsedAddLiquidityInstruction> {
    let args = AddLiquidityArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 21 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "add_liquidity requires 21 accounts"));
    }
    Ok(ParsedAddLiquidityInstruction {
        program_id: instruction.program_id,
        accounts: AddLiquidityAccounts {
            liquidity_provider: instruction.accounts[0].pubkey,
            mint_address: instruction.accounts[1].pubkey,
            lp_token_account: instruction.accounts[2].pubkey,
            vault_token_account: instruction.accounts[3].pubkey,
            lp_vault_authority: instruction.accounts[4].pubkey,
            global_config: instruction.accounts[5].pubkey,
            lp_protocol_fee_config: instruction.accounts[6].pubkey,
            asset_config: instruction.accounts[7].pubkey,
            lp_stable_config: (instruction.accounts[8].pubkey != instruction.program_id).then_some(instruction.accounts[8].pubkey),
            treasury_program: (instruction.accounts[9].pubkey != instruction.program_id).then_some(instruction.accounts[9].pubkey),
            treasury_global_config: (instruction.accounts[10].pubkey != instruction.program_id).then_some(instruction.accounts[10].pubkey),
            treasury_asset_config: (instruction.accounts[11].pubkey != instruction.program_id).then_some(instruction.accounts[11].pubkey),
            treasury_user_position: (instruction.accounts[12].pubkey != instruction.program_id).then_some(instruction.accounts[12].pubkey),
            treasury_vault_authority: (instruction.accounts[13].pubkey != instruction.program_id).then_some(instruction.accounts[13].pubkey),
            treasury_mint: (instruction.accounts[14].pubkey != instruction.program_id).then_some(instruction.accounts[14].pubkey),
            treasury_asset_vault: (instruction.accounts[15].pubkey != instruction.program_id).then_some(instruction.accounts[15].pubkey),
            treasury_user_treasury_token_account: (instruction.accounts[16].pubkey != instruction.program_id).then_some(instruction.accounts[16].pubkey),
            treasury_token_program: (instruction.accounts[17].pubkey != instruction.program_id).then_some(instruction.accounts[17].pubkey),
            treasury_associated_token_program: (instruction.accounts[18].pubkey != instruction.program_id).then_some(instruction.accounts[18].pubkey),
            treasury_system_program: (instruction.accounts[19].pubkey != instruction.program_id).then_some(instruction.accounts[19].pubkey),
            token_program: instruction.accounts[20].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[21..].to_vec(),
    })
}

/// Sweeps the entire balance from the program-level fee vault to the designated fee wallet.
///
/// Flow:
/// - Verifies the caller-supplied `fee_wallet` matches `GlobalConfig.fee_wallet` via `has_one`.
/// - Transfers the full balance of `fee_token_account` (owned by `program_authority`) to
///   `fee_wallet_token_account`.
///
/// Parameters:
/// - `fee_wallet`: The fee wallet public key; used as an `#[instruction]` seed for the constraint.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct ClaimFeesArgs {
    pub fee_wallet: Pubkey,
}

impl ClaimFeesArgs {
    pub const DISCRIMINATOR: [u8; 8] = [82, 251, 233, 156, 12, 52, 184, 202];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaimFeesAccounts {
    /// the mint address of the quote token
    pub fee_mint: Pubkey,
    /// the token account of the fee wallet
    pub fee_wallet_token_account: Pubkey,
    /// the program authority, used to sign the CPI transfer
    pub program_authority: Pubkey,
    /// the fee vault token account, used to transfer the tokens to the fee wallet
    pub fee_token_account: Pubkey,
    /// the global config, used to check if the program is paused, and check fee wallet
    pub global_config: Pubkey,
    /// the token program, could be either the token2022 or the legacy token program
    pub token_program: Pubkey,
}

impl ClaimFeesAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &ClaimFeesArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(6 + remaining_accounts.len());
        accounts.push(AccountMeta::new_readonly(self.fee_mint, false));
        accounts.push(AccountMeta::new(self.fee_wallet_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.program_authority, false));
        accounts.push(AccountMeta::new(self.fee_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.token_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedClaimFeesInstruction {
    pub program_id: Pubkey,
    pub accounts: ClaimFeesAccounts,
    pub args: ClaimFeesArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_claim_fees_instruction(instruction: &Instruction) -> std::io::Result<ParsedClaimFeesInstruction> {
    let args = ClaimFeesArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 6 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "claim_fees requires 6 accounts"));
    }
    Ok(ParsedClaimFeesInstruction {
        program_id: instruction.program_id,
        accounts: ClaimFeesAccounts {
            fee_mint: instruction.accounts[0].pubkey,
            fee_wallet_token_account: instruction.accounts[1].pubkey,
            program_authority: instruction.accounts[2].pubkey,
            fee_token_account: instruction.accounts[3].pubkey,
            global_config: instruction.accounts[4].pubkey,
            token_program: instruction.accounts[5].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[6..].to_vec(),
    })
}

/// Closes the LP's protocol-fee token account and returns any remaining balance to the LP.
///
/// Flow:
/// - Checks that the program is not paused.
/// - If the fee account holds a non-zero balance, transfers it to `lp_destination_token_account`.
/// - Closes the fee token ATA and returns the rent lamports to `liquidity_provider`.
///
/// This instruction should be called after all pairs have been closed via `close_pair`.
/// Closing the fee account while active pairs exist will cause future swaps for those pairs
/// to fail, as the swap instruction debits protocol fees from this account.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct CloseLpFeeAccountArgs {
}

impl CloseLpFeeAccountArgs {
    pub const DISCRIMINATOR: [u8; 8] = [188, 218, 123, 57, 25, 51, 105, 181];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CloseLpFeeAccountAccounts {
    /// the liquidity provider; receives the remaining fee balance and reclaimed rent
    pub liquidity_provider: Pubkey,
    /// the separate LP fee vault authority that owns the fee token account
    pub lp_fee_vault_authority: Pubkey,
    /// the global config, used to verify the fee token mint and check pause state;
    /// placed before fee_token_mint_address so its seeds constraint is validated first
    pub global_config: Pubkey,
    /// the mint address of the fee token; must match global config
    pub fee_token_mint_address: Pubkey,
    /// the LP's protocol-fee token account to drain and close
    pub lp_fee_token_account: Pubkey,
    /// the LP token account that receives any remaining fee balance
    pub lp_destination_token_account: Pubkey,
    /// the token program for the fee token
    pub token_program_fee: Pubkey,
}

impl CloseLpFeeAccountAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &CloseLpFeeAccountArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(7 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.liquidity_provider, true));
        accounts.push(AccountMeta::new_readonly(self.lp_fee_vault_authority, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.fee_token_mint_address, false));
        accounts.push(AccountMeta::new(self.lp_fee_token_account, false));
        accounts.push(AccountMeta::new(self.lp_destination_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_fee, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedCloseLpFeeAccountInstruction {
    pub program_id: Pubkey,
    pub accounts: CloseLpFeeAccountAccounts,
    pub args: CloseLpFeeAccountArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_close_lp_fee_account_instruction(instruction: &Instruction) -> std::io::Result<ParsedCloseLpFeeAccountInstruction> {
    let args = CloseLpFeeAccountArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 7 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "close_lp_fee_account requires 7 accounts"));
    }
    Ok(ParsedCloseLpFeeAccountInstruction {
        program_id: instruction.program_id,
        accounts: CloseLpFeeAccountAccounts {
            liquidity_provider: instruction.accounts[0].pubkey,
            lp_fee_vault_authority: instruction.accounts[1].pubkey,
            global_config: instruction.accounts[2].pubkey,
            fee_token_mint_address: instruction.accounts[3].pubkey,
            lp_fee_token_account: instruction.accounts[4].pubkey,
            lp_destination_token_account: instruction.accounts[5].pubkey,
            token_program_fee: instruction.accounts[6].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[7..].to_vec(),
    })
}

/// Closes a trading pair and reclaims rent; returns vault tokens to the LP if all pairs for a mint are closed.
///
/// Flow:
/// - Checks that the program is not paused.
/// - If treasury is enabled for this LP, verifies that the treasury user position has zero balance.
/// - Decrements `used` on the `UserVaultInfo` PDAs and `used_in_pairs_count` on both asset configs.
/// - If a vault's `used` count reaches zero, transfers the remaining vault balance back to the LP
///   and closes the vault ATA and `UserVaultInfo` PDA.
///
/// The LP must call `remove_liquidity` to drain all vault and treasury balances before calling
/// this instruction. If treasury is enabled, pass the `treasury_user_position` account; it must
/// report a zero balance for the instruction to succeed. After closing all pairs, call
/// `close_lp_fee_account` to recover any remaining fee token balance.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct ClosePairArgs {
}

impl ClosePairArgs {
    pub const DISCRIMINATOR: [u8; 8] = [45, 8, 194, 47, 65, 139, 172, 120];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClosePairAccounts {
    /// the admin, checked by has_one constraint with global config
    pub admin: Pubkey,
    /// the liquidity provider, will receive tokens and reclaimed rent back if necessary
    pub liquidity_provider: Pubkey,
    /// the pair account, will be closed
    pub pair: Pubkey,
    /// the mint address of the pair's quote token
    pub quote_token_mint_address: Pubkey,
    /// the mint address of the pair's base token
    pub base_token_mint_address: Pubkey,
    /// the LP-specific vault authority, used to sign LP vault transfers
    pub lp_vault_authority: Pubkey,
    /// the vault token account for the quote token
    pub quote_token_vault_token_account: Pubkey,
    /// the vault token account for the base token
    pub base_token_vault_token_account: Pubkey,
    /// the token account of the liquidity provider for the quote token
    pub lp_quote_token_account: Pubkey,
    /// the token account of the liquidity provider for the base token
    pub lp_base_token_account: Pubkey,
    /// the LP vault info for the quote token
    pub lp_vault_quote_pda: Pubkey,
    /// the LP vault info for the base token
    pub lp_vault_base_pda: Pubkey,
    /// the asset config for the quote token
    pub quote_asset_config: Pubkey,
    /// the asset config for the base token
    pub base_asset_config: Pubkey,
    /// the global config, used to check if the program is paused, and check admin
    pub global_config: Pubkey,
    /// LP-specific treasury toggle and protocol fee overrides.
    pub lp_protocol_fee_config: Pubkey,
    /// Treasury user position for the LP vault authority.
    /// Always required; data_is_empty() means LP never deposited to treasury.
    pub treasury_user_position: Pubkey,
    /// the token program for the quote token, could be either the token2022 or the legacy token program
    pub token_program_quote: Pubkey,
    /// the token program for the base token, could be either the token2022 or the legacy token program
    pub token_program_base: Pubkey,
}

impl ClosePairAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &ClosePairArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(19 + remaining_accounts.len());
        accounts.push(AccountMeta::new_readonly(self.admin, false));
        accounts.push(AccountMeta::new(self.liquidity_provider, true));
        accounts.push(AccountMeta::new(self.pair, false));
        accounts.push(AccountMeta::new_readonly(self.quote_token_mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.base_token_mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.lp_vault_authority, false));
        accounts.push(AccountMeta::new(self.quote_token_vault_token_account, false));
        accounts.push(AccountMeta::new(self.base_token_vault_token_account, false));
        accounts.push(AccountMeta::new(self.lp_quote_token_account, false));
        accounts.push(AccountMeta::new(self.lp_base_token_account, false));
        accounts.push(AccountMeta::new(self.lp_vault_quote_pda, false));
        accounts.push(AccountMeta::new(self.lp_vault_base_pda, false));
        accounts.push(AccountMeta::new(self.quote_asset_config, false));
        accounts.push(AccountMeta::new(self.base_asset_config, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.lp_protocol_fee_config, false));
        accounts.push(AccountMeta::new_readonly(self.treasury_user_position, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_quote, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_base, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedClosePairInstruction {
    pub program_id: Pubkey,
    pub accounts: ClosePairAccounts,
    pub args: ClosePairArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_close_pair_instruction(instruction: &Instruction) -> std::io::Result<ParsedClosePairInstruction> {
    let args = ClosePairArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 19 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "close_pair requires 19 accounts"));
    }
    Ok(ParsedClosePairInstruction {
        program_id: instruction.program_id,
        accounts: ClosePairAccounts {
            admin: instruction.accounts[0].pubkey,
            liquidity_provider: instruction.accounts[1].pubkey,
            pair: instruction.accounts[2].pubkey,
            quote_token_mint_address: instruction.accounts[3].pubkey,
            base_token_mint_address: instruction.accounts[4].pubkey,
            lp_vault_authority: instruction.accounts[5].pubkey,
            quote_token_vault_token_account: instruction.accounts[6].pubkey,
            base_token_vault_token_account: instruction.accounts[7].pubkey,
            lp_quote_token_account: instruction.accounts[8].pubkey,
            lp_base_token_account: instruction.accounts[9].pubkey,
            lp_vault_quote_pda: instruction.accounts[10].pubkey,
            lp_vault_base_pda: instruction.accounts[11].pubkey,
            quote_asset_config: instruction.accounts[12].pubkey,
            base_asset_config: instruction.accounts[13].pubkey,
            global_config: instruction.accounts[14].pubkey,
            lp_protocol_fee_config: instruction.accounts[15].pubkey,
            treasury_user_position: instruction.accounts[16].pubkey,
            token_program_quote: instruction.accounts[17].pubkey,
            token_program_base: instruction.accounts[18].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[19..].to_vec(),
    })
}

/// Closes the LP's treasury user position and returns the reclaimed rent to the LP.
///
/// Flow:
/// - Checks that the program is not paused.
/// - Pins `treasury_mint` against the treasury program's global config.
/// - Verifies `treasury_user_position` by deriving the expected treasury PDA.
/// - CPIs into the treasury `close_user_position` instruction, signing as `lp_vault_authority`.
/// - Closes the LP's treasury receipt account when it is already empty.
/// - Sweeps the full `lp_vault_authority` lamport balance to the liquidity provider.
///
/// Treasury bills the position's rent to `lp_vault_authority` and refunds to that same PDA on
/// close, so the final sweep is the only way the LP gets the SOL back.
///
/// Call this after `remove_liquidity` has drained the position. Treasury requires principal,
/// yield, and pending deposits to all be zero, and pending deposits only clear once they are
/// merge-ready, so this cannot run in the same breath as the final redeem.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct CloseTreasuryPositionArgs {
}

impl CloseTreasuryPositionArgs {
    pub const DISCRIMINATOR: [u8; 8] = [62, 152, 253, 37, 167, 251, 8, 64];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CloseTreasuryPositionAccounts {
    /// the liquidity provider; receives the reclaimed rent
    pub liquidity_provider: Pubkey,
    pub global_config: Pubkey,
    /// the treasury program's global config; pins `treasury_mint` to the real receipt mint
    pub treasury_global_config: Pubkey,
    /// the LP-specific vault authority; owns the treasury position and holds its rent lamports
    pub lp_vault_authority: Pubkey,
    /// the treasury user position to close
    pub treasury_user_position: Pubkey,
    /// the treasury receipt mint; verified against treasury's global config in the handler.
    /// Without that check any mint would do, and the receipt-account constraint below would
    /// equally accept one of the LP's swap vault ATAs, which share the same authority.
    pub treasury_mint: Pubkey,
    /// the LP's treasury receipt account, closed when it is already empty
    pub treasury_user_treasury_token_account: Pubkey,
    pub treasury_program: Pubkey,
    pub token_program_treasury: Pubkey,
    pub system_program: Pubkey,
}

impl CloseTreasuryPositionAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &CloseTreasuryPositionArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(10 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.liquidity_provider, true));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.treasury_global_config, false));
        accounts.push(AccountMeta::new(self.lp_vault_authority, false));
        accounts.push(AccountMeta::new(self.treasury_user_position, false));
        accounts.push(AccountMeta::new_readonly(self.treasury_mint, false));
        accounts.push(AccountMeta::new(self.treasury_user_treasury_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.treasury_program, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_treasury, false));
        accounts.push(AccountMeta::new_readonly(self.system_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedCloseTreasuryPositionInstruction {
    pub program_id: Pubkey,
    pub accounts: CloseTreasuryPositionAccounts,
    pub args: CloseTreasuryPositionArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_close_treasury_position_instruction(instruction: &Instruction) -> std::io::Result<ParsedCloseTreasuryPositionInstruction> {
    let args = CloseTreasuryPositionArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 10 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "close_treasury_position requires 10 accounts"));
    }
    Ok(ParsedCloseTreasuryPositionInstruction {
        program_id: instruction.program_id,
        accounts: CloseTreasuryPositionAccounts {
            liquidity_provider: instruction.accounts[0].pubkey,
            global_config: instruction.accounts[1].pubkey,
            treasury_global_config: instruction.accounts[2].pubkey,
            lp_vault_authority: instruction.accounts[3].pubkey,
            treasury_user_position: instruction.accounts[4].pubkey,
            treasury_mint: instruction.accounts[5].pubkey,
            treasury_user_treasury_token_account: instruction.accounts[6].pubkey,
            treasury_program: instruction.accounts[7].pubkey,
            token_program_treasury: instruction.accounts[8].pubkey,
            system_program: instruction.accounts[9].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[10..].to_vec(),
    })
}

/// Completes an admin transfer when the pending admin signs and accepts the role.
///
/// Flow:
/// - Verifies the signer matches `GlobalConfig.pending_admin`.
/// - Promotes pending admin to `GlobalConfig.admin` and clears the pending field.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct ConfirmNewAdminArgs {
}

impl ConfirmNewAdminArgs {
    pub const DISCRIMINATOR: [u8; 8] = [3, 109, 83, 170, 106, 54, 173, 117];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmNewAdminAccounts {
    /// the global config account, will be updated
    pub global_config: Pubkey,
    pub new_admin: Pubkey,
}

impl ConfirmNewAdminAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &ConfirmNewAdminArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(2 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.new_admin, true));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedConfirmNewAdminInstruction {
    pub program_id: Pubkey,
    pub accounts: ConfirmNewAdminAccounts,
    pub args: ConfirmNewAdminArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_confirm_new_admin_instruction(instruction: &Instruction) -> std::io::Result<ParsedConfirmNewAdminInstruction> {
    let args = ConfirmNewAdminArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 2 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "confirm_new_admin requires 2 accounts"));
    }
    Ok(ParsedConfirmNewAdminInstruction {
        program_id: instruction.program_id,
        accounts: ConfirmNewAdminAccounts {
            global_config: instruction.accounts[0].pubkey,
            new_admin: instruction.accounts[1].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[2..].to_vec(),
    })
}

/// Registers a new asset (quote or base token) with its NAV price sources.
///
/// Flow:
/// - Validates NAV sources and the price-difference bound.
/// - Initialises the `AssetConfig` PDA storing the NAV configuration and asset type.
///
/// Parameters:
/// - `nav_data`: Up to 5 NAV source definitions (Hardcoded, U64FixedAddress, or PythPush).
/// - `price_difference_bps`: Maximum permitted divergence between NAV sources in basis points.
/// - `asset_type`: Classification of the asset (RWA or Stable).
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct InitAssetConfigAccountArgs {
    pub nav_data: Vec<NavData>,
    pub price_difference_bps: u16,
    pub asset_type: AssetType,
}

impl InitAssetConfigAccountArgs {
    pub const DISCRIMINATOR: [u8; 8] = [32, 66, 21, 159, 176, 230, 59, 11];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitAssetConfigAccountAccounts {
    /// the RWA config account, will be initialized if needed
    pub asset_config: Pubkey,
    /// the mint address of the RWA token
    pub mint_address: Pubkey,
    pub admin: Pubkey,
    /// the fee vault token account, used to store the fees
    pub fee_vault_token_account: Pubkey,
    /// the program authority
    pub program_authority: Pubkey,
    /// the global config, used to check admin
    pub global_config: Pubkey,
    /// the token program for the asset token, could be either the token2022 or the legacy token program
    pub token_program: Pubkey,
    /// the system program, used to initialize the account
    pub system_program: Pubkey,
    pub associated_token_program: Pubkey,
}

impl InitAssetConfigAccountAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &InitAssetConfigAccountArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(9 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.asset_config, false));
        accounts.push(AccountMeta::new_readonly(self.mint_address, false));
        accounts.push(AccountMeta::new(self.admin, true));
        accounts.push(AccountMeta::new(self.fee_vault_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.program_authority, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.token_program, false));
        accounts.push(AccountMeta::new_readonly(self.system_program, false));
        accounts.push(AccountMeta::new_readonly(self.associated_token_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedInitAssetConfigAccountInstruction {
    pub program_id: Pubkey,
    pub accounts: InitAssetConfigAccountAccounts,
    pub args: InitAssetConfigAccountArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_init_asset_config_account_instruction(instruction: &Instruction) -> std::io::Result<ParsedInitAssetConfigAccountInstruction> {
    let args = InitAssetConfigAccountArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 9 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "init_asset_config_account requires 9 accounts"));
    }
    Ok(ParsedInitAssetConfigAccountInstruction {
        program_id: instruction.program_id,
        accounts: InitAssetConfigAccountAccounts {
            asset_config: instruction.accounts[0].pubkey,
            mint_address: instruction.accounts[1].pubkey,
            admin: instruction.accounts[2].pubkey,
            fee_vault_token_account: instruction.accounts[3].pubkey,
            program_authority: instruction.accounts[4].pubkey,
            global_config: instruction.accounts[5].pubkey,
            token_program: instruction.accounts[6].pubkey,
            system_program: instruction.accounts[7].pubkey,
            associated_token_program: instruction.accounts[8].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[9..].to_vec(),
    })
}

/// Initialises the global configuration and the program-level fee vault ATA.
///
/// Flow:
/// - Validates that `protocol_fees_bps` and `spread_protocol_fees_bps` are within range.
/// - Stores admin, fee wallet, fee rates, and fee token mint in `GlobalConfig`.
/// - Creates the global fee vault ATA owned by `program_authority`.
/// - The program starts **paused**; call `update_global_config` to unpause.
///
/// Parameters:
/// - `fee_wallet`: Recipient of protocol fees swept by `claim_fees`.
/// - `protocol_fees_bps`: Default issuer protocol fee rate in basis points.
/// - `spread_protocol_fees_bps`: Default spread protocol fee rate in basis points.
/// - `fee_token_mint`: Mint of the token LPs use to pay protocol fees (e.g. USDC).
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct InitGlobalConfigArgs {
    pub fee_wallet: Pubkey,
    pub protocol_fees_bps: u16,
    pub spread_protocol_fees_bps: u16,
    pub fee_token_mint: Pubkey,
}

impl InitGlobalConfigArgs {
    pub const DISCRIMINATOR: [u8; 8] = [140, 136, 214, 48, 87, 0, 120, 255];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitGlobalConfigAccounts {
    /// the global config account, will be initialized
    pub global_config: Pubkey,
    /// the admin, will be the admin of the global config
    pub admin: Pubkey,
    pub program_data: Pubkey,
    /// the program authority PDA, will own the fee vault
    pub program_authority: Pubkey,
    /// the mint of the fee token
    pub fee_token_mint_address: Pubkey,
    /// the program-level fee vault, initialized with global config
    pub fee_token_account: Pubkey,
    /// the token program for the fee token
    pub token_program_fee: Pubkey,
    pub associated_token_program: Pubkey,
    /// the system program, used to initialize the account
    pub system_program: Pubkey,
}

impl InitGlobalConfigAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &InitGlobalConfigArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(9 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.global_config, false));
        accounts.push(AccountMeta::new(self.admin, true));
        accounts.push(AccountMeta::new_readonly(self.program_data, false));
        accounts.push(AccountMeta::new_readonly(self.program_authority, false));
        accounts.push(AccountMeta::new_readonly(self.fee_token_mint_address, false));
        accounts.push(AccountMeta::new(self.fee_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_fee, false));
        accounts.push(AccountMeta::new_readonly(self.associated_token_program, false));
        accounts.push(AccountMeta::new_readonly(self.system_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedInitGlobalConfigInstruction {
    pub program_id: Pubkey,
    pub accounts: InitGlobalConfigAccounts,
    pub args: InitGlobalConfigArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_init_global_config_instruction(instruction: &Instruction) -> std::io::Result<ParsedInitGlobalConfigInstruction> {
    let args = InitGlobalConfigArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 9 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "init_global_config requires 9 accounts"));
    }
    Ok(ParsedInitGlobalConfigInstruction {
        program_id: instruction.program_id,
        accounts: InitGlobalConfigAccounts {
            global_config: instruction.accounts[0].pubkey,
            admin: instruction.accounts[1].pubkey,
            program_data: instruction.accounts[2].pubkey,
            program_authority: instruction.accounts[3].pubkey,
            fee_token_mint_address: instruction.accounts[4].pubkey,
            fee_token_account: instruction.accounts[5].pubkey,
            token_program_fee: instruction.accounts[6].pubkey,
            associated_token_program: instruction.accounts[7].pubkey,
            system_program: instruction.accounts[8].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[9..].to_vec(),
    })
}

/// Initialises a new quote/base trading pair for a liquidity provider.
///
/// Flow:
/// - Validates fee rates and that the two mints are distinct.
/// - Creates or increments `UserVaultInfo` PDAs for both mints.
/// - Initialises vault ATAs (owned by `lp_vault_authority`) and the LP fee ATA (owned by `lp_fee_vault_authority`).
/// - Increments `used_in_pairs_count` on both asset configs.
/// - Creates `LpStableConfig` PDAs for any stable token mints in the pair.
///
/// Parameters:
/// - `redemption_fee_bps`: Fee applied when swapping quote → base, in basis points.
/// - `discount_rate_bps`: Fee applied when swapping base → quote, in basis points.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct InitPairArgs {
    pub redemption_fee_bps: u16,
    pub discount_rate_bps: u16,
}

impl InitPairArgs {
    pub const DISCRIMINATOR: [u8; 8] = [210, 79, 92, 60, 153, 69, 57, 157];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitPairAccounts {
    /// the liquidity provider, must sign to initialize its own pair
    pub liquidity_provider: Pubkey,
    /// the pair account, will be initialized
    pub pair: Pubkey,
    /// the mint address of the pair's quote token
    pub quote_token_mint_address: Pubkey,
    /// the mint address of the pair's base token
    pub base_token_mint_address: Pubkey,
    /// the LP-specific vault authority used to own LP's token accounts
    pub lp_vault_authority: Pubkey,
    /// the separate LP fee vault authority used to own the LP's protocol-fee token account
    pub lp_fee_vault_authority: Pubkey,
    /// the vault token account for the quote token
    pub quote_token_vault_token_account: Pubkey,
    /// the vault token account for the base token
    pub base_token_vault_token_account: Pubkey,
    /// the LP vault info for the quote token
    pub lp_vault_quote_pda: Pubkey,
    /// the LP vault info for the base token
    pub lp_vault_base_pda: Pubkey,
    /// the global config, used to check the pause state and the fee token mint
    pub global_config: Pubkey,
    /// the mint address used by LPs to pay protocol fees
    pub fee_token_mint_address: Pubkey,
    /// the LP's protocol-fee token account
    pub lp_fee_token_account: Pubkey,
    /// LP stable config for the quote token — Some only when quote token is Stable, None for RWA
    pub lp_stable_config_quote: Option<Pubkey>,
    /// LP stable config for the base token — Some only when base token is Stable, None for RWA
    pub lp_stable_config_base: Option<Pubkey>,
    /// the asset config for the quote token
    pub quote_asset_config: Pubkey,
    /// the asset config for the base token
    pub base_asset_config: Pubkey,
    /// the token program for the quote token, could be either the token2022 or the legacy token program
    pub token_program_quote: Pubkey,
    /// the token program for the base token, could be either the token2022 or the legacy token program
    pub token_program_base: Pubkey,
    /// the token program for the fee token, could be either the token2022 or the legacy token program
    pub token_program_fee: Pubkey,
    pub associated_token_program: Pubkey,
    /// the system program, used to initialize the account
    pub system_program: Pubkey,
}

impl InitPairAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &InitPairArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(22 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.liquidity_provider, true));
        accounts.push(AccountMeta::new(self.pair, false));
        accounts.push(AccountMeta::new_readonly(self.quote_token_mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.base_token_mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.lp_vault_authority, false));
        accounts.push(AccountMeta::new_readonly(self.lp_fee_vault_authority, false));
        accounts.push(AccountMeta::new(self.quote_token_vault_token_account, false));
        accounts.push(AccountMeta::new(self.base_token_vault_token_account, false));
        accounts.push(AccountMeta::new(self.lp_vault_quote_pda, false));
        accounts.push(AccountMeta::new(self.lp_vault_base_pda, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.fee_token_mint_address, false));
        accounts.push(AccountMeta::new(self.lp_fee_token_account, false));
        accounts.push(match self.lp_stable_config_quote {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.lp_stable_config_base {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(AccountMeta::new(self.quote_asset_config, false));
        accounts.push(AccountMeta::new(self.base_asset_config, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_quote, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_base, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_fee, false));
        accounts.push(AccountMeta::new_readonly(self.associated_token_program, false));
        accounts.push(AccountMeta::new_readonly(self.system_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedInitPairInstruction {
    pub program_id: Pubkey,
    pub accounts: InitPairAccounts,
    pub args: InitPairArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_init_pair_instruction(instruction: &Instruction) -> std::io::Result<ParsedInitPairInstruction> {
    let args = InitPairArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 22 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "init_pair requires 22 accounts"));
    }
    Ok(ParsedInitPairInstruction {
        program_id: instruction.program_id,
        accounts: InitPairAccounts {
            liquidity_provider: instruction.accounts[0].pubkey,
            pair: instruction.accounts[1].pubkey,
            quote_token_mint_address: instruction.accounts[2].pubkey,
            base_token_mint_address: instruction.accounts[3].pubkey,
            lp_vault_authority: instruction.accounts[4].pubkey,
            lp_fee_vault_authority: instruction.accounts[5].pubkey,
            quote_token_vault_token_account: instruction.accounts[6].pubkey,
            base_token_vault_token_account: instruction.accounts[7].pubkey,
            lp_vault_quote_pda: instruction.accounts[8].pubkey,
            lp_vault_base_pda: instruction.accounts[9].pubkey,
            global_config: instruction.accounts[10].pubkey,
            fee_token_mint_address: instruction.accounts[11].pubkey,
            lp_fee_token_account: instruction.accounts[12].pubkey,
            lp_stable_config_quote: (instruction.accounts[13].pubkey != instruction.program_id).then_some(instruction.accounts[13].pubkey),
            lp_stable_config_base: (instruction.accounts[14].pubkey != instruction.program_id).then_some(instruction.accounts[14].pubkey),
            quote_asset_config: instruction.accounts[15].pubkey,
            base_asset_config: instruction.accounts[16].pubkey,
            token_program_quote: instruction.accounts[17].pubkey,
            token_program_base: instruction.accounts[18].pubkey,
            token_program_fee: instruction.accounts[19].pubkey,
            associated_token_program: instruction.accounts[20].pubkey,
            system_program: instruction.accounts[21].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[22..].to_vec(),
    })
}

/// Withdraws tokens from the vault back to the LP, optionally redeeming from the treasury program.
///
/// Flow:
/// - Checks the program pause state. Asset and LP stable pause flags are deliberately not
///   checked here so an LP can always exit a paused asset.
/// - If treasury is enabled, CPIs into the treasury `redeem` instruction to move tokens back
///   into the vault; the actual asset amount transferred to the LP is the vault balance delta
///   after the CPI (relevant for `ExactIn` mode where the output depends on NAV).
/// - If treasury is disabled, verifies the vault holds sufficient balance and transfers directly.
/// - Transfers the resulting token amount from the vault to the LP's token account.
///
/// Parameters:
/// - `amount`: Amount to redeem, interpreted according to `exact_mode`.
/// - `treasury_nav_account_count`: Number of NAV accounts in `remaining_accounts` for the treasury CPI.
/// - `treasury_apy_account_count`: Number of APY accounts in `remaining_accounts` for the treasury CPI.
/// - `exact_mode`: `ExactOut` — `amount` is asset tokens to receive; `ExactIn` — `amount` is
///   treasury tokens to burn (output is NAV-determined). Use `ExactIn` to fully drain a position.
/// - `amount_threshold`: A floor on the assets paid out for `ExactIn`, a ceiling on the treasury tokens burned for `ExactOut`.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct RemoveLiquidityArgs {
    pub amount: u64,
    pub treasury_nav_account_count: u8,
    pub treasury_apy_account_count: u8,
    pub exact_mode: ExactMode,
    pub amount_threshold: Option<u64>,
}

impl RemoveLiquidityArgs {
    pub const DISCRIMINATOR: [u8; 8] = [80, 85, 209, 72, 24, 206, 177, 108];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoveLiquidityAccounts {
    /// the liquidity provider, will receive the tokens back
    pub liquidity_provider: Pubkey,
    /// the mint address of the token
    pub mint_address: Pubkey,
    /// the token account of the liquidity provider
    pub lp_token_account: Pubkey,
    /// the vault token account for the token
    pub vault_token_account: Pubkey,
    /// the LP-specific vault authority, used to sign the CPI transfers
    pub lp_vault_authority: Pubkey,
    /// the global config, used to check if the program is paused
    pub global_config: Pubkey,
    /// LP-specific treasury toggle and protocol fee overrides.
    pub lp_protocol_fee_config: Pubkey,
    pub treasury_program: Option<Pubkey>,
    pub treasury_global_config: Option<Pubkey>,
    pub treasury_asset_config: Option<Pubkey>,
    pub treasury_user_position: Option<Pubkey>,
    pub treasury_vault_authority: Option<Pubkey>,
    pub treasury_mint: Option<Pubkey>,
    pub treasury_user_treasury_token_account: Option<Pubkey>,
    pub treasury_asset_vault: Option<Pubkey>,
    pub treasury_latest_apy_entry: Option<Pubkey>,
    pub treasury_token_program: Option<Pubkey>,
    pub treasury_associated_token_program: Option<Pubkey>,
    /// the token program for the token, could be either the token2022 or the legacy token program
    pub token_program: Pubkey,
}

impl RemoveLiquidityAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &RemoveLiquidityArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(19 + remaining_accounts.len());
        accounts.push(AccountMeta::new_readonly(self.liquidity_provider, true));
        accounts.push(AccountMeta::new_readonly(self.mint_address, false));
        accounts.push(AccountMeta::new(self.lp_token_account, false));
        accounts.push(AccountMeta::new(self.vault_token_account, false));
        accounts.push(AccountMeta::new(self.lp_vault_authority, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.lp_protocol_fee_config, false));
        accounts.push(match self.treasury_program {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_global_config {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_asset_config {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_user_position {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_vault_authority {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_mint {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_user_treasury_token_account {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_asset_vault {
            Some(address) => AccountMeta::new(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_latest_apy_entry {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_token_program {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.treasury_associated_token_program {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(AccountMeta::new_readonly(self.token_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedRemoveLiquidityInstruction {
    pub program_id: Pubkey,
    pub accounts: RemoveLiquidityAccounts,
    pub args: RemoveLiquidityArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_remove_liquidity_instruction(instruction: &Instruction) -> std::io::Result<ParsedRemoveLiquidityInstruction> {
    let args = RemoveLiquidityArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 19 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "remove_liquidity requires 19 accounts"));
    }
    Ok(ParsedRemoveLiquidityInstruction {
        program_id: instruction.program_id,
        accounts: RemoveLiquidityAccounts {
            liquidity_provider: instruction.accounts[0].pubkey,
            mint_address: instruction.accounts[1].pubkey,
            lp_token_account: instruction.accounts[2].pubkey,
            vault_token_account: instruction.accounts[3].pubkey,
            lp_vault_authority: instruction.accounts[4].pubkey,
            global_config: instruction.accounts[5].pubkey,
            lp_protocol_fee_config: instruction.accounts[6].pubkey,
            treasury_program: (instruction.accounts[7].pubkey != instruction.program_id).then_some(instruction.accounts[7].pubkey),
            treasury_global_config: (instruction.accounts[8].pubkey != instruction.program_id).then_some(instruction.accounts[8].pubkey),
            treasury_asset_config: (instruction.accounts[9].pubkey != instruction.program_id).then_some(instruction.accounts[9].pubkey),
            treasury_user_position: (instruction.accounts[10].pubkey != instruction.program_id).then_some(instruction.accounts[10].pubkey),
            treasury_vault_authority: (instruction.accounts[11].pubkey != instruction.program_id).then_some(instruction.accounts[11].pubkey),
            treasury_mint: (instruction.accounts[12].pubkey != instruction.program_id).then_some(instruction.accounts[12].pubkey),
            treasury_user_treasury_token_account: (instruction.accounts[13].pubkey != instruction.program_id).then_some(instruction.accounts[13].pubkey),
            treasury_asset_vault: (instruction.accounts[14].pubkey != instruction.program_id).then_some(instruction.accounts[14].pubkey),
            treasury_latest_apy_entry: (instruction.accounts[15].pubkey != instruction.program_id).then_some(instruction.accounts[15].pubkey),
            treasury_token_program: (instruction.accounts[16].pubkey != instruction.program_id).then_some(instruction.accounts[16].pubkey),
            treasury_associated_token_program: (instruction.accounts[17].pubkey != instruction.program_id).then_some(instruction.accounts[17].pubkey),
            token_program: instruction.accounts[18].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[19..].to_vec(),
    })
}

/// Sets or updates LP-specific protocol fee overrides.
///
/// Flow:
/// - Only callable by the admin.
/// - Creates the `LpProtocolFeeConfig` PDA if it does not yet exist.
/// - Stores per-LP fee rates.
///
/// Parameters:
/// - `protocol_fees_bps`: LP-specific issuer protocol fee rate in basis points.
/// - `spread_protocol_fees_bps`: LP-specific spread protocol fee rate in basis points.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SetLpProtocolFeeConfigArgs {
    pub protocol_fees_bps: u16,
    pub spread_protocol_fees_bps: u16,
}

impl SetLpProtocolFeeConfigArgs {
    pub const DISCRIMINATOR: [u8; 8] = [116, 84, 221, 0, 37, 34, 202, 205];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetLpProtocolFeeConfigAccounts {
    pub admin: Pubkey,
    pub global_config: Pubkey,
    pub lp_protocol_fee_config: Pubkey,
    /// liquidity provider whose fee overrides are being set
    pub liquidity_provider: Pubkey,
    pub system_program: Pubkey,
}

impl SetLpProtocolFeeConfigAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &SetLpProtocolFeeConfigArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(5 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.admin, true));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new(self.lp_protocol_fee_config, false));
        accounts.push(AccountMeta::new_readonly(self.liquidity_provider, false));
        accounts.push(AccountMeta::new_readonly(self.system_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSetLpProtocolFeeConfigInstruction {
    pub program_id: Pubkey,
    pub accounts: SetLpProtocolFeeConfigAccounts,
    pub args: SetLpProtocolFeeConfigArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_set_lp_protocol_fee_config_instruction(instruction: &Instruction) -> std::io::Result<ParsedSetLpProtocolFeeConfigInstruction> {
    let args = SetLpProtocolFeeConfigArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 5 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "set_lp_protocol_fee_config requires 5 accounts"));
    }
    Ok(ParsedSetLpProtocolFeeConfigInstruction {
        program_id: instruction.program_id,
        accounts: SetLpProtocolFeeConfigAccounts {
            admin: instruction.accounts[0].pubkey,
            global_config: instruction.accounts[1].pubkey,
            lp_protocol_fee_config: instruction.accounts[2].pubkey,
            liquidity_provider: instruction.accounts[3].pubkey,
            system_program: instruction.accounts[4].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[5..].to_vec(),
    })
}

/// Enables or disables treasury-backed liquidity routing for the signing LP.
///
/// Flow:
/// - Only callable by the LP themselves.
/// - If the `LpProtocolFeeConfig` PDA does not yet exist it is created with the global
///   default fee rates; the LP pays for the account.
/// - Writes the new `treasury_enabled` flag to the LP's config.
/// - When opting in, tops `lp_vault_authority` up to the rent for a `UserPosition` grown to
///   treasury's `max_pending_deposit_slots` plus the receipt ATA, so no later swap fails on a
///   realloc the PDA cannot pay for. `close_treasury_position` refunds the unused remainder.
///
/// Parameters:
/// - `enabled`: Whether the LP opts in (`true`) or out (`false`) of treasury routing.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SetLpTreasuryEnabledArgs {
    pub enabled: bool,
}

impl SetLpTreasuryEnabledArgs {
    pub const DISCRIMINATOR: [u8; 8] = [211, 145, 194, 69, 58, 232, 85, 175];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetLpTreasuryEnabledAccounts {
    pub liquidity_provider: Pubkey,
    pub global_config: Pubkey,
    pub lp_protocol_fee_config: Pubkey,
    /// the LP-specific vault authority
    pub lp_vault_authority: Pubkey,
    /// the treasury program's global config
    pub treasury_global_config: Pubkey,
    /// the treasury receipt mint
    pub treasury_mint: Pubkey,
    /// the LP's treasury position
    pub treasury_user_position: Pubkey,
    pub system_program: Pubkey,
}

impl SetLpTreasuryEnabledAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &SetLpTreasuryEnabledArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(8 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.liquidity_provider, true));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new(self.lp_protocol_fee_config, false));
        accounts.push(AccountMeta::new(self.lp_vault_authority, false));
        accounts.push(AccountMeta::new_readonly(self.treasury_global_config, false));
        accounts.push(AccountMeta::new_readonly(self.treasury_mint, false));
        accounts.push(AccountMeta::new_readonly(self.treasury_user_position, false));
        accounts.push(AccountMeta::new_readonly(self.system_program, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSetLpTreasuryEnabledInstruction {
    pub program_id: Pubkey,
    pub accounts: SetLpTreasuryEnabledAccounts,
    pub args: SetLpTreasuryEnabledArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_set_lp_treasury_enabled_instruction(instruction: &Instruction) -> std::io::Result<ParsedSetLpTreasuryEnabledInstruction> {
    let args = SetLpTreasuryEnabledArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 8 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "set_lp_treasury_enabled requires 8 accounts"));
    }
    Ok(ParsedSetLpTreasuryEnabledInstruction {
        program_id: instruction.program_id,
        accounts: SetLpTreasuryEnabledAccounts {
            liquidity_provider: instruction.accounts[0].pubkey,
            global_config: instruction.accounts[1].pubkey,
            lp_protocol_fee_config: instruction.accounts[2].pubkey,
            lp_vault_authority: instruction.accounts[3].pubkey,
            treasury_global_config: instruction.accounts[4].pubkey,
            treasury_mint: instruction.accounts[5].pubkey,
            treasury_user_position: instruction.accounts[6].pubkey,
            system_program: instruction.accounts[7].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[8..].to_vec(),
    })
}

/// Begins an admin transfer by recording a pending admin chosen by the current admin.
///
/// Flow:
/// - Verified through the `has_one = admin` constraint on `GlobalConfig`.
/// - Stores `new_admin` as `GlobalConfig.pending_admin`.
/// - Transfer is completed by the pending admin calling `confirm_new_admin`.
///
/// Parameters:
/// - `new_admin`: Public key of the account that will become the new admin.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SetNewAdminArgs {
    pub new_admin: Pubkey,
}

impl SetNewAdminArgs {
    pub const DISCRIMINATOR: [u8; 8] = [62, 156, 4, 148, 79, 162, 148, 252];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetNewAdminAccounts {
    /// the global config account, will be updated
    pub global_config: Pubkey,
    /// the multi liquid admin
    pub admin: Pubkey,
}

impl SetNewAdminAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &SetNewAdminArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(2 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.admin, true));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSetNewAdminInstruction {
    pub program_id: Pubkey,
    pub accounts: SetNewAdminAccounts,
    pub args: SetNewAdminArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_set_new_admin_instruction(instruction: &Instruction) -> std::io::Result<ParsedSetNewAdminInstruction> {
    let args = SetNewAdminArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 2 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "set_new_admin requires 2 accounts"));
    }
    Ok(ParsedSetNewAdminInstruction {
        program_id: instruction.program_id,
        accounts: SetNewAdminAccounts {
            global_config: instruction.accounts[0].pubkey,
            admin: instruction.accounts[1].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[2..].to_vec(),
    })
}

/// Pauses or unpauses all swaps involving a specific asset globally.
///
/// Flow:
/// - Only callable by the admin.
/// - Writes the new pause flag to `AssetConfig.paused`.
///
/// Parameters:
/// - `paused`: New pause state for this asset across all pairs.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SetPausedForAssetArgs {
    pub paused: bool,
}

impl SetPausedForAssetArgs {
    pub const DISCRIMINATOR: [u8; 8] = [116, 141, 145, 189, 67, 108, 178, 238];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetPausedForAssetAccounts {
    /// global config account, used to check the admin
    pub global_config: Pubkey,
    /// RWA config account, used to update the paused state
    pub asset_config: Pubkey,
    /// the mint address of the RWA token
    pub mint_address: Pubkey,
    /// the multi liquid admin
    pub admin: Pubkey,
}

impl SetPausedForAssetAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &SetPausedForAssetArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(4 + remaining_accounts.len());
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new(self.asset_config, false));
        accounts.push(AccountMeta::new_readonly(self.mint_address, false));
        accounts.push(AccountMeta::new(self.admin, true));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSetPausedForAssetInstruction {
    pub program_id: Pubkey,
    pub accounts: SetPausedForAssetAccounts,
    pub args: SetPausedForAssetArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_set_paused_for_asset_instruction(instruction: &Instruction) -> std::io::Result<ParsedSetPausedForAssetInstruction> {
    let args = SetPausedForAssetArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 4 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "set_paused_for_asset requires 4 accounts"));
    }
    Ok(ParsedSetPausedForAssetInstruction {
        program_id: instruction.program_id,
        accounts: SetPausedForAssetAccounts {
            global_config: instruction.accounts[0].pubkey,
            asset_config: instruction.accounts[1].pubkey,
            mint_address: instruction.accounts[2].pubkey,
            admin: instruction.accounts[3].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[4..].to_vec(),
    })
}

/// Pauses or unpauses all swaps through this LP's quote token for a given stable mint.
///
/// Flow:
/// - The liquidity provider signs; the `LpStableConfig` PDA is verified by seeds.
/// - Writes the new pause flag to `LpStableConfig.paused`.
///
/// Parameters:
/// - `paused`: New pause state for this LP's stable mint configuration.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SetPausedForLpStableConfigArgs {
    pub paused: bool,
}

impl SetPausedForLpStableConfigArgs {
    pub const DISCRIMINATOR: [u8; 8] = [214, 35, 14, 32, 51, 46, 101, 150];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetPausedForLpStableConfigAccounts {
    /// global config account, used to authorize the admin signer
    pub global_config: Pubkey,
    /// LP stable config account, used to update the paused state
    pub lp_stable_config: Pubkey,
    /// the mint address of the stable coin
    pub mint_address: Pubkey,
    /// the liquidity provider
    pub liquidity_provider: Pubkey,
    /// the signer, could be either multiliquid admin, or the liquidity provider
    pub signer: Pubkey,
}

impl SetPausedForLpStableConfigAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &SetPausedForLpStableConfigArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(5 + remaining_accounts.len());
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new(self.lp_stable_config, false));
        accounts.push(AccountMeta::new_readonly(self.mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.liquidity_provider, false));
        accounts.push(AccountMeta::new_readonly(self.signer, true));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSetPausedForLpStableConfigInstruction {
    pub program_id: Pubkey,
    pub accounts: SetPausedForLpStableConfigAccounts,
    pub args: SetPausedForLpStableConfigArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_set_paused_for_lp_stable_config_instruction(instruction: &Instruction) -> std::io::Result<ParsedSetPausedForLpStableConfigInstruction> {
    let args = SetPausedForLpStableConfigArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 5 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "set_paused_for_lp_stable_config requires 5 accounts"));
    }
    Ok(ParsedSetPausedForLpStableConfigInstruction {
        program_id: instruction.program_id,
        accounts: SetPausedForLpStableConfigAccounts {
            global_config: instruction.accounts[0].pubkey,
            lp_stable_config: instruction.accounts[1].pubkey,
            mint_address: instruction.accounts[2].pubkey,
            liquidity_provider: instruction.accounts[3].pubkey,
            signer: instruction.accounts[4].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[5..].to_vec(),
    })
}

/// Executes a swap between the quote token and the base token for a given pair.
///
/// Flow:
/// - Checks program, pair, RWA, and stable pause states.
/// - Reads NAV for the base (RWA) token and calculates swap amounts with fees.
/// - Computes the protocol fee from the LP's fee account and transfers it to the global fee vault.
/// - Transfers tokens between the trader and the LP's vault (via SPL transfer-checked).
/// - If treasury is enabled for the LP, routes vault movements through the treasury CPI.
///
/// Parameters:
/// - `amount`: Exact input or output amount depending on `swap_type`.
/// - `min_amount_out`: Slippage guard for ExactIn swaps; the instruction errors if output is below this.
/// - `max_amount_in`: Slippage guard for ExactOut swaps; the instruction errors if input exceeds this.
/// - `swap_direction`: `QuoteToBase` (buy RWA) or `BaseToQuote` (sell RWA).
/// - `swap_type`: `ExactIn` (fixed input) or `ExactOut` (fixed output).
/// - `treasury_nav_account_count`: Number of NAV accounts in `remaining_accounts` for the treasury CPI.
/// - `treasury_apy_account_count`: Number of APY accounts in `remaining_accounts` for the treasury CPI.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct SwapArgs {
    pub amount: u64,
    pub min_amount_out: Option<u64>,
    pub max_amount_in: Option<u64>,
    pub swap_direction: SwapDirection,
    pub swap_type: SwapType,
    pub treasury_nav_account_count: u8,
    pub treasury_apy_account_count: u8,
}

impl SwapArgs {
    pub const DISCRIMINATOR: [u8; 8] = [248, 198, 158, 145, 225, 117, 135, 200];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapAccounts {
    /// the trader
    pub user: Pubkey,
    /// the pair account
    pub pair: Pubkey,
    /// the program authority, used to sign the CPI transfers
    pub program_authority: Pubkey,
    /// liquidity provider, must be the liquidity provider of the pair
    pub liquidity_provider: Pubkey,
    /// the LP-specific vault authority, used to sign LP vault transfers
    pub lp_vault_authority: Pubkey,
    /// the separate LP fee vault authority used to own the LP's protocol-fee token account
    pub lp_fee_vault_authority: Pubkey,
    /// the mint address of the quote token
    pub quote_token_mint_address: Pubkey,
    /// the mint address of the base token
    pub base_token_mint_address: Pubkey,
    /// the token account of the base token, owned by the trader
    pub base_token_user_token_account: Pubkey,
    /// the token account of the quote token, owned by the trader
    pub quote_token_user_token_account: Pubkey,
    /// the vault token account for the quote token
    pub quote_token_vault_token_account: Pubkey,
    /// the vault token account for the base token
    pub base_token_vault_token_account: Pubkey,
    /// the global config, used to check if the program is paused
    pub global_config: Pubkey,
    /// the mint address used by LPs to pay protocol fees
    pub fee_token_mint_address: Pubkey,
    /// the LP's protocol-fee token account
    pub lp_fee_token_account: Pubkey,
    /// the fee vault token account for the global fee token, initialized in init_global_config
    pub fee_token_account: Pubkey,
    /// the asset config account for the base token
    pub base_config: Pubkey,
    /// the asset config account for the quote token
    pub quote_config: Pubkey,
    /// the asset config account for the global fee token
    pub fee_config: Pubkey,
    /// LP stable config for the quote token — Some only when quote token is Stable, None for RWA
    pub lp_stable_config_quote: Option<Pubkey>,
    /// LP stable config for the base token — Some only when base token is Stable, None for RWA
    pub lp_stable_config_base: Option<Pubkey>,
    /// LP-specific protocol fee overrides, if initialized
    pub lp_protocol_fee_config: Pubkey,
    /// the token program for the quote token, could be either the token2022 or the legacy token program
    pub token_program_quote: Pubkey,
    /// the token program for the base token, could be either the token2022 or the legacy token program
    pub token_program_base: Pubkey,
    /// the token program for the fee token, could be either the token2022 or the legacy token program
    pub token_program_fee: Pubkey,
}

impl SwapAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &SwapArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(25 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.user, true));
        accounts.push(AccountMeta::new_readonly(self.pair, false));
        accounts.push(AccountMeta::new_readonly(self.program_authority, false));
        accounts.push(AccountMeta::new_readonly(self.liquidity_provider, false));
        accounts.push(AccountMeta::new(self.lp_vault_authority, false));
        accounts.push(AccountMeta::new_readonly(self.lp_fee_vault_authority, false));
        accounts.push(AccountMeta::new_readonly(self.quote_token_mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.base_token_mint_address, false));
        accounts.push(AccountMeta::new(self.base_token_user_token_account, false));
        accounts.push(AccountMeta::new(self.quote_token_user_token_account, false));
        accounts.push(AccountMeta::new(self.quote_token_vault_token_account, false));
        accounts.push(AccountMeta::new(self.base_token_vault_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.fee_token_mint_address, false));
        accounts.push(AccountMeta::new(self.lp_fee_token_account, false));
        accounts.push(AccountMeta::new(self.fee_token_account, false));
        accounts.push(AccountMeta::new_readonly(self.base_config, false));
        accounts.push(AccountMeta::new_readonly(self.quote_config, false));
        accounts.push(AccountMeta::new_readonly(self.fee_config, false));
        accounts.push(match self.lp_stable_config_quote {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(match self.lp_stable_config_base {
            Some(address) => AccountMeta::new_readonly(address, false),
            None => AccountMeta::new_readonly(program_id, false),
        });
        accounts.push(AccountMeta::new_readonly(self.lp_protocol_fee_config, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_quote, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_base, false));
        accounts.push(AccountMeta::new_readonly(self.token_program_fee, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSwapInstruction {
    pub program_id: Pubkey,
    pub accounts: SwapAccounts,
    pub args: SwapArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_swap_instruction(instruction: &Instruction) -> std::io::Result<ParsedSwapInstruction> {
    let args = SwapArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 25 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "swap requires 25 accounts"));
    }
    Ok(ParsedSwapInstruction {
        program_id: instruction.program_id,
        accounts: SwapAccounts {
            user: instruction.accounts[0].pubkey,
            pair: instruction.accounts[1].pubkey,
            program_authority: instruction.accounts[2].pubkey,
            liquidity_provider: instruction.accounts[3].pubkey,
            lp_vault_authority: instruction.accounts[4].pubkey,
            lp_fee_vault_authority: instruction.accounts[5].pubkey,
            quote_token_mint_address: instruction.accounts[6].pubkey,
            base_token_mint_address: instruction.accounts[7].pubkey,
            base_token_user_token_account: instruction.accounts[8].pubkey,
            quote_token_user_token_account: instruction.accounts[9].pubkey,
            quote_token_vault_token_account: instruction.accounts[10].pubkey,
            base_token_vault_token_account: instruction.accounts[11].pubkey,
            global_config: instruction.accounts[12].pubkey,
            fee_token_mint_address: instruction.accounts[13].pubkey,
            lp_fee_token_account: instruction.accounts[14].pubkey,
            fee_token_account: instruction.accounts[15].pubkey,
            base_config: instruction.accounts[16].pubkey,
            quote_config: instruction.accounts[17].pubkey,
            fee_config: instruction.accounts[18].pubkey,
            lp_stable_config_quote: (instruction.accounts[19].pubkey != instruction.program_id).then_some(instruction.accounts[19].pubkey),
            lp_stable_config_base: (instruction.accounts[20].pubkey != instruction.program_id).then_some(instruction.accounts[20].pubkey),
            lp_protocol_fee_config: instruction.accounts[21].pubkey,
            token_program_quote: instruction.accounts[22].pubkey,
            token_program_base: instruction.accounts[23].pubkey,
            token_program_fee: instruction.accounts[24].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[25..].to_vec(),
    })
}

/// Updates the NAV sources or price-difference bound for an existing asset config.
///
/// Flow:
/// - Validates updated NAV sources and price-difference bound.
/// - Overwrites the `AssetConfig` fields; the asset type cannot be changed.
///
/// Parameters:
/// - `nav_data`: Replacement NAV source definitions (up to 5).
/// - `price_difference_bps`: Updated maximum permitted NAV divergence in basis points.
/// - `asset_type`: Must match the existing asset type (validated by the instruction).
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct UpdateAssetConfigAccountArgs {
    pub nav_data: Vec<NavData>,
    pub price_difference_bps: u16,
    pub asset_type: AssetType,
}

impl UpdateAssetConfigAccountArgs {
    pub const DISCRIMINATOR: [u8; 8] = [217, 201, 225, 177, 234, 99, 234, 162];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateAssetConfigAccountAccounts {
    /// the RWA config account, will be updated
    pub asset_config: Pubkey,
    /// the mint address of the RWA token (used in seeds)
    pub mint_address: Pubkey,
    /// the multi liquid admin
    pub admin: Pubkey,
    /// the global config account, used to check the admin
    pub global_config: Pubkey,
}

impl UpdateAssetConfigAccountAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &UpdateAssetConfigAccountArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(4 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.asset_config, false));
        accounts.push(AccountMeta::new_readonly(self.mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.admin, true));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedUpdateAssetConfigAccountInstruction {
    pub program_id: Pubkey,
    pub accounts: UpdateAssetConfigAccountAccounts,
    pub args: UpdateAssetConfigAccountArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_update_asset_config_account_instruction(instruction: &Instruction) -> std::io::Result<ParsedUpdateAssetConfigAccountInstruction> {
    let args = UpdateAssetConfigAccountArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 4 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "update_asset_config_account requires 4 accounts"));
    }
    Ok(ParsedUpdateAssetConfigAccountInstruction {
        program_id: instruction.program_id,
        accounts: UpdateAssetConfigAccountAccounts {
            asset_config: instruction.accounts[0].pubkey,
            mint_address: instruction.accounts[1].pubkey,
            admin: instruction.accounts[2].pubkey,
            global_config: instruction.accounts[3].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[4..].to_vec(),
    })
}

/// Updates one or more fields of the global configuration.
///
/// Flow:
/// - Validates updated fee rates if provided.
/// - Applies each `Some(value)` field; `None` fields are left unchanged.
///
/// Parameters:
/// - `fee_wallet`: New fee wallet recipient, or `None` to leave unchanged.
/// - `paused`: New pause state, or `None` to leave unchanged.
/// - `protocol_fees_bps`: New default issuer fee rate, or `None` to leave unchanged.
/// - `spread_protocol_fees_bps`: New default spread fee rate, or `None` to leave unchanged.
/// - `fee_token_mint`: New fee token mint, or `None` to leave unchanged.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct UpdateGlobalConfigArgs {
    pub fee_wallet: Option<Pubkey>,
    pub paused: Option<bool>,
    pub protocol_fees_bps: Option<u16>,
    pub spread_protocol_fees_bps: Option<u16>,
    pub fee_token_mint: Option<Pubkey>,
}

impl UpdateGlobalConfigArgs {
    pub const DISCRIMINATOR: [u8; 8] = [164, 84, 130, 189, 111, 58, 250, 200];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateGlobalConfigAccounts {
    /// the global config account, will be updated
    pub global_config: Pubkey,
    /// the multi liquid admin
    pub admin: Pubkey,
}

impl UpdateGlobalConfigAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &UpdateGlobalConfigArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(2 + remaining_accounts.len());
        accounts.push(AccountMeta::new(self.global_config, false));
        accounts.push(AccountMeta::new_readonly(self.admin, true));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedUpdateGlobalConfigInstruction {
    pub program_id: Pubkey,
    pub accounts: UpdateGlobalConfigAccounts,
    pub args: UpdateGlobalConfigArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_update_global_config_instruction(instruction: &Instruction) -> std::io::Result<ParsedUpdateGlobalConfigInstruction> {
    let args = UpdateGlobalConfigArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 2 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "update_global_config requires 2 accounts"));
    }
    Ok(ParsedUpdateGlobalConfigInstruction {
        program_id: instruction.program_id,
        accounts: UpdateGlobalConfigAccounts {
            global_config: instruction.accounts[0].pubkey,
            admin: instruction.accounts[1].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[2..].to_vec(),
    })
}

/// Updates the fee rates and pause state for an existing trading pair.
///
/// Flow:
/// - Validates that the updated fee rates are within range.
/// - Writes the new fee rates and pause flag to the `Pair` account.
///
/// Parameters:
/// - `redemption_fee_bps`: Updated quote → base fee rate in basis points.
/// - `discount_rate_bps`: Updated base → quote fee rate in basis points.
/// - `paused`: New pause state for this specific pair.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct UpdatePairArgs {
    pub redemption_fee_bps: u16,
    pub discount_rate_bps: u16,
    pub paused: bool,
}

impl UpdatePairArgs {
    pub const DISCRIMINATOR: [u8; 8] = [176, 62, 36, 215, 255, 206, 35, 12];

    /// Checks the discriminator and decodes the Borsh payload. Allocation trailing bytes are allowed.
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        super::decode(data, Self::DISCRIMINATOR)
    }

    /// Encodes the discriminator followed by the Borsh payload.
    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        super::encode(self, Self::DISCRIMINATOR)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdatePairAccounts {
    /// the liquidity provider, must be the liquidity provider of the pair
    pub liquidity_provider: Pubkey,
    /// the pair account, will be updated
    pub pair: Pubkey,
    /// the mint address of the quote token (used in seeds)
    pub quote_token_mint_address: Pubkey,
    /// the mint address of the base token (used in seeds)
    pub base_token_mint_address: Pubkey,
    /// the global config account, used to check if the program is paused
    pub global_config: Pubkey,
}

impl UpdatePairAccounts {
    /// All accounts are explicit; absent optional accounts use the supplied program ID sentinel.
    pub fn instruction(
        &self,
        program_id: Pubkey,
        args: &UpdatePairArgs,
        remaining_accounts: &[AccountMeta],
    ) -> std::io::Result<Instruction> {
        let mut accounts = Vec::with_capacity(5 + remaining_accounts.len());
        accounts.push(AccountMeta::new_readonly(self.liquidity_provider, true));
        accounts.push(AccountMeta::new(self.pair, false));
        accounts.push(AccountMeta::new_readonly(self.quote_token_mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.base_token_mint_address, false));
        accounts.push(AccountMeta::new_readonly(self.global_config, false));
        accounts.extend_from_slice(remaining_accounts);
        Ok(Instruction { program_id, accounts, data: args.encode()? })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedUpdatePairInstruction {
    pub program_id: Pubkey,
    pub accounts: UpdatePairAccounts,
    pub args: UpdatePairArgs,
    pub remaining_accounts: Vec<AccountMeta>,
}

/// Parses using the instruction's actual program ID, including optional-account sentinels.
pub fn parse_update_pair_instruction(instruction: &Instruction) -> std::io::Result<ParsedUpdatePairInstruction> {
    let args = UpdatePairArgs::decode(&instruction.data)?;
    if instruction.accounts.len() < 5 {
        return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "update_pair requires 5 accounts"));
    }
    Ok(ParsedUpdatePairInstruction {
        program_id: instruction.program_id,
        accounts: UpdatePairAccounts {
            liquidity_provider: instruction.accounts[0].pubkey,
            pair: instruction.accounts[1].pubkey,
            quote_token_mint_address: instruction.accounts[2].pubkey,
            base_token_mint_address: instruction.accounts[3].pubkey,
            global_config: instruction.accounts[4].pubkey,
        },
        args,
        remaining_accounts: instruction.accounts[5..].to_vec(),
    })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstructionKind {
    AddLiquidity,
    ClaimFees,
    CloseLpFeeAccount,
    ClosePair,
    CloseTreasuryPosition,
    ConfirmNewAdmin,
    InitAssetConfigAccount,
    InitGlobalConfig,
    InitPair,
    RemoveLiquidity,
    SetLpProtocolFeeConfig,
    SetLpTreasuryEnabled,
    SetNewAdmin,
    SetPausedForAsset,
    SetPausedForLpStableConfig,
    Swap,
    UpdateAssetConfigAccount,
    UpdateGlobalConfig,
    UpdatePair,
}

pub const INSTRUCTION_DISCRIMINATORS: &[(&str, [u8; 8])] = &[
    ("add_liquidity", AddLiquidityArgs::DISCRIMINATOR),
    ("claim_fees", ClaimFeesArgs::DISCRIMINATOR),
    ("close_lp_fee_account", CloseLpFeeAccountArgs::DISCRIMINATOR),
    ("close_pair", ClosePairArgs::DISCRIMINATOR),
    ("close_treasury_position", CloseTreasuryPositionArgs::DISCRIMINATOR),
    ("confirm_new_admin", ConfirmNewAdminArgs::DISCRIMINATOR),
    ("init_asset_config_account", InitAssetConfigAccountArgs::DISCRIMINATOR),
    ("init_global_config", InitGlobalConfigArgs::DISCRIMINATOR),
    ("init_pair", InitPairArgs::DISCRIMINATOR),
    ("remove_liquidity", RemoveLiquidityArgs::DISCRIMINATOR),
    ("set_lp_protocol_fee_config", SetLpProtocolFeeConfigArgs::DISCRIMINATOR),
    ("set_lp_treasury_enabled", SetLpTreasuryEnabledArgs::DISCRIMINATOR),
    ("set_new_admin", SetNewAdminArgs::DISCRIMINATOR),
    ("set_paused_for_asset", SetPausedForAssetArgs::DISCRIMINATOR),
    ("set_paused_for_lp_stable_config", SetPausedForLpStableConfigArgs::DISCRIMINATOR),
    ("swap", SwapArgs::DISCRIMINATOR),
    ("update_asset_config_account", UpdateAssetConfigAccountArgs::DISCRIMINATOR),
    ("update_global_config", UpdateGlobalConfigArgs::DISCRIMINATOR),
    ("update_pair", UpdatePairArgs::DISCRIMINATOR),
];

pub fn identify_instruction(data: &[u8]) -> std::io::Result<InstructionKind> {
    match super::discriminator(data)? {
        AddLiquidityArgs::DISCRIMINATOR => Ok(InstructionKind::AddLiquidity),
        ClaimFeesArgs::DISCRIMINATOR => Ok(InstructionKind::ClaimFees),
        CloseLpFeeAccountArgs::DISCRIMINATOR => Ok(InstructionKind::CloseLpFeeAccount),
        ClosePairArgs::DISCRIMINATOR => Ok(InstructionKind::ClosePair),
        CloseTreasuryPositionArgs::DISCRIMINATOR => Ok(InstructionKind::CloseTreasuryPosition),
        ConfirmNewAdminArgs::DISCRIMINATOR => Ok(InstructionKind::ConfirmNewAdmin),
        InitAssetConfigAccountArgs::DISCRIMINATOR => Ok(InstructionKind::InitAssetConfigAccount),
        InitGlobalConfigArgs::DISCRIMINATOR => Ok(InstructionKind::InitGlobalConfig),
        InitPairArgs::DISCRIMINATOR => Ok(InstructionKind::InitPair),
        RemoveLiquidityArgs::DISCRIMINATOR => Ok(InstructionKind::RemoveLiquidity),
        SetLpProtocolFeeConfigArgs::DISCRIMINATOR => Ok(InstructionKind::SetLpProtocolFeeConfig),
        SetLpTreasuryEnabledArgs::DISCRIMINATOR => Ok(InstructionKind::SetLpTreasuryEnabled),
        SetNewAdminArgs::DISCRIMINATOR => Ok(InstructionKind::SetNewAdmin),
        SetPausedForAssetArgs::DISCRIMINATOR => Ok(InstructionKind::SetPausedForAsset),
        SetPausedForLpStableConfigArgs::DISCRIMINATOR => Ok(InstructionKind::SetPausedForLpStableConfig),
        SwapArgs::DISCRIMINATOR => Ok(InstructionKind::Swap),
        UpdateAssetConfigAccountArgs::DISCRIMINATOR => Ok(InstructionKind::UpdateAssetConfigAccount),
        UpdateGlobalConfigArgs::DISCRIMINATOR => Ok(InstructionKind::UpdateGlobalConfig),
        UpdatePairArgs::DISCRIMINATOR => Ok(InstructionKind::UpdatePair),
        _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Unknown instruction discriminator")),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsedInstruction {
    AddLiquidity(ParsedAddLiquidityInstruction),
    ClaimFees(ParsedClaimFeesInstruction),
    CloseLpFeeAccount(ParsedCloseLpFeeAccountInstruction),
    ClosePair(ParsedClosePairInstruction),
    CloseTreasuryPosition(ParsedCloseTreasuryPositionInstruction),
    ConfirmNewAdmin(ParsedConfirmNewAdminInstruction),
    InitAssetConfigAccount(ParsedInitAssetConfigAccountInstruction),
    InitGlobalConfig(ParsedInitGlobalConfigInstruction),
    InitPair(ParsedInitPairInstruction),
    RemoveLiquidity(ParsedRemoveLiquidityInstruction),
    SetLpProtocolFeeConfig(ParsedSetLpProtocolFeeConfigInstruction),
    SetLpTreasuryEnabled(ParsedSetLpTreasuryEnabledInstruction),
    SetNewAdmin(ParsedSetNewAdminInstruction),
    SetPausedForAsset(ParsedSetPausedForAssetInstruction),
    SetPausedForLpStableConfig(ParsedSetPausedForLpStableConfigInstruction),
    Swap(ParsedSwapInstruction),
    UpdateAssetConfigAccount(ParsedUpdateAssetConfigAccountInstruction),
    UpdateGlobalConfig(ParsedUpdateGlobalConfigInstruction),
    UpdatePair(ParsedUpdatePairInstruction),
}

pub fn parse_instruction(instruction: &Instruction) -> std::io::Result<ParsedInstruction> {
    match identify_instruction(&instruction.data)? {
        InstructionKind::AddLiquidity => Ok(ParsedInstruction::AddLiquidity(parse_add_liquidity_instruction(instruction)?)),
        InstructionKind::ClaimFees => Ok(ParsedInstruction::ClaimFees(parse_claim_fees_instruction(instruction)?)),
        InstructionKind::CloseLpFeeAccount => Ok(ParsedInstruction::CloseLpFeeAccount(parse_close_lp_fee_account_instruction(instruction)?)),
        InstructionKind::ClosePair => Ok(ParsedInstruction::ClosePair(parse_close_pair_instruction(instruction)?)),
        InstructionKind::CloseTreasuryPosition => Ok(ParsedInstruction::CloseTreasuryPosition(parse_close_treasury_position_instruction(instruction)?)),
        InstructionKind::ConfirmNewAdmin => Ok(ParsedInstruction::ConfirmNewAdmin(parse_confirm_new_admin_instruction(instruction)?)),
        InstructionKind::InitAssetConfigAccount => Ok(ParsedInstruction::InitAssetConfigAccount(parse_init_asset_config_account_instruction(instruction)?)),
        InstructionKind::InitGlobalConfig => Ok(ParsedInstruction::InitGlobalConfig(parse_init_global_config_instruction(instruction)?)),
        InstructionKind::InitPair => Ok(ParsedInstruction::InitPair(parse_init_pair_instruction(instruction)?)),
        InstructionKind::RemoveLiquidity => Ok(ParsedInstruction::RemoveLiquidity(parse_remove_liquidity_instruction(instruction)?)),
        InstructionKind::SetLpProtocolFeeConfig => Ok(ParsedInstruction::SetLpProtocolFeeConfig(parse_set_lp_protocol_fee_config_instruction(instruction)?)),
        InstructionKind::SetLpTreasuryEnabled => Ok(ParsedInstruction::SetLpTreasuryEnabled(parse_set_lp_treasury_enabled_instruction(instruction)?)),
        InstructionKind::SetNewAdmin => Ok(ParsedInstruction::SetNewAdmin(parse_set_new_admin_instruction(instruction)?)),
        InstructionKind::SetPausedForAsset => Ok(ParsedInstruction::SetPausedForAsset(parse_set_paused_for_asset_instruction(instruction)?)),
        InstructionKind::SetPausedForLpStableConfig => Ok(ParsedInstruction::SetPausedForLpStableConfig(parse_set_paused_for_lp_stable_config_instruction(instruction)?)),
        InstructionKind::Swap => Ok(ParsedInstruction::Swap(parse_swap_instruction(instruction)?)),
        InstructionKind::UpdateAssetConfigAccount => Ok(ParsedInstruction::UpdateAssetConfigAccount(parse_update_asset_config_account_instruction(instruction)?)),
        InstructionKind::UpdateGlobalConfig => Ok(ParsedInstruction::UpdateGlobalConfig(parse_update_global_config_instruction(instruction)?)),
        InstructionKind::UpdatePair => Ok(ParsedInstruction::UpdatePair(parse_update_pair_instruction(instruction)?)),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccountKind {
    AssetConfig,
    GlobalConfig,
    LpProtocolFeeConfig,
    LpStableConfig,
    Pair,
    UserVaultInfo,
}

pub const ACCOUNT_DISCRIMINATORS: &[(&str, [u8; 8])] = &[
    ("AssetConfig", AssetConfig::DISCRIMINATOR),
    ("GlobalConfig", GlobalConfig::DISCRIMINATOR),
    ("LpProtocolFeeConfig", LpProtocolFeeConfig::DISCRIMINATOR),
    ("LpStableConfig", LpStableConfig::DISCRIMINATOR),
    ("Pair", Pair::DISCRIMINATOR),
    ("UserVaultInfo", UserVaultInfo::DISCRIMINATOR),
];

pub fn identify_account(data: &[u8]) -> std::io::Result<AccountKind> {
    match super::discriminator(data)? {
        AssetConfig::DISCRIMINATOR => Ok(AccountKind::AssetConfig),
        GlobalConfig::DISCRIMINATOR => Ok(AccountKind::GlobalConfig),
        LpProtocolFeeConfig::DISCRIMINATOR => Ok(AccountKind::LpProtocolFeeConfig),
        LpStableConfig::DISCRIMINATOR => Ok(AccountKind::LpStableConfig),
        Pair::DISCRIMINATOR => Ok(AccountKind::Pair),
        UserVaultInfo::DISCRIMINATOR => Ok(AccountKind::UserVaultInfo),
        _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Unknown account discriminator")),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Account {
    AssetConfig(AssetConfig),
    GlobalConfig(GlobalConfig),
    LpProtocolFeeConfig(LpProtocolFeeConfig),
    LpStableConfig(LpStableConfig),
    Pair(Pair),
    UserVaultInfo(UserVaultInfo),
}

impl Account {
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        match identify_account(data)? {
            AccountKind::AssetConfig => Ok(Self::AssetConfig(AssetConfig::decode(data)?)),
            AccountKind::GlobalConfig => Ok(Self::GlobalConfig(GlobalConfig::decode(data)?)),
            AccountKind::LpProtocolFeeConfig => Ok(Self::LpProtocolFeeConfig(LpProtocolFeeConfig::decode(data)?)),
            AccountKind::LpStableConfig => Ok(Self::LpStableConfig(LpStableConfig::decode(data)?)),
            AccountKind::Pair => Ok(Self::Pair(Pair::decode(data)?)),
            AccountKind::UserVaultInfo => Ok(Self::UserVaultInfo(UserVaultInfo::decode(data)?)),
        }
    }

    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        match self {
            Self::AssetConfig(value) => value.encode(),
            Self::GlobalConfig(value) => value.encode(),
            Self::LpProtocolFeeConfig(value) => value.encode(),
            Self::LpStableConfig(value) => value.encode(),
            Self::Pair(value) => value.encode(),
            Self::UserVaultInfo(value) => value.encode(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventKind {
    AdminChanged,
    AssetConfigInitialized,
    AssetConfigUpdated,
    AssetPauseChanged,
    FeesClaimed,
    GlobalConfigInitialized,
    GlobalConfigUpdated,
    LiquidityAdded,
    LiquidityRemoved,
    LpFeeAccountClosed,
    LpProtocolFeeConfigUpdated,
    LpStableConfigPauseChanged,
    LpTreasuryEnabledChanged,
    NewAdminProposed,
    PairClosed,
    PairInitialized,
    PairUpdated,
    SwapExecuted,
    TreasuryPositionClosed,
}

pub const EVENT_DISCRIMINATORS: &[(&str, [u8; 8])] = &[
    ("AdminChanged", AdminChanged::DISCRIMINATOR),
    ("AssetConfigInitialized", AssetConfigInitialized::DISCRIMINATOR),
    ("AssetConfigUpdated", AssetConfigUpdated::DISCRIMINATOR),
    ("AssetPauseChanged", AssetPauseChanged::DISCRIMINATOR),
    ("FeesClaimed", FeesClaimed::DISCRIMINATOR),
    ("GlobalConfigInitialized", GlobalConfigInitialized::DISCRIMINATOR),
    ("GlobalConfigUpdated", GlobalConfigUpdated::DISCRIMINATOR),
    ("LiquidityAdded", LiquidityAdded::DISCRIMINATOR),
    ("LiquidityRemoved", LiquidityRemoved::DISCRIMINATOR),
    ("LpFeeAccountClosed", LpFeeAccountClosed::DISCRIMINATOR),
    ("LpProtocolFeeConfigUpdated", LpProtocolFeeConfigUpdated::DISCRIMINATOR),
    ("LpStableConfigPauseChanged", LpStableConfigPauseChanged::DISCRIMINATOR),
    ("LpTreasuryEnabledChanged", LpTreasuryEnabledChanged::DISCRIMINATOR),
    ("NewAdminProposed", NewAdminProposed::DISCRIMINATOR),
    ("PairClosed", PairClosed::DISCRIMINATOR),
    ("PairInitialized", PairInitialized::DISCRIMINATOR),
    ("PairUpdated", PairUpdated::DISCRIMINATOR),
    ("SwapExecuted", SwapExecuted::DISCRIMINATOR),
    ("TreasuryPositionClosed", TreasuryPositionClosed::DISCRIMINATOR),
];

pub fn identify_event(data: &[u8]) -> std::io::Result<EventKind> {
    match super::discriminator(data)? {
        AdminChanged::DISCRIMINATOR => Ok(EventKind::AdminChanged),
        AssetConfigInitialized::DISCRIMINATOR => Ok(EventKind::AssetConfigInitialized),
        AssetConfigUpdated::DISCRIMINATOR => Ok(EventKind::AssetConfigUpdated),
        AssetPauseChanged::DISCRIMINATOR => Ok(EventKind::AssetPauseChanged),
        FeesClaimed::DISCRIMINATOR => Ok(EventKind::FeesClaimed),
        GlobalConfigInitialized::DISCRIMINATOR => Ok(EventKind::GlobalConfigInitialized),
        GlobalConfigUpdated::DISCRIMINATOR => Ok(EventKind::GlobalConfigUpdated),
        LiquidityAdded::DISCRIMINATOR => Ok(EventKind::LiquidityAdded),
        LiquidityRemoved::DISCRIMINATOR => Ok(EventKind::LiquidityRemoved),
        LpFeeAccountClosed::DISCRIMINATOR => Ok(EventKind::LpFeeAccountClosed),
        LpProtocolFeeConfigUpdated::DISCRIMINATOR => Ok(EventKind::LpProtocolFeeConfigUpdated),
        LpStableConfigPauseChanged::DISCRIMINATOR => Ok(EventKind::LpStableConfigPauseChanged),
        LpTreasuryEnabledChanged::DISCRIMINATOR => Ok(EventKind::LpTreasuryEnabledChanged),
        NewAdminProposed::DISCRIMINATOR => Ok(EventKind::NewAdminProposed),
        PairClosed::DISCRIMINATOR => Ok(EventKind::PairClosed),
        PairInitialized::DISCRIMINATOR => Ok(EventKind::PairInitialized),
        PairUpdated::DISCRIMINATOR => Ok(EventKind::PairUpdated),
        SwapExecuted::DISCRIMINATOR => Ok(EventKind::SwapExecuted),
        TreasuryPositionClosed::DISCRIMINATOR => Ok(EventKind::TreasuryPositionClosed),
        _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Unknown event discriminator")),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    AdminChanged(AdminChanged),
    AssetConfigInitialized(AssetConfigInitialized),
    AssetConfigUpdated(AssetConfigUpdated),
    AssetPauseChanged(AssetPauseChanged),
    FeesClaimed(FeesClaimed),
    GlobalConfigInitialized(GlobalConfigInitialized),
    GlobalConfigUpdated(GlobalConfigUpdated),
    LiquidityAdded(LiquidityAdded),
    LiquidityRemoved(LiquidityRemoved),
    LpFeeAccountClosed(LpFeeAccountClosed),
    LpProtocolFeeConfigUpdated(LpProtocolFeeConfigUpdated),
    LpStableConfigPauseChanged(LpStableConfigPauseChanged),
    LpTreasuryEnabledChanged(LpTreasuryEnabledChanged),
    NewAdminProposed(NewAdminProposed),
    PairClosed(PairClosed),
    PairInitialized(PairInitialized),
    PairUpdated(PairUpdated),
    SwapExecuted(SwapExecuted),
    TreasuryPositionClosed(TreasuryPositionClosed),
}

impl Event {
    pub fn decode(data: &[u8]) -> std::io::Result<Self> {
        match identify_event(data)? {
            EventKind::AdminChanged => Ok(Self::AdminChanged(AdminChanged::decode(data)?)),
            EventKind::AssetConfigInitialized => Ok(Self::AssetConfigInitialized(AssetConfigInitialized::decode(data)?)),
            EventKind::AssetConfigUpdated => Ok(Self::AssetConfigUpdated(AssetConfigUpdated::decode(data)?)),
            EventKind::AssetPauseChanged => Ok(Self::AssetPauseChanged(AssetPauseChanged::decode(data)?)),
            EventKind::FeesClaimed => Ok(Self::FeesClaimed(FeesClaimed::decode(data)?)),
            EventKind::GlobalConfigInitialized => Ok(Self::GlobalConfigInitialized(GlobalConfigInitialized::decode(data)?)),
            EventKind::GlobalConfigUpdated => Ok(Self::GlobalConfigUpdated(GlobalConfigUpdated::decode(data)?)),
            EventKind::LiquidityAdded => Ok(Self::LiquidityAdded(LiquidityAdded::decode(data)?)),
            EventKind::LiquidityRemoved => Ok(Self::LiquidityRemoved(LiquidityRemoved::decode(data)?)),
            EventKind::LpFeeAccountClosed => Ok(Self::LpFeeAccountClosed(LpFeeAccountClosed::decode(data)?)),
            EventKind::LpProtocolFeeConfigUpdated => Ok(Self::LpProtocolFeeConfigUpdated(LpProtocolFeeConfigUpdated::decode(data)?)),
            EventKind::LpStableConfigPauseChanged => Ok(Self::LpStableConfigPauseChanged(LpStableConfigPauseChanged::decode(data)?)),
            EventKind::LpTreasuryEnabledChanged => Ok(Self::LpTreasuryEnabledChanged(LpTreasuryEnabledChanged::decode(data)?)),
            EventKind::NewAdminProposed => Ok(Self::NewAdminProposed(NewAdminProposed::decode(data)?)),
            EventKind::PairClosed => Ok(Self::PairClosed(PairClosed::decode(data)?)),
            EventKind::PairInitialized => Ok(Self::PairInitialized(PairInitialized::decode(data)?)),
            EventKind::PairUpdated => Ok(Self::PairUpdated(PairUpdated::decode(data)?)),
            EventKind::SwapExecuted => Ok(Self::SwapExecuted(SwapExecuted::decode(data)?)),
            EventKind::TreasuryPositionClosed => Ok(Self::TreasuryPositionClosed(TreasuryPositionClosed::decode(data)?)),
        }
    }

    pub fn encode(&self) -> std::io::Result<Vec<u8>> {
        match self {
            Self::AdminChanged(value) => value.encode(),
            Self::AssetConfigInitialized(value) => value.encode(),
            Self::AssetConfigUpdated(value) => value.encode(),
            Self::AssetPauseChanged(value) => value.encode(),
            Self::FeesClaimed(value) => value.encode(),
            Self::GlobalConfigInitialized(value) => value.encode(),
            Self::GlobalConfigUpdated(value) => value.encode(),
            Self::LiquidityAdded(value) => value.encode(),
            Self::LiquidityRemoved(value) => value.encode(),
            Self::LpFeeAccountClosed(value) => value.encode(),
            Self::LpProtocolFeeConfigUpdated(value) => value.encode(),
            Self::LpStableConfigPauseChanged(value) => value.encode(),
            Self::LpTreasuryEnabledChanged(value) => value.encode(),
            Self::NewAdminProposed(value) => value.encode(),
            Self::PairClosed(value) => value.encode(),
            Self::PairInitialized(value) => value.encode(),
            Self::PairUpdated(value) => value.encode(),
            Self::SwapExecuted(value) => value.encode(),
            Self::TreasuryPositionClosed(value) => value.encode(),
        }
    }
}

pub const ERRORS: &[super::ProgramErrorMetadata] = &[
    super::ProgramErrorMetadata { code: 6000, name: "InvalidNav", message: "Invalid NAV" },
    super::ProgramErrorMetadata { code: 6001, name: "ConfidenceTooLow", message: "Confidence too low" },
    super::ProgramErrorMetadata { code: 6002, name: "OutOfRange", message: "Out of range" },
    super::ProgramErrorMetadata { code: 6003, name: "MustProvideAtLeastOneNavData", message: "Must provide at least one NAV data" },
    super::ProgramErrorMetadata { code: 6004, name: "MustProvideHardcodedPrice", message: "Must provide hardcoded price" },
    super::ProgramErrorMetadata { code: 6005, name: "ProgramPaused", message: "Program paused" },
    super::ProgramErrorMetadata { code: 6006, name: "AmountMustBePositive", message: "Amount must be positive" },
    super::ProgramErrorMetadata { code: 6007, name: "InsufficientLiquidity", message: "Insufficient liquidity" },
    super::ProgramErrorMetadata { code: 6008, name: "PairPaused", message: "Pair paused" },
    super::ProgramErrorMetadata { code: 6009, name: "RwaPaused", message: "RWA paused" },
    super::ProgramErrorMetadata { code: 6010, name: "StablePaused", message: "Stable paused" },
    super::ProgramErrorMetadata { code: 6011, name: "Max5NavData", message: "Max 5 NAV data" },
    super::ProgramErrorMetadata { code: 6012, name: "SwapAmountTooSmall", message: "Swap amount too small" },
    super::ProgramErrorMetadata { code: 6013, name: "DiscountMustBePositive", message: "Discount must be positive" },
    super::ProgramErrorMetadata { code: 6014, name: "AmountInMustBePositive", message: "Amount in must be positive" },
    super::ProgramErrorMetadata { code: 6015, name: "AmountOutMustBePositive", message: "Amount out must be positive" },
    super::ProgramErrorMetadata { code: 6016, name: "PriceDecimalsTooLarge", message: "Price decimals too large" },
    super::ProgramErrorMetadata { code: 6017, name: "Unauthorized", message: "Unauthorized" },
    super::ProgramErrorMetadata { code: 6018, name: "MathOverflow", message: "Math Overflow" },
    super::ProgramErrorMetadata { code: 6019, name: "MathUnderflow", message: "Math Underflow" },
    super::ProgramErrorMetadata { code: 6020, name: "InvalidAssetType", message: "Invalid asset type" },
    super::ProgramErrorMetadata { code: 6021, name: "NavMustBePositive", message: "Nav must be positive" },
    super::ProgramErrorMetadata { code: 6022, name: "FeesOutOfRange", message: "Fees out of range" },
    super::ProgramErrorMetadata { code: 6023, name: "AssetConfigInUse", message: "Asset config in use" },
    super::ProgramErrorMetadata { code: 6024, name: "InvalidNewAdmin", message: "Invalid new admin" },
    super::ProgramErrorMetadata { code: 6025, name: "InvalidAccountPublicKey", message: "Invalid account public key" },
    super::ProgramErrorMetadata { code: 6026, name: "AmountInTooHigh", message: "Amount in too high" },
    super::ProgramErrorMetadata { code: 6027, name: "AmountOutTooLow", message: "Amount out too low" },
    super::ProgramErrorMetadata { code: 6028, name: "InsufficientLpFeeBalance", message: "Insufficient LP fee balance" },
    super::ProgramErrorMetadata { code: 6029, name: "InvalidFeedId", message: "Invalid pyth feed id" },
    super::ProgramErrorMetadata { code: 6030, name: "InvalidMaxAge", message: "Pyth max age must be > 0" },
    super::ProgramErrorMetadata { code: 6031, name: "MaxAgeTooLarge", message: "Pyth max age too high" },
    super::ProgramErrorMetadata { code: 6032, name: "ConfBpsTooLarge", message: "Pyth max conf too high" },
    super::ProgramErrorMetadata { code: 6033, name: "MissingPythAccount", message: "Pyth feed missing from remaining accounts" },
    super::ProgramErrorMetadata { code: 6034, name: "FeedIdMismatch", message: "Pyth feed mismatch" },
    super::ProgramErrorMetadata { code: 6035, name: "MissingTreasuryAccounts", message: "Missing treasury accounts" },
    super::ProgramErrorMetadata { code: 6036, name: "InvalidTreasuryProgram", message: "Invalid treasury program" },
    super::ProgramErrorMetadata { code: 6037, name: "TreasuryBalanceNonZero", message: "Treasury balance is non-zero" },
    super::ProgramErrorMetadata { code: 6038, name: "MissingLpStableConfig", message: "LP stable config must be provided for stable tokens" },
    super::ProgramErrorMetadata { code: 6039, name: "NonCanonicalTokenOrder", message: "Quote mint must be lexicographically less than base mint" },
    super::ProgramErrorMetadata { code: 6040, name: "InvalidTreasuryMint", message: "Invalid treasury mint" },
    super::ProgramErrorMetadata { code: 6041, name: "TransferFeeNotSupported", message: "Mints charging a Token-2022 transfer fee are not supported" },
    super::ProgramErrorMetadata { code: 6042, name: "InvalidTokenExtensionData", message: "Token-2022 extension data could not be decoded" },
    super::ProgramErrorMetadata { code: 6043, name: "UnauthorizedInitializer", message: "Caller must be the program upgrade authority" },
    super::ProgramErrorMetadata { code: 6044, name: "LpVaultAuthorityUnderfunded", message: "LP vault authority has insufficient SOL to fund the treasury position rent" },
    super::ProgramErrorMetadata { code: 6045, name: "FeeAssetPaused", message: "Protocol fee asset paused" },
    super::ProgramErrorMetadata { code: 6046, name: "SignerInRemainingAccounts", message: "Remaining accounts must not contain signers" },
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum ProgramError {
    /// Invalid NAV
    InvalidNav = 6000,
    /// Confidence too low
    ConfidenceTooLow = 6001,
    /// Out of range
    OutOfRange = 6002,
    /// Must provide at least one NAV data
    MustProvideAtLeastOneNavData = 6003,
    /// Must provide hardcoded price
    MustProvideHardcodedPrice = 6004,
    /// Program paused
    ProgramPaused = 6005,
    /// Amount must be positive
    AmountMustBePositive = 6006,
    /// Insufficient liquidity
    InsufficientLiquidity = 6007,
    /// Pair paused
    PairPaused = 6008,
    /// RWA paused
    RwaPaused = 6009,
    /// Stable paused
    StablePaused = 6010,
    /// Max 5 NAV data
    Max5NavData = 6011,
    /// Swap amount too small
    SwapAmountTooSmall = 6012,
    /// Discount must be positive
    DiscountMustBePositive = 6013,
    /// Amount in must be positive
    AmountInMustBePositive = 6014,
    /// Amount out must be positive
    AmountOutMustBePositive = 6015,
    /// Price decimals too large
    PriceDecimalsTooLarge = 6016,
    /// Unauthorized
    Unauthorized = 6017,
    /// Math Overflow
    MathOverflow = 6018,
    /// Math Underflow
    MathUnderflow = 6019,
    /// Invalid asset type
    InvalidAssetType = 6020,
    /// Nav must be positive
    NavMustBePositive = 6021,
    /// Fees out of range
    FeesOutOfRange = 6022,
    /// Asset config in use
    AssetConfigInUse = 6023,
    /// Invalid new admin
    InvalidNewAdmin = 6024,
    /// Invalid account public key
    InvalidAccountPublicKey = 6025,
    /// Amount in too high
    AmountInTooHigh = 6026,
    /// Amount out too low
    AmountOutTooLow = 6027,
    /// Insufficient LP fee balance
    InsufficientLpFeeBalance = 6028,
    /// Invalid pyth feed id
    InvalidFeedId = 6029,
    /// Pyth max age must be > 0
    InvalidMaxAge = 6030,
    /// Pyth max age too high
    MaxAgeTooLarge = 6031,
    /// Pyth max conf too high
    ConfBpsTooLarge = 6032,
    /// Pyth feed missing from remaining accounts
    MissingPythAccount = 6033,
    /// Pyth feed mismatch
    FeedIdMismatch = 6034,
    /// Missing treasury accounts
    MissingTreasuryAccounts = 6035,
    /// Invalid treasury program
    InvalidTreasuryProgram = 6036,
    /// Treasury balance is non-zero
    TreasuryBalanceNonZero = 6037,
    /// LP stable config must be provided for stable tokens
    MissingLpStableConfig = 6038,
    /// Quote mint must be lexicographically less than base mint
    NonCanonicalTokenOrder = 6039,
    /// Invalid treasury mint
    InvalidTreasuryMint = 6040,
    /// Mints charging a Token-2022 transfer fee are not supported
    TransferFeeNotSupported = 6041,
    /// Token-2022 extension data could not be decoded
    InvalidTokenExtensionData = 6042,
    /// Caller must be the program upgrade authority
    UnauthorizedInitializer = 6043,
    /// LP vault authority has insufficient SOL to fund the treasury position rent
    LpVaultAuthorityUnderfunded = 6044,
    /// Protocol fee asset paused
    FeeAssetPaused = 6045,
    /// Remaining accounts must not contain signers
    SignerInRemainingAccounts = 6046,
}

impl ProgramError {
    pub const fn from_code(code: u32) -> Option<Self> {
        match code {
            6000 => Some(Self::InvalidNav),
            6001 => Some(Self::ConfidenceTooLow),
            6002 => Some(Self::OutOfRange),
            6003 => Some(Self::MustProvideAtLeastOneNavData),
            6004 => Some(Self::MustProvideHardcodedPrice),
            6005 => Some(Self::ProgramPaused),
            6006 => Some(Self::AmountMustBePositive),
            6007 => Some(Self::InsufficientLiquidity),
            6008 => Some(Self::PairPaused),
            6009 => Some(Self::RwaPaused),
            6010 => Some(Self::StablePaused),
            6011 => Some(Self::Max5NavData),
            6012 => Some(Self::SwapAmountTooSmall),
            6013 => Some(Self::DiscountMustBePositive),
            6014 => Some(Self::AmountInMustBePositive),
            6015 => Some(Self::AmountOutMustBePositive),
            6016 => Some(Self::PriceDecimalsTooLarge),
            6017 => Some(Self::Unauthorized),
            6018 => Some(Self::MathOverflow),
            6019 => Some(Self::MathUnderflow),
            6020 => Some(Self::InvalidAssetType),
            6021 => Some(Self::NavMustBePositive),
            6022 => Some(Self::FeesOutOfRange),
            6023 => Some(Self::AssetConfigInUse),
            6024 => Some(Self::InvalidNewAdmin),
            6025 => Some(Self::InvalidAccountPublicKey),
            6026 => Some(Self::AmountInTooHigh),
            6027 => Some(Self::AmountOutTooLow),
            6028 => Some(Self::InsufficientLpFeeBalance),
            6029 => Some(Self::InvalidFeedId),
            6030 => Some(Self::InvalidMaxAge),
            6031 => Some(Self::MaxAgeTooLarge),
            6032 => Some(Self::ConfBpsTooLarge),
            6033 => Some(Self::MissingPythAccount),
            6034 => Some(Self::FeedIdMismatch),
            6035 => Some(Self::MissingTreasuryAccounts),
            6036 => Some(Self::InvalidTreasuryProgram),
            6037 => Some(Self::TreasuryBalanceNonZero),
            6038 => Some(Self::MissingLpStableConfig),
            6039 => Some(Self::NonCanonicalTokenOrder),
            6040 => Some(Self::InvalidTreasuryMint),
            6041 => Some(Self::TransferFeeNotSupported),
            6042 => Some(Self::InvalidTokenExtensionData),
            6043 => Some(Self::UnauthorizedInitializer),
            6044 => Some(Self::LpVaultAuthorityUnderfunded),
            6045 => Some(Self::FeeAssetPaused),
            6046 => Some(Self::SignerInRemainingAccounts),
            _ => None,
        }
    }

    pub const fn code(self) -> u32 { self as u32 }

    pub const fn name(self) -> &'static str {
        match self {
            Self::InvalidNav => "InvalidNav",
            Self::ConfidenceTooLow => "ConfidenceTooLow",
            Self::OutOfRange => "OutOfRange",
            Self::MustProvideAtLeastOneNavData => "MustProvideAtLeastOneNavData",
            Self::MustProvideHardcodedPrice => "MustProvideHardcodedPrice",
            Self::ProgramPaused => "ProgramPaused",
            Self::AmountMustBePositive => "AmountMustBePositive",
            Self::InsufficientLiquidity => "InsufficientLiquidity",
            Self::PairPaused => "PairPaused",
            Self::RwaPaused => "RwaPaused",
            Self::StablePaused => "StablePaused",
            Self::Max5NavData => "Max5NavData",
            Self::SwapAmountTooSmall => "SwapAmountTooSmall",
            Self::DiscountMustBePositive => "DiscountMustBePositive",
            Self::AmountInMustBePositive => "AmountInMustBePositive",
            Self::AmountOutMustBePositive => "AmountOutMustBePositive",
            Self::PriceDecimalsTooLarge => "PriceDecimalsTooLarge",
            Self::Unauthorized => "Unauthorized",
            Self::MathOverflow => "MathOverflow",
            Self::MathUnderflow => "MathUnderflow",
            Self::InvalidAssetType => "InvalidAssetType",
            Self::NavMustBePositive => "NavMustBePositive",
            Self::FeesOutOfRange => "FeesOutOfRange",
            Self::AssetConfigInUse => "AssetConfigInUse",
            Self::InvalidNewAdmin => "InvalidNewAdmin",
            Self::InvalidAccountPublicKey => "InvalidAccountPublicKey",
            Self::AmountInTooHigh => "AmountInTooHigh",
            Self::AmountOutTooLow => "AmountOutTooLow",
            Self::InsufficientLpFeeBalance => "InsufficientLpFeeBalance",
            Self::InvalidFeedId => "InvalidFeedId",
            Self::InvalidMaxAge => "InvalidMaxAge",
            Self::MaxAgeTooLarge => "MaxAgeTooLarge",
            Self::ConfBpsTooLarge => "ConfBpsTooLarge",
            Self::MissingPythAccount => "MissingPythAccount",
            Self::FeedIdMismatch => "FeedIdMismatch",
            Self::MissingTreasuryAccounts => "MissingTreasuryAccounts",
            Self::InvalidTreasuryProgram => "InvalidTreasuryProgram",
            Self::TreasuryBalanceNonZero => "TreasuryBalanceNonZero",
            Self::MissingLpStableConfig => "MissingLpStableConfig",
            Self::NonCanonicalTokenOrder => "NonCanonicalTokenOrder",
            Self::InvalidTreasuryMint => "InvalidTreasuryMint",
            Self::TransferFeeNotSupported => "TransferFeeNotSupported",
            Self::InvalidTokenExtensionData => "InvalidTokenExtensionData",
            Self::UnauthorizedInitializer => "UnauthorizedInitializer",
            Self::LpVaultAuthorityUnderfunded => "LpVaultAuthorityUnderfunded",
            Self::FeeAssetPaused => "FeeAssetPaused",
            Self::SignerInRemainingAccounts => "SignerInRemainingAccounts",
        }
    }

    pub const fn message(self) -> &'static str {
        match self {
            Self::InvalidNav => "Invalid NAV",
            Self::ConfidenceTooLow => "Confidence too low",
            Self::OutOfRange => "Out of range",
            Self::MustProvideAtLeastOneNavData => "Must provide at least one NAV data",
            Self::MustProvideHardcodedPrice => "Must provide hardcoded price",
            Self::ProgramPaused => "Program paused",
            Self::AmountMustBePositive => "Amount must be positive",
            Self::InsufficientLiquidity => "Insufficient liquidity",
            Self::PairPaused => "Pair paused",
            Self::RwaPaused => "RWA paused",
            Self::StablePaused => "Stable paused",
            Self::Max5NavData => "Max 5 NAV data",
            Self::SwapAmountTooSmall => "Swap amount too small",
            Self::DiscountMustBePositive => "Discount must be positive",
            Self::AmountInMustBePositive => "Amount in must be positive",
            Self::AmountOutMustBePositive => "Amount out must be positive",
            Self::PriceDecimalsTooLarge => "Price decimals too large",
            Self::Unauthorized => "Unauthorized",
            Self::MathOverflow => "Math Overflow",
            Self::MathUnderflow => "Math Underflow",
            Self::InvalidAssetType => "Invalid asset type",
            Self::NavMustBePositive => "Nav must be positive",
            Self::FeesOutOfRange => "Fees out of range",
            Self::AssetConfigInUse => "Asset config in use",
            Self::InvalidNewAdmin => "Invalid new admin",
            Self::InvalidAccountPublicKey => "Invalid account public key",
            Self::AmountInTooHigh => "Amount in too high",
            Self::AmountOutTooLow => "Amount out too low",
            Self::InsufficientLpFeeBalance => "Insufficient LP fee balance",
            Self::InvalidFeedId => "Invalid pyth feed id",
            Self::InvalidMaxAge => "Pyth max age must be > 0",
            Self::MaxAgeTooLarge => "Pyth max age too high",
            Self::ConfBpsTooLarge => "Pyth max conf too high",
            Self::MissingPythAccount => "Pyth feed missing from remaining accounts",
            Self::FeedIdMismatch => "Pyth feed mismatch",
            Self::MissingTreasuryAccounts => "Missing treasury accounts",
            Self::InvalidTreasuryProgram => "Invalid treasury program",
            Self::TreasuryBalanceNonZero => "Treasury balance is non-zero",
            Self::MissingLpStableConfig => "LP stable config must be provided for stable tokens",
            Self::NonCanonicalTokenOrder => "Quote mint must be lexicographically less than base mint",
            Self::InvalidTreasuryMint => "Invalid treasury mint",
            Self::TransferFeeNotSupported => "Mints charging a Token-2022 transfer fee are not supported",
            Self::InvalidTokenExtensionData => "Token-2022 extension data could not be decoded",
            Self::UnauthorizedInitializer => "Caller must be the program upgrade authority",
            Self::LpVaultAuthorityUnderfunded => "LP vault authority has insufficient SOL to fund the treasury position rent",
            Self::FeeAssetPaused => "Protocol fee asset paused",
            Self::SignerInRemainingAccounts => "Remaining accounts must not contain signers",
        }
    }
}

impl std::fmt::Display for ProgramError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.message())
    }
}

impl std::error::Error for ProgramError {}