may_cpi 13.0.0

CPI for the Mayflower program
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
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
use anchor_lang::prelude::*;

#[cfg(feature = "local")]
declare_id!("43bYyFn8WBwxXvXh28yQ22SQz1TMY1w5DYnRAzRqpJ1J");

#[cfg(feature = "devnet")]
declare_id!("MD2pPJCjpUT5ttJFUVeP2Xka1ZSvCJMZUoX4XTdPdet");

#[cfg(feature = "mainnet")]
declare_id!("MMkP6WPG4ySTudigPQpKNpranEYBzYRDe8Ua7Dx89Rk");

#[program]
pub mod mayflower {
    use super::*;

    pub fn version(_ctx: Context<VersionAccounts>) -> Result<()> {
        panic!("not implemented")
    }

    pub fn init_log_account(_ctx: Context<InitLogAccountAccounts>) -> Result<()> {
        panic!("not implemented")
    }

    pub fn receive_log(_ctx: Context<ReceiveLogAccounts>, _log: [u8; 504]) -> Result<()> {
        panic!("not implemented")
    }

    pub fn test_log(_ctx: Context<TestLogAccounts>) -> Result<()> {
        panic!("not implemented")
    }

    /// Initialize a platform tenant.
    /// 
    /// Tenants are the top-level organizational units in the protocol. Each tenant can have
    /// multiple market groups, and receives a portion of all fees generated by markets under
    /// their umbrella.
    /// 
    /// # Arguments
    /// 
    /// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
    /// This fee is taken from all market operations and distributed to the tenant.
    /// * `permissionless_group_creation` - If true, anyone can create market groups under this
    /// tenant. If false, only the tenant admin can create new groups.
    /// 
    /// # Access Control
    /// 
    /// This instruction can only be called by the program itself (root authority).
    pub fn tenant_init(_ctx: Context<TenantInitAccounts>, _fee_micro_bps: u32, _permissionless_group_creation: bool) -> Result<()> {
        panic!("not implemented")
    }

    /// Initialize a platform tenant with an admin.
    /// 
    /// This instruction is similar to `tenant_init` but allows specifying an admin
    /// account that will have full control over the tenant.
    /// 
    /// # Arguments
    /// 
    /// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
    /// This fee is taken from all market operations and distributed to the tenant.
    /// * `permissionless_group_creation` - If true, anyone can create market groups under this
    /// tenant. If false, only the tenant admin can create new groups.
    /// * `admin` - Public key of the admin account that will have full control over the tenant.
    pub fn tenant_init_with_admin(_ctx: Context<TenantInitWithAdminAccounts>, _fee_micro_bps: u32, _permissionless_group_creation: bool, _admin: Pubkey) -> Result<()> {
        panic!("not implemented")
    }

    /// Propose a new admin for the tenant.
    /// 
    /// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
    /// who must then accept the role using `tenant_accept_new_admin`.
    pub fn tenant_propose_admin(_ctx: Context<TenantProposeAdminAccounts>, _new_admin: Pubkey) -> Result<TenantProposeAdminEvent> {
        panic!("not implemented")
    }

    /// Accept admin ownership of a tenant.
    /// 
    /// Completes the two-step ownership transfer process. The proposed admin calls this
    /// instruction to accept control of the tenant.
    pub fn tenant_accept_new_admin(_ctx: Context<TenantAcceptNewAdminAccounts>) -> Result<TenantAcceptNewAdminEvent> {
        panic!("not implemented")
    }

    /// Change the fee rate for a tenant.
    /// 
    /// Updates the platform fee rate applied to all market operations under this tenant.
    pub fn tenant_change_fee_mbps(_ctx: Context<TenantChangeFeeMbpsAccounts>, _fee_micro_bps: u32) -> Result<TenantChangeFeeMbpsEvent> {
        panic!("not implemented")
    }

    /// Initialize a market group under a tenant.
    /// 
    /// Market groups are collections of markets that share the same fee structure and admin.
    /// Each group can contain multiple markets with different token pairs and price curves.
    /// The group admin has control over all markets within the group and collects trading fees.
    /// 
    /// # Arguments
    /// 
    /// * `args` - Initialization arguments containing:
    /// - `fees`: Fee structure for buy, sell, borrow, and exercise operations
    /// - `group_admin`: Public key that will administer this market group
    /// 
    /// # Access Control
    /// 
    /// If the tenant has `permissionless_group_creation` disabled, only the tenant admin
    /// can create new market groups.
    pub fn market_group_init(_ctx: Context<MarketGroupInitAccounts>, _args: MarketGroupInitArgs) -> Result<()> {
        panic!("not implemented")
    }

    /// Propose a new admin for the market group.
    /// 
    /// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
    /// who must then accept the role using `market_group_accept_new_admin`.
    /// 
    /// # Arguments
    /// 
    /// * `new_admin` - Public key of the proposed new admin
    /// 
    /// # Access Control
    /// 
    /// Only the current market group admin can propose a new admin.
    /// 
    /// # Security
    /// 
    /// Two-step transfer prevents accidental loss of admin control by requiring the new admin
    /// to explicitly accept the role.
    pub fn market_group_propose_admin(_ctx: Context<MarketGroupProposeAdminAccounts>, _new_admin: Pubkey) -> Result<MarketGroupProposeAdminEvent> {
        panic!("not implemented")
    }

    /// Accept admin ownership of a market group.
    /// 
    /// Completes the two-step ownership transfer process. The proposed admin calls this
    /// instruction to accept control of the market group.
    /// 
    /// # Access Control
    /// 
    /// Only the proposed new admin can accept ownership.
    /// 
    /// # Effects
    /// 
    /// - Transfers full admin control to the new admin
    /// - Clears the proposed admin field
    /// - The new admin gains ability to:
    /// - Create new markets in the group
    /// - Change group fees
    /// - Collect accumulated revenue
    /// - Modify market permissions
    pub fn market_group_accept_new_admin(_ctx: Context<MarketGroupAcceptNewAdminAccounts>) -> Result<MarketGroupAcceptNewAdminEvent> {
        panic!("not implemented")
    }

    /// Initialize a linear market with a simple price curve.
    /// 
    /// Creates a new market with a linear bonding curve that determines token prices based on
    /// supply. The curve has three segments: floor (constant price), shoulder (linear increase),
    /// and tail (constant max price).
    /// 
    /// # Arguments
    /// 
    /// * `market_linear_args` - Configuration parameters including:
    /// - `floor`: Minimum price per token (floor price)
    /// - `target`: Target price where the shoulder segment ends
    /// - `slope_numerator` / `slope_denominator`: Rate of price increase in shoulder segment
    /// - `shoulder_start` / `shoulder_end`: Token supply range for linear price growth
    /// - `tail_start`: Token supply where max price is reached
    /// - `permissions`: Trading restrictions and feature flags
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can create new markets.
    /// 
    /// # Created Accounts
    /// 
    /// - Market account storing price curve and state
    /// - Token mint for the market's synthetic token
    /// - Option token mint for exercisable options
    /// - Liquidity vault holding backing collateral
    /// - Revenue escrow accounts for fee collection
    pub fn market_linear_init(_ctx: Context<MarketLinearInitAccounts>, _market_linear_args: MarketLinearArgs) -> Result<()> {
        panic!("not implemented")
    }

    /// Initialize a linear market with Dutch auction price boost.
    /// 
    /// Creates a linear market with an additional Dutch auction mechanism that provides
    /// temporary price boosts. The boost decays over time from a maximum multiplier down
    /// to 1x (no boost).
    /// 
    /// # Arguments
    /// 
    /// * `market_linear_init_with_dutch_args` - Configuration containing:
    /// - All standard linear market parameters (floor, target, slopes, etc.)
    /// - `dutch_numerator` / `dutch_denominator`: Maximum price boost multiplier
    /// - `dutch_duration`: Time in seconds for boost to decay from max to 1x
    /// - `dutch_start`: Unix timestamp when the Dutch auction begins
    /// 
    /// # Dutch Auction Mechanics
    /// 
    /// - Initial boost: price × (dutch_numerator / dutch_denominator)
    /// - Linear decay over dutch_duration seconds
    /// - After duration expires, boost remains at 1x (no effect)
    /// - Useful for token launches to incentivize early buyers
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can create new markets.
    pub fn market_linear_init_with_dutch(_ctx: Context<MarketLinearInitWithDutchAccounts>, _market_linear_init_with_dutch_args: MarketLinearInitWithDutchArgs) -> Result<()> {
        panic!("not implemented")
    }

    /// Mint option tokens by depositing market tokens.
    /// 
    /// Converts market tokens into option tokens at a 1:1 ratio. Option tokens represent
    /// the right to purchase market tokens at the floor price by depositing the main
    /// backing token (e.g., USDC).
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Number of market tokens to convert into options
    /// 
    /// # Requirements
    /// 
    /// - User must have sufficient market token balance
    /// - Market must allow option minting (check permissions)
    /// 
    /// # Use Cases
    /// 
    /// - Hedge against price increases by locking in floor price
    /// - Create structured products with downside protection
    /// - Enable secondary markets for price speculation
    pub fn mint_options(_ctx: Context<MintOptionsAccounts>, _amount: u64) -> Result<MintOptionsEvent> {
        panic!("not implemented")
    }

    /// Collect accumulated trading fees from a market group.
    /// 
    /// Transfers fee revenue from the group's escrow account to the admin's wallet.
    /// Fees accumulate from all trading operations (buy, sell, borrow, exercise) across
    /// all markets in the group.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Amount to collect:
    /// - `FullOrPartialU64::Full`: Collect entire escrow balance
    /// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can collect revenue.
    /// 
    /// # Fee Distribution
    /// 
    /// Trading fees are split between:
    /// - Tenant: Platform-level fee (set during tenant creation)
    /// - Market Group: Admin fee (set during group creation)
    /// 
    /// This instruction collects only the group's portion.
    pub fn market_group_collect_rev(_ctx: Context<MarketGroupCollectRevAccounts>, _amount: FullOrPartialU64) -> Result<MarketGroupCollectRevEvent> {
        panic!("not implemented")
    }

    /// Collect accumulated platform fees from a tenant.
    /// 
    /// Transfers platform fee revenue from the tenant's escrow account to the admin's wallet.
    /// Platform fees accumulate from all trading operations (buy, sell, borrow, exercise) across
    /// all markets under this tenant.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Amount to collect:
    /// - `FullOrPartialU64::Full`: Collect entire escrow balance
    /// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
    /// 
    /// # Access Control
    /// 
    /// Only the tenant admin can collect platform revenue.
    /// 
    /// # Fee Distribution
    /// 
    /// Trading fees are split between:
    /// - Tenant: Platform-level fee (set during tenant creation)
    /// - Market Group: Admin fee (set during group creation)
    /// 
    /// This instruction collects only the tenant's platform fee portion.
    pub fn tenant_collect_rev(_ctx: Context<TenantCollectRevAccounts>, _amount: FullOrPartialU64) -> Result<TenantCollectRevEvent> {
        panic!("not implemented")
    }

    /// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
    /// 
    /// Raise the market floor price while preserving bonding curve area.
    /// 
    /// Increases the minimum (floor) price of the market token while maintaining the
    /// total area under the price curve. This ensures the market's total value capacity
    /// remains constant while providing price support.
    /// 
    /// # Arguments
    /// 
    /// * `new_floor` - New minimum price per token (must be higher than current)
    /// * `new_shoulder_end` - New token supply where shoulder segment ends
    /// 
    /// # Curve Adjustment
    /// 
    /// When the floor rises:
    /// - Floor segment moves up to new price level
    /// - Shoulder segment becomes steeper to preserve area
    /// - Tail segment adjusts to maintain continuity
    /// 
    /// # Requirements
    /// 
    /// - Market must have excess liquidity to support higher floor
    /// - New floor must be greater than current floor
    /// - Curve area preservation must be mathematically valid
    /// 
    /// # Access Control
    /// 
    /// Can be triggered by authorized operators or through automated mechanisms.
    pub fn raise_floor_preserve_area(_ctx: Context<RaiseFloorPreserveAreaAccounts>, _new_floor: DecimalSerialized, _new_shoulder_end: u64) -> Result<RaiseFloorFromTriggerEvent> {
        panic!("not implemented")
    }

    /// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
    /// 
    /// Raise the floor price with additional validation checks.
    /// 
    /// Similar to `raise_floor_preserve_area` but includes extra safety checks to ensure
    /// the operation maintains market integrity. Validates curve parameters and liquidity
    /// requirements before applying changes.
    /// 
    /// # Arguments
    /// 
    /// * `args` - Parameters including:
    /// - `new_floor`: Target floor price
    /// - `new_shoulder_end`: Adjusted shoulder endpoint
    /// - `max_deviation_bps`: Maximum allowed deviation in basis points
    /// 
    /// # Additional Checks
    /// 
    /// - Verifies sufficient backing liquidity exists
    /// - Ensures curve area preservation within tolerance
    /// - Validates no tokens would be instantly profitable to redeem
    /// - Checks market state consistency after adjustment
    /// 
    /// # Use Cases
    /// 
    /// - Automated floor raising based on market conditions
    /// - Protocol-driven price support mechanisms
    /// - Treasury management operations
    pub fn raise_floor_preserve_area_checked(_ctx: Context<RaiseFloorPreserveAreaCheckedAccounts>, _args: RaiseFloorPreserveAreaCheckedArgs) -> Result<RaiseFloorPreserveAreaCheckedEvent> {
        panic!("not implemented")
    }

    /// Raise the floor and preserve the area of the market
    /// This instruction takes in constraints
    /// * `new_floor` - The new floor price (must be greater than the current floor)
    /// * `new_shoulder_end` - The new shoulder end (must be greater than the current shoulder end)
    /// * `min_liq_ratio` - The minimum liquidity ratio (greater than or equal to 0.0)
    /// * `max_area_shrinkage_tolerance_units` - The maximum token units that the total area of the curve is allowed to shrink by
    /// This is set by the client to restrict overly aggressive floor raising, with a tolerance to account for "slippage"
    /// 
    /// # Access Control
    /// Only the market group admin can raise the floor price.
    pub fn raise_floor_preserve_area_checked2(_ctx: Context<RaiseFloorPreserveAreaChecked2Accounts>, _args: RaiseFloorPreserveAreaCheckedArgs2) -> Result<RaiseFloorPreserveAreaChecked2Event> {
        panic!("not implemented")
    }

    /// DEPRECATED: use raise_floor_from_excess_liquidity2 instead, as it is more secure
    /// 
    /// Raise the floor price using excess market liquidity.
    /// 
    /// Automatically increases the floor price when the market has accumulated excess
    /// backing liquidity beyond what's needed for the current token supply. This provides
    /// organic price appreciation based on market performance.
    /// 
    /// # Arguments
    /// 
    /// * `floor_increase_ratio` - Percentage increase for the floor price (as decimal)
    /// - 0.1 = 10% increase
    /// - 0.05 = 5% increase
    /// - Must be positive and reasonable (typically < 0.5)
    /// 
    /// # Mechanism
    /// 
    /// 1. Calculates available excess liquidity (cash above backing requirements)
    /// 2. Determines maximum sustainable floor increase
    /// 3. Applies requested ratio (capped by available excess)
    /// 4. Adjusts curve parameters to preserve total area
    /// 
    /// # Requirements
    /// 
    /// - Market must have excess liquidity
    /// - Floor increase must be sustainable given current token supply
    /// - Market permissions must allow floor raising
    /// 
    /// # Benefits
    /// 
    /// - Rewards token holders when market performs well
    /// - Creates deflationary pressure through higher floor
    /// - Maintains full backing at new price levels
    pub fn raise_floor_from_excess_liquidity(_ctx: Context<RaiseFloorFromExcessLiquidityAccounts>, _floor_increase_ratio: DecimalSerialized) -> Result<RaiseFloorFromExcessLiquidityEvent> {
        panic!("not implemented")
    }

    /// Raise the floor price using excess market liquidity.
    /// 
    /// Automatically increases the floor price when the market has accumulated excess
    /// backing liquidity beyond what's needed for the current token supply. This provides
    /// organic price appreciation based on market performance.
    /// 
    /// # Arguments
    /// 
    /// * `args` - Parameters including:
    /// - `max_new_floor`: The maximum new floor that is allowed
    /// - `increase_ratio_micro_basis_points`: The amount to increase the floor by, in micro basis points
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can raise the floor price.
    /// 
    /// # Use Cases
    /// - Automated floor raising based on market conditions
    /// - Protocol-driven price support mechanisms
    /// - Treasury management operations
    pub fn raise_floor_from_excess_liquidity_checked(_ctx: Context<RaiseFloorFromExcessLiquidityCheckedAccounts>, _args: RaiseFloorFromExcessLiquidityCheckedArgs) -> Result<RaiseFloorFromExcessLiquidity2Event> {
        panic!("not implemented")
    }

    /// Update market permissions and feature flags.
    /// 
    /// Controls which operations are allowed on a market. Can be used to pause trading,
    /// disable specific features, or adjust market behavior.
    /// 
    /// # Arguments
    /// 
    /// * `new_flags` - New permission set including:
    /// - `can_buy`: Allow token purchases
    /// - `can_sell`: Allow token sales
    /// - `can_borrow`: Allow borrowing against collateral
    /// - `can_add_liquidity`: Allow liquidity donations
    /// - `can_remove_liquidity`: Allow liquidity removal
    /// - `can_open_position`: Allow new position creation
    /// - `can_close_position`: Allow position closure
    /// - `can_change_fees`: Allow fee adjustments
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can change market flags.
    /// 
    /// # Use Cases
    /// 
    /// - Emergency pause during security incidents
    /// - Gradual feature rollout
    /// - Market maintenance windows
    /// - Compliance-driven restrictions
    pub fn market_flags_change(_ctx: Context<MarketFlagsChangeAccounts>, _new_flags: MarketPermissions) -> Result<MarketFlagsChangeEvent> {
        panic!("not implemented")
    }

    /// Update fee structure for all markets in a group.
    /// 
    /// Changes the fee rates charged on trading operations. New fees apply to all future
    /// transactions across all markets within the group.
    /// 
    /// # Arguments
    /// 
    /// * `new_fees` - Updated fee structure:
    /// - `buy`: Fee on token purchases (micro basis points)
    /// - `sell`: Fee on token sales (micro basis points)
    /// - `borrow`: Fee on borrowing operations (micro basis points)
    /// - `exercise`: Fee on option exercise (micro basis points)
    /// 
    /// # Fee Calculation
    /// 
    /// Fees are specified in micro basis points where:
    /// - 1 micro bp = 1/100 of a basis point = 0.0001%
    /// - 100 micro bps = 1 basis point = 0.01%
    /// - 10,000 micro bps = 100 basis points = 1%
    /// - Example: 50 micro bps = 0.5 basis points = 0.005% fee
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can change fees.
    /// 
    /// # Considerations
    /// 
    /// - Changes affect all markets in the group immediately
    /// - Cannot exceed maximum fee limits set by protocol
    /// - Platform (tenant) fees are added on top of group fees
    pub fn market_group_change_fees(_ctx: Context<MarketGroupChangeFeesAccounts>, _new_fees: Fees) -> Result<MarketGroupChangeFeesEvent> {
        panic!("not implemented")
    }

    /// Initialize a personal position account for market interaction.
    /// 
    /// Creates a user-specific account that tracks collateral deposits and debt obligations
    /// for a particular market. Required before performing borrow operations or using
    /// collateral-based features.
    /// 
    /// # Position Features
    /// 
    /// Personal positions enable:
    /// - Collateral deposits (market tokens as collateral)
    /// - Borrowing against collateral (up to LTV limits)
    /// - Tracking debt obligations and interest
    /// - Liquidation protection through collateralization
    /// 
    /// # Account Structure
    /// 
    /// - Unique per user per market
    /// - Stores collateral and debt balances
    /// - Tracks last update timestamp for interest
    /// - Immutable market and owner references
    /// 
    /// # One-Time Setup
    /// 
    /// Each user needs only one position per market. Attempting to create a duplicate
    /// will fail. The position persists until explicitly closed.
    pub fn personal_position_init(_ctx: Context<PersonalPositionInitAccounts>) -> Result<PersonalPositionInitEvent> {
        panic!("not implemented")
    }

    /// DEPRECATED: use donate_liquidity2 instead, as v2 gets logged by the indexer
    /// 
    /// Donate backing liquidity to the market.
    /// 
    /// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
    /// market tokens in return. This creates excess liquidity that can be used to raise
    /// the floor price or improve market stability.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Amount of main tokens to donate
    /// 
    /// # Effects
    /// 
    /// - Increases market's cash balance
    /// - Creates excess liquidity (cash > backing requirements)
    /// - Enables floor price increases
    /// - Benefits all token holders through improved backing
    /// 
    /// # Use Cases
    /// 
    /// - Protocol treasury supporting market stability
    /// - Community-funded price support
    /// - Grants or subsidies to bootstrap markets
    /// - Creating buffer for market operations
    /// 
    /// # Note
    /// 
    /// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
    pub fn donate_liquidity(_ctx: Context<DonateLiquidityAccounts>, _amount: u64) -> Result<DonateLiquidityEvent> {
        panic!("not implemented")
    }

    /// Donate backing liquidity to the market.
    /// 
    /// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
    /// market tokens in return. This creates excess liquidity that can be used to raise
    /// the floor price or improve market stability.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Amount of main tokens to donate
    /// 
    /// # Effects
    /// 
    /// - Increases market's cash balance
    /// - Creates excess liquidity (cash > backing requirements)
    /// - Enables floor price increases
    /// - Benefits all token holders through improved backing
    /// 
    /// # Use Cases
    /// 
    /// - Protocol treasury supporting market stability
    /// - Community-funded price support
    /// - Grants or subsidies to bootstrap markets
    /// - Creating buffer for market operations
    /// 
    /// # Note
    /// 
    /// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
    pub fn donate_liquidity2(_ctx: Context<DonateLiquidity2Accounts>, _amount: u64) -> Result<DonateLiquidityEvent> {
        panic!("not implemented")
    }

    /// Buy market tokens using exact amount of main tokens.
    /// 
    /// Purchases market tokens by depositing a specific amount of main tokens (e.g., USDC).
    /// The number of tokens received depends on the current price curve position. Includes
    /// slippage protection through minimum output requirement.
    /// 
    /// # Arguments
    /// 
    /// * `cash_in` - Exact amount of main tokens to spend
    /// * `min_token_out` - Minimum market tokens to receive (reverts if not met)
    /// 
    /// # Price Calculation
    /// 
    /// Token price follows the bonding curve:
    /// - Floor segment: Constant price at floor level
    /// - Shoulder segment: Linear price increase
    /// - Tail segment: Constant price at maximum
    /// - Dutch boost: Temporary multiplier if active
    /// 
    /// # Fees
    /// 
    /// Buy fee is deducted from input amount:
    /// - Platform fee (tenant level)
    /// - Group fee (market group level)
    /// - Net amount used for token purchase
    /// 
    /// # Slippage Protection
    /// 
    /// Transaction reverts if `tokens_received < min_token_out`
    pub fn buy_with_exact_cash_in(_ctx: Context<BuyWithExactCashInAccounts>, _cash_in: u64, _min_token_out: u64) -> Result<BuyEvent> {
        panic!("not implemented")
    }

    /// Buy market tokens and immediately deposit as collateral.
    /// 
    /// Combines token purchase with collateral deposit in a single atomic transaction.
    /// Useful for users who want to immediately use purchased tokens as collateral for
    /// borrowing operations.
    /// 
    /// # Arguments
    /// 
    /// * `cash_in` - Exact amount of main tokens to spend
    /// * `min_token_out` - Minimum market tokens to receive
    /// 
    /// # Transaction Flow
    /// 
    /// 1. Deduct fees from input amount
    /// 2. Purchase tokens at current curve price
    /// 3. Deposit all tokens into personal position
    /// 4. Update position's collateral balance
    /// 
    /// # Requirements
    /// 
    /// - Personal position must exist (call `personal_position_init` first)
    /// - Sufficient main token balance
    /// - Market must allow buying and deposits
    /// 
    /// # Benefits
    /// 
    /// - Single transaction reduces costs
    /// - Atomic operation prevents MEV
    /// - Immediate collateral availability
    pub fn buy_with_exact_cash_in_and_deposit(_ctx: Context<BuyWithExactCashInAndDepositAccounts>, _cash_in: u64, _min_token_out: u64) -> Result<BuyWithExactCashInAndDepositEvent> {
        panic!("not implemented")
    }

    /// Buy market tokens and immediately deposit as collateral with debt.
    /// 
    /// Combines token purchase with collateral deposit in a single atomic transaction.
    /// Useful for users who want to immediately use purchased tokens as collateral for
    /// borrowing operations.
    /// 
    /// # Arguments
    /// 
    /// * `args` - Arguments for the transaction
    /// - `exact_cash_in` - Exact amount of cash to spend on tokens
    /// - `min_token_received` - Minimum acceptable tokens to receive (slippage protection)
    /// - `new_acquired_debt` - New debt amount to take on
    pub fn buy_with_exact_cash_in_and_deposit_with_debt(_ctx: Context<BuyWithExactCashInAndDepositWithDebtAccounts>, _args: BuyWithExactCashInAndDepositWithDebtArgs) -> Result<BuyWithExactCashInAndDepositWithDebtEvent> {
        panic!("not implemented")
    }

    /// Sell exact amount of market tokens for main tokens.
    /// 
    /// Sells a specific number of market tokens and receives main tokens (e.g., USDC)
    /// based on the current bonding curve price. Includes slippage protection through
    /// minimum output requirement.
    /// 
    /// # Arguments
    /// 
    /// * `amount_in` - Exact number of market tokens to sell
    /// * `cash_out_min` - Minimum main tokens to receive (reverts if not met)
    /// 
    /// # Price Calculation
    /// 
    /// Sell price follows bonding curve in reverse:
    /// - Reduces token supply, moving down the curve
    /// - Higher supplies sell at higher prices first
    /// - Cannot sell below floor price
    /// 
    /// # Fees
    /// 
    /// Sell fee is deducted from output amount:
    /// - Gross proceeds calculated from curve
    /// - Platform and group fees deducted
    /// - Net amount sent to seller
    /// 
    /// # Market Impact
    /// 
    /// Large sells may experience price slippage as they move down the curve.
    /// Consider breaking into smaller transactions for better execution.
    pub fn sell_with_exact_token_in(_ctx: Context<SellWithExactTokenInAccounts>, _amount_in: u64, _cash_out_min: u64) -> Result<SellWithExactTokenInEvent> {
        panic!("not implemented")
    }

    /// Withdraw collateral and sell tokens in one transaction.
    /// 
    /// Atomically withdraws market tokens from a personal position and sells them for
    /// main tokens. Useful for exiting collateralized positions or taking profits.
    /// 
    /// # Arguments
    /// 
    /// * `amount_in` - Number of tokens to withdraw and sell
    /// * `cash_out_min` - Minimum main tokens to receive
    /// 
    /// # Transaction Flow
    /// 
    /// 1. Withdraw tokens from personal position
    /// 2. Check position remains healthy (if debt exists)
    /// 3. Sell tokens on bonding curve
    /// 4. Transfer proceeds to user
    /// 
    /// # Position Health
    /// 
    /// If position has outstanding debt:
    /// - Remaining collateral must maintain required LTV
    /// - Transaction reverts if withdrawal would enable liquidation
    /// - Consider repaying debt before large withdrawals
    /// 
    /// # Use Cases
    /// 
    /// - Taking profits while maintaining position
    /// - Reducing exposure during market volatility
    /// - Exiting positions efficiently
    pub fn sell_with_exact_token_in_after_withdraw(_ctx: Context<SellWithExactTokenInAfterWithdrawAccounts>, _amount_in: u64, _cash_out_min: u64) -> Result<SellWithExactTokenInAfterWithdrawEvent> {
        panic!("not implemented")
    }

    /// Deposit market tokens as collateral into personal position.
    /// 
    /// Adds market tokens to your position's collateral balance, enabling borrowing
    /// operations. Deposited tokens remain locked until withdrawn or liquidated.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Number of market tokens to deposit
    /// 
    /// # Collateral Benefits
    /// 
    /// - Enables borrowing main tokens up to LTV limit
    /// - Earns potential appreciation if floor price rises
    /// - Protects position from liquidation
    /// - Can be withdrawn anytime (if position healthy)
    /// 
    /// # Requirements
    /// 
    /// - Personal position must exist
    /// - Sufficient token balance in wallet
    /// - Market must allow deposits
    pub fn deposit(_ctx: Context<DepositAccounts>, _amount: u64) -> Result<DepositEvent> {
        panic!("not implemented")
    }

    /// Withdraw collateral from personal position.
    /// 
    /// Removes market tokens from collateral, returning them to your wallet. Withdrawal
    /// is only allowed if the position remains healthy after removal.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Number of market tokens to withdraw
    /// 
    /// # Health Requirements
    /// 
    /// If position has debt:
    /// - Remaining collateral value must exceed debt × (1 / LTV)
    /// - Example: $1000 debt at 80% LTV requires $1250 collateral
    /// - Transaction reverts if health check fails
    /// 
    /// # Full Withdrawal
    /// 
    /// To withdraw all collateral:
    /// 1. Repay all outstanding debt first
    /// 2. Then withdraw full collateral balance
    pub fn withdraw(_ctx: Context<WithdrawAccounts>, _amount: u64) -> Result<WithdrawEvent> {
        panic!("not implemented")
    }

    /// Borrow main tokens against deposited collateral.
    /// 
    /// Takes a loan in main tokens (e.g., USDC) using market tokens as collateral.
    /// Borrowed amount is limited by position's collateral value and market LTV ratio.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Amount of main tokens to borrow
    /// 
    /// # Borrowing Limits
    /// 
    /// Maximum borrow = Collateral Value × LTV Ratio
    /// - Collateral valued at current floor price
    /// - LTV typically 50-80% depending on market
    /// - Cannot exceed available market liquidity
    /// 
    /// # Interest Accrual
    /// 
    /// - Interest calculated per-second at market rate
    /// - Compounds continuously on outstanding debt
    /// - Rate may vary based on utilization
    /// 
    /// # Liquidation Risk
    /// 
    /// Position can be liquidated if:
    /// - Market token price drops significantly
    /// - Accumulated interest pushes debt above limit
    /// - Market LTV parameters change
    /// 
    /// Monitor position health regularly to avoid liquidation.
    pub fn borrow(_ctx: Context<BorrowAccounts>, _amount: u64) -> Result<BorrowEvent> {
        panic!("not implemented")
    }

    /// Repay borrowed main tokens to reduce debt.
    /// 
    /// Repays outstanding debt in main tokens, reducing position's obligations and
    /// improving health factor. Can repay partial or full amounts.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Amount of main tokens to repay
    /// 
    /// # Repayment Order
    /// 
    /// Payments apply to:
    /// 1. Accrued interest first
    /// 2. Principal debt second
    /// 
    /// # Benefits of Repayment
    /// 
    /// - Reduces liquidation risk
    /// - Stops interest accrual on repaid amount
    /// - Frees up borrowing capacity
    /// - Enables collateral withdrawal
    /// 
    /// # Full Repayment
    /// 
    /// To close position completely:
    /// 1. Repay all debt including accrued interest
    /// 2. Withdraw all collateral
    /// 3. Position can then be closed if desired
    pub fn repay(_ctx: Context<RepayAccounts>, _amount: u64) -> Result<RepayEvent> {
        panic!("not implemented")
    }

    /// Withdraw collateral, sell it, and optionally repay debt from proceeds.
    /// 
    /// Atomically combines withdraw, sell, and repay operations. Withdraws collateral tokens
    /// from personal position, sells them back to the market, optionally repays debt from
    /// the proceeds, and transfers remaining cash to the user.
    /// 
    /// # Arguments
    /// 
    /// * `args.collateral_reduce_by` - Amount of collateral tokens to withdraw and sell
    /// * `args.debt_reduce_by` - Amount of debt to repay from sale proceeds (can be 0)
    /// * `args.min_cash_to_user` - Minimum cash to receive after repaying debt (slippage protection)
    /// 
    /// # Operation Flow
    /// 
    /// 1. Withdraw collateral from position
    /// 2. Sell withdrawn collateral to market
    /// 3. Repay debt from sale proceeds (if debt_reduce_by > 0)
    /// 4. Transfer remaining cash to user
    /// 
    /// # Slippage Protection
    /// 
    /// Transaction fails if:
    /// - Sale proceeds < debt_reduce_by + min_cash_to_user
    /// - Protects against unfavorable price movements
    /// 
    /// # Debt Repayment
    /// 
    /// - Debt repayment is optional (debt_reduce_by can be 0)
    /// - If repaying, permission checks ensure repay is allowed
    /// - Remaining sale proceeds go to user after repayment
    /// 
    /// # Use Cases
    /// 
    /// - Close leveraged position: withdraw all collateral, sell, repay all debt
    /// - Partial deleverage: reduce position and debt simultaneously
    /// - Take profit: withdraw and sell collateral, keep debt unchanged (debt_reduce_by = 0)
    pub fn withdraw_sell_and_repay(_ctx: Context<WithdrawSellAndRepayAccounts>, _args: WithdrawSellAndRepayArgs) -> Result<WithdrawSellAndRepayEvent> {
        panic!("not implemented")
    }

    /// Exercise option tokens to purchase market tokens at floor price.
    /// 
    /// Converts option tokens into market tokens by paying the floor price in main tokens.
    /// This allows option holders to acquire tokens at a fixed price regardless of current
    /// market price.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Number of option tokens to exercise
    /// 
    /// # Economics
    /// 
    /// For each option token:
    /// - Pay: 1 unit of main token × floor price
    /// - Receive: 1 market token
    /// - Burn: 1 option token
    /// 
    /// # Profitability
    /// 
    /// Profitable when: Current Price > Floor Price + Exercise Fee
    /// - Check current bonding curve price
    /// - Account for exercise fees
    /// - Consider immediate sell vs holding
    /// 
    /// # Requirements
    /// 
    /// - Sufficient option token balance
    /// - Sufficient main tokens for payment
    /// - Market must allow option exercise
    pub fn exercise_options(_ctx: Context<ExerciseOptionsAccounts>, _amount: u64) -> Result<ExerciseOptionsEvent> {
        panic!("not implemented")
    }

    /// Redeem market tokens at the guaranteed floor price.
    /// 
    /// Allows token holders to exit at the floor price when market price is at or near
    /// the floor. This provides downside protection and ensures minimum redemption value.
    /// 
    /// # Arguments
    /// 
    /// * `amount_tokens_in` - Number of market tokens to redeem
    /// 
    /// # Redemption Limits
    /// 
    /// Maximum redeemable = Tail Width = (tail_start - shoulder_end)
    /// - Protects bonding curve integrity
    /// - Ensures sufficient liquidity for all holders
    /// - Resets as tokens are bought back
    /// 
    /// # Price Guarantee
    /// 
    /// Receives: Floor Price × Tokens - Fees
    /// - Always redeems at floor regardless of curve position
    /// - Sell fees still apply (platform + group)
    /// - Net proceeds = floor_price × tokens × (1 - total_fee_rate)
    /// 
    /// # Use Cases
    /// 
    /// - Exit strategy during market downturns
    /// - Arbitrage when market price < floor
    /// - Risk management for large positions
    pub fn redeem_at_floor(_ctx: Context<RedeemAtFloorAccounts>, _amount_tokens_in: u64) -> Result<RedeemAtFloorEvent> {
        panic!("not implemented")
    }

    /// Initialize a multi-curve market with Dutch auction configuration.
    /// 
    /// Creates a market using a multi-segment bonding curve that provides more flexibility
    /// than linear markets. Supports variable-length price curves with multiple segments,
    /// each with its own slope. Includes Dutch auction for initial price discovery.
    /// 
    /// # Arguments
    /// 
    /// * `args` - Configuration including:
    /// - `floor`: Base price per token
    /// - `target`: Maximum price per token
    /// - `shoulder_start` / `shoulder_end`: Range for initial linear segment
    /// - `tail_start`: Beginning of constant max price segment
    /// - `middle_segments`: Array of intermediate curve segments
    /// - Dutch auction parameters (multiplier, duration, start time)
    /// 
    /// # Multi-Curve Advantages
    /// 
    /// - Flexible price discovery through custom segments
    /// - Better modeling of complex tokenomics
    /// - Smooth transitions between price regions
    /// - Support for non-linear growth patterns
    /// 
    /// # Segment Structure
    /// 
    /// 1. Floor: Constant price from 0 to shoulder_start
    /// 2. First shoulder: Linear from shoulder_start to first middle segment
    /// 3. Middle segments: Variable slopes and ranges (can be empty)
    /// 4. Final shoulder: From last middle segment to shoulder_end
    /// 5. Tail: Constant max price from tail_start onward
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can create new markets.
    pub fn multi_market_init_with_dutch(_ctx: Context<MultiMarketInitWithDutchAccounts>, _args: MultiMarketInitWithDutchArgs) -> Result<()> {
        panic!("not implemented")
    }

    /// Raise floor price for multi-curve markets with validation.
    /// 
    /// Increases the minimum token price while preserving the total area under the
    /// multi-segment curve. More complex than linear markets due to multiple segments
    /// requiring coordinated adjustment.
    /// 
    /// # Arguments
    /// 
    /// * `args` - Parameters including:
    /// - `new_floor`: Target floor price
    /// - `new_shoulder_end`: Adjusted endpoint for price curve
    /// - `new_middle_segments`: Recalculated intermediate segments
    /// - `max_deviation_bps`: Tolerance for area preservation
    /// 
    /// # Segment Adjustment
    /// 
    /// When floor rises:
    /// 1. All segments shift up by floor delta
    /// 2. Slopes adjust to maintain total area
    /// 3. Segment boundaries may compress
    /// 4. Continuity preserved at all transitions
    /// 
    /// # Validation Checks
    /// 
    /// - Area preservation within tolerance
    /// - Sufficient backing liquidity
    /// - Valid segment progression (monotonic)
    /// - No instant arbitrage opportunities
    /// 
    /// # Complexity Note
    /// 
    /// Multi-curve floor raising requires careful calculation to maintain curve
    /// properties across all segments while preserving economic invariants.
    pub fn raise_floor_preserve_area_checked_multi(_ctx: Context<RaiseFloorPreserveAreaCheckedMultiAccounts>, _args: RaiseFloorPreserveAreaCheckedMultiArgs) -> Result<RaiseFloorPreserveAreaCheckedEvent> {
        panic!("not implemented")
    }

    /// Buy from multi-curve market and deposit as collateral.
    /// 
    /// Purchases tokens from a multi-segment bonding curve and immediately deposits them
    /// into a personal position. Combines acquisition and collateralization in one step.
    /// 
    /// # Arguments
    /// 
    /// * `cash_in` - Exact amount of main tokens to spend
    /// * `min_token_out` - Minimum tokens to receive (slippage protection)
    /// 
    /// # Multi-Curve Pricing
    /// 
    /// Price depends on current supply position:
    /// - Traverses multiple segments with different slopes
    /// - Large buys may span several segments
    /// - Each segment calculated independently
    /// - Dutch boost applies if active
    /// 
    /// # Atomic Benefits
    /// 
    /// - Single transaction for buy + deposit
    /// - Reduces transaction costs
    /// - Prevents front-running between operations
    /// - Immediate collateral availability
    /// 
    /// # Requirements
    /// 
    /// - Personal position must exist
    /// - Market must allow buying and deposits
    /// - Sufficient main token balance
    pub fn buy_with_exact_cash_in_and_deposit_multi(_ctx: Context<BuyWithExactCashInAndDepositMultiAccounts>, _cash_in: u64, _min_token_out: u64) -> Result<BuyWithExactCashInAndDepositEvent> {
        panic!("not implemented")
    }

    /// Buy tokens from a multi-curve market.
    /// 
    /// Purchases market tokens using a multi-segment bonding curve that can model
    /// complex price dynamics. Supports large purchases that span multiple curve
    /// segments with different characteristics.
    /// 
    /// # Arguments
    /// 
    /// * `cash_in` - Exact amount of main tokens to spend
    /// * `min_token_out` - Minimum tokens required (reverts if not met)
    /// 
    /// # Execution Across Segments
    /// 
    /// Large purchases may traverse multiple segments:
    /// 1. Start at current supply position
    /// 2. Buy at current segment's price/slope
    /// 3. If segment exhausted, continue to next
    /// 4. Accumulate tokens from each segment
    /// 5. Stop when cash exhausted or curve end reached
    /// 
    /// # Price Impact
    /// 
    /// - Each segment may have different price sensitivity
    /// - Steeper slopes mean higher price impact
    /// - Consider breaking very large orders
    /// 
    /// # Fees
    /// 
    /// Standard fee structure applies:
    /// - Platform fee to tenant
    /// - Group fee to market admin
    /// - Deducted from input amount
    pub fn buy_with_exact_cash_in_multi(_ctx: Context<BuyWithExactCashInMultiAccounts>, _cash_in: u64, _min_token_out: u64) -> Result<BuyEvent> {
        panic!("not implemented")
    }

    /// Sell tokens to a multi-curve market.
    /// 
    /// Sells market tokens back to the protocol following the multi-segment bonding curve
    /// in reverse. Large sales may span multiple segments with varying price impacts.
    /// 
    /// # Arguments
    /// 
    /// * `amount_in` - Exact number of tokens to sell
    /// * `cash_out_min` - Minimum main tokens to receive
    /// 
    /// # Multi-Segment Execution
    /// 
    /// Sells work backwards through curve:
    /// 1. Start at current supply position
    /// 2. Sell into current segment at its price
    /// 3. If more to sell, move to previous segment
    /// 4. Continue until all tokens sold
    /// 5. Cannot sell below floor price
    /// 
    /// # Price Discovery
    /// 
    /// - Higher supplies sell first (higher prices)
    /// - Price decreases as supply reduces
    /// - Each segment has independent characteristics
    /// - Floor provides absolute minimum
    /// 
    /// # Slippage Considerations
    /// 
    /// Multi-curve markets may have:
    /// - Variable liquidity across segments
    /// - Sudden price changes at boundaries
    /// - Different impacts in different regions
    pub fn sell_with_exact_token_in_multi(_ctx: Context<SellWithExactTokenInMultiAccounts>, _amount_in: u64, _cash_out_min: u64) -> Result<SellWithExactTokenInEvent> {
        panic!("not implemented")
    }

    /// Exercise options in a multi-curve market.
    /// 
    /// Converts option tokens to market tokens at the floor price, regardless of the
    /// current position on the multi-segment curve. Options provide downside protection
    /// in volatile multi-curve markets.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Number of option tokens to exercise
    /// 
    /// # Exercise Mechanics
    /// 
    /// Same as linear markets:
    /// - Pay floor price per option in main tokens
    /// - Receive one market token per option
    /// - Options are burned
    /// 
    /// # Multi-Curve Considerations
    /// 
    /// - Floor price is constant across all segments
    /// - Current curve position doesn't affect exercise
    /// - Especially valuable when price is in higher segments
    /// - Provides arbitrage during market dislocations
    /// 
    /// # Strategic Use
    /// 
    /// In multi-curve markets, options help:
    /// - Navigate complex price dynamics
    /// - Profit from segment transitions
    /// - Hedge against curve adjustments
    pub fn exercise_options_multi(_ctx: Context<ExerciseOptionsMultiAccounts>, _amount: u64) -> Result<ExerciseOptionsEvent> {
        panic!("not implemented")
    }

    /// Repay debt in a multi-curve market.
    /// 
    /// Repays borrowed main tokens to reduce debt obligations in a personal position.
    /// Multi-curve markets may have different interest dynamics based on utilization
    /// across curve segments.
    /// 
    /// # Arguments
    /// 
    /// * `amount` - Amount of main tokens to repay
    /// 
    /// # Interest Considerations
    /// 
    /// Multi-curve markets may feature:
    /// - Variable rates based on curve position
    /// - Different risk profiles across segments
    /// - Dynamic rate adjustments
    /// 
    /// # Repayment Priority
    /// 
    /// Same as linear markets:
    /// 1. Accrued interest first
    /// 2. Principal balance second
    /// 3. Excess returned to payer
    /// 
    /// # Position Management
    /// 
    /// Regular repayments recommended to:
    /// - Maintain healthy LTV ratios
    /// - Reduce liquidation risk
    /// - Take advantage of rate changes
    pub fn repay_multi(_ctx: Context<RepayMultiAccounts>, _amount: u64) -> Result<RepayEvent> {
        panic!("not implemented")
    }

    /// Redeem tokens at floor price in multi-curve market.
    /// 
    /// Provides guaranteed exit at the floor price for multi-curve market tokens.
    /// Essential safety mechanism given the complexity of multi-segment pricing.
    /// 
    /// # Arguments
    /// 
    /// * `amount_tokens_in` - Number of tokens to redeem at floor
    /// 
    /// # Redemption in Complex Markets
    /// 
    /// Multi-curve considerations:
    /// - Floor constant across all segments
    /// - Redemption bypasses curve complexity
    /// - Same tail width limits apply
    /// - Critical during segment transitions
    /// 
    /// # Maximum Redemption
    /// 
    /// Limited to tail width: (tail_start - shoulder_end)
    /// - Protects curve integrity
    /// - Ensures fair access for all holders
    /// - Resets as market activity continues
    /// 
    /// # Use Cases
    /// 
    /// Especially important in multi-curve markets for:
    /// - Exiting during curve adjustments
    /// - Arbitrage across segments
    /// - Risk management in complex dynamics
    /// - Guaranteed liquidity provision
    pub fn redeem_at_floor_multi(_ctx: Context<RedeemAtFloorMultiAccounts>, _amount_tokens_in: u64) -> Result<RedeemAtFloorEvent> {
        panic!("not implemented")
    }

    /// Modify the price curve's sensitivity to supply changes at the current token supply level.
    /// 
    /// Allows market administrators to dynamically adjust how quickly the token price changes
    /// in response to supply increases. The modification is applied at the current token supply
    /// level and affects the curve's behavior for all future supply levels beyond that point.
    /// 
    /// # Arguments
    /// 
    /// * `args` - Curve modification parameters including:
    /// - `multiplier`: Magnitude of slope change (0.0 < multiplier < 1.0)
    /// - `new_middle_segment_count`: Expected number of middle segments after modification
    /// - `increase`: Whether to increase (true) or decrease (false) sensitivity
    /// 
    /// # How it works
    /// 
    /// The function modifies the curve's vertex structure by either:
    /// - **Inserting a new vertex** at the current supply level if it falls within the final segment
    /// - **Removing the last vertex** if the current supply is not in the final segment and the
    /// sensitivity direction doesn't match the final segment's current direction
    /// 
    /// # Sensitivity Direction
    /// 
    /// - **`increase = true`** (`SensitivityDirection::Higher`): Makes the curve more sensitive to supply changes
    /// - Results in steeper slopes = faster price increases as supply grows
    /// - Useful for encouraging early adoption or responding to high demand
    /// 
    /// - **`increase = false`** (`SensitivityDirection::Lower`): Makes the curve less sensitive to supply changes
    /// - Results in gentler slopes = slower price increases as supply grows
    /// - Useful for risk management or stabilizing prices in volatile conditions
    /// 
    /// # Multiplier Effect
    /// 
    /// The `multiplier` parameter (0.0 < multiplier < 1.0) determines the magnitude of change:
    /// - For `Higher` direction: new_slope = current_slope × (1 + multiplier)
    /// - For `Lower` direction: new_slope = current_slope × (1 - multiplier)
    /// 
    /// # Access Control
    /// 
    /// Only the market group admin can modify curves.
    /// 
    /// # Use Cases
    /// 
    /// - **Market Making**: Adjust sensitivity based on trading volume or market volatility
    /// - **Risk Management**: Reduce sensitivity in high-supply regions to prevent extreme price swings
    /// - **Liquidity Provision**: Increase sensitivity in low-supply regions to encourage early adoption
    /// - **Dynamic Pricing**: Respond to market conditions by modifying curve behavior
    /// 
    /// # Constraints
    /// 
    /// - `multiplier` must be between 0.0 and 1.0 (exclusive)
    /// - The function preserves curve continuity at segment boundaries
    /// - Modifications only affect the curve beyond the current supply level
    /// - The account must be reallocated to accommodate the new segment count
    /// 
    /// # Safety Considerations
    /// 
    /// - Changes are irreversible once applied
    /// - The operation will panic if the actual number of middle segments after modification
    /// doesn't match the expected `new_middle_segment_count`
    /// - Consider market impact before significant changes
    /// - Monitor market behavior after curve changes
    pub fn modify_curve_multi(_ctx: Context<ModifyCurveMultiAccounts>, _args: ModifyCurveArgs) -> Result<()> {
        panic!("not implemented")
    }

}

// Instruction account structures
#[derive(Accounts)]
pub struct VersionAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
}

#[derive(Accounts)]
pub struct InitLogAccountAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub system_program: AccountInfo<'info>,
}

#[derive(Accounts)]
pub struct ReceiveLogAccounts<'info> {
    #[account(mut, signer)]
    pub log_account: AccountInfo<'info>,
}

#[derive(Accounts)]
pub struct TestLogAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub self_program: AccountInfo<'info>,
}

/// Initialize a platform tenant.
/// 
/// Tenants are the top-level organizational units in the protocol. Each tenant can have
/// multiple market groups, and receives a portion of all fees generated by markets under
/// their umbrella.
/// 
/// # Arguments
/// 
/// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
/// This fee is taken from all market operations and distributed to the tenant.
/// * `permissionless_group_creation` - If true, anyone can create market groups under this
/// tenant. If false, only the tenant admin can create new groups.
/// 
/// # Access Control
/// 
/// This instruction can only be called by the program itself (root authority).
#[derive(Accounts)]
pub struct TenantInitAccounts<'info> {
    /// Account paying for the tenant account creation.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Root authority (the program itself) authorizing tenant creation.
    #[account(signer)]
    pub root: AccountInfo<'info>,
    /// Seed signer used to derive the tenant's PDA address.
    #[account(signer)]
    pub tenant_seed: AccountInfo<'info>,
    /// The new tenant account being initialized.
    #[account(mut)]
    pub tenant: AccountInfo<'info>,
    /// System program for creating the tenant account.
    pub system_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Initialize a platform tenant with an admin.
/// 
/// This instruction is similar to `tenant_init` but allows specifying an admin
/// account that will have full control over the tenant.
/// 
/// # Arguments
/// 
/// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
/// This fee is taken from all market operations and distributed to the tenant.
/// * `permissionless_group_creation` - If true, anyone can create market groups under this
/// tenant. If false, only the tenant admin can create new groups.
/// * `admin` - Public key of the admin account that will have full control over the tenant.
#[derive(Accounts)]
pub struct TenantInitWithAdminAccounts<'info> {
    /// Account paying for the tenant account creation.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Root authority (the program itself) authorizing tenant creation.
    #[account(signer)]
    pub root: AccountInfo<'info>,
    /// Seed signer used to derive the tenant's PDA address.
    #[account(signer)]
    pub tenant_seed: AccountInfo<'info>,
    /// The new tenant account being initialized.
    #[account(mut)]
    pub tenant: AccountInfo<'info>,
    /// System program for creating the tenant account.
    pub system_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Propose a new admin for the tenant.
/// 
/// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
/// who must then accept the role using `tenant_accept_new_admin`.
#[derive(Accounts)]
pub struct TenantProposeAdminAccounts<'info> {
    /// Current tenant admin proposing the transfer.
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    /// Tenant account for which a new admin is being proposed.
    #[account(mut)]
    pub tenant: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Accept admin ownership of a tenant.
/// 
/// Completes the two-step ownership transfer process. The proposed admin calls this
/// instruction to accept control of the tenant.
#[derive(Accounts)]
pub struct TenantAcceptNewAdminAccounts<'info> {
    /// The proposed admin accepting ownership of the tenant.
    #[account(mut, signer)]
    pub new_admin: AccountInfo<'info>,
    /// Tenant account whose ownership is being transferred.
    #[account(mut)]
    pub tenant: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Change the fee rate for a tenant.
/// 
/// Updates the platform fee rate applied to all market operations under this tenant.
#[derive(Accounts)]
pub struct TenantChangeFeeMbpsAccounts<'info> {
    /// Payer of the fee.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Root authority (the program itself) authorized to change the fee
    #[account(signer)]
    pub root: AccountInfo<'info>,
    /// Tenant account whose platform fee is being updated.
    #[account(mut)]
    pub tenant: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Initialize a market group under a tenant.
/// 
/// Market groups are collections of markets that share the same fee structure and admin.
/// Each group can contain multiple markets with different token pairs and price curves.
/// The group admin has control over all markets within the group and collects trading fees.
/// 
/// # Arguments
/// 
/// * `args` - Initialization arguments containing:
/// - `fees`: Fee structure for buy, sell, borrow, and exercise operations
/// - `group_admin`: Public key that will administer this market group
/// 
/// # Access Control
/// 
/// If the tenant has `permissionless_group_creation` disabled, only the tenant admin
/// can create new market groups.
#[derive(Accounts)]
pub struct MarketGroupInitAccounts<'info> {
    /// Account paying for the market group account creation.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Tenant account that will own this market group.
    pub tenant: AccountInfo<'info>,
    /// Optional account, which only needs to match if the tenant does not allow permissionless group creation
    /// Must be the tenant admin if permissionless creation is disabled.
    #[account(signer)]
    pub tenant_admin: AccountInfo<'info>,
    /// Seed signer used to derive the market group's PDA address.
    #[account(signer)]
    pub seed: AccountInfo<'info>,
    /// The new market group account being initialized.
    #[account(mut)]
    pub market_group: AccountInfo<'info>,
    /// System program for creating the market group account.
    pub system_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Propose a new admin for the market group.
/// 
/// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
/// who must then accept the role using `market_group_accept_new_admin`.
/// 
/// # Arguments
/// 
/// * `new_admin` - Public key of the proposed new admin
/// 
/// # Access Control
/// 
/// Only the current market group admin can propose a new admin.
/// 
/// # Security
/// 
/// Two-step transfer prevents accidental loss of admin control by requiring the new admin
/// to explicitly accept the role.
#[derive(Accounts)]
pub struct MarketGroupProposeAdminAccounts<'info> {
    /// Current market group admin proposing the transfer.
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    /// Market group account for which a new admin is being proposed.
    #[account(mut)]
    pub market_group: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Accept admin ownership of a market group.
/// 
/// Completes the two-step ownership transfer process. The proposed admin calls this
/// instruction to accept control of the market group.
/// 
/// # Access Control
/// 
/// Only the proposed new admin can accept ownership.
/// 
/// # Effects
/// 
/// - Transfers full admin control to the new admin
/// - Clears the proposed admin field
/// - The new admin gains ability to:
/// - Create new markets in the group
/// - Change group fees
/// - Collect accumulated revenue
/// - Modify market permissions
#[derive(Accounts)]
pub struct MarketGroupAcceptNewAdminAccounts<'info> {
    /// The proposed admin accepting ownership of the market group.
    #[account(mut, signer)]
    pub new_admin: AccountInfo<'info>,
    /// Market group account whose ownership is being transferred.
    #[account(mut)]
    pub market_group: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Initialize a linear market with a simple price curve.
/// 
/// Creates a new market with a linear bonding curve that determines token prices based on
/// supply. The curve has three segments: floor (constant price), shoulder (linear increase),
/// and tail (constant max price).
/// 
/// # Arguments
/// 
/// * `market_linear_args` - Configuration parameters including:
/// - `floor`: Minimum price per token (floor price)
/// - `target`: Target price where the shoulder segment ends
/// - `slope_numerator` / `slope_denominator`: Rate of price increase in shoulder segment
/// - `shoulder_start` / `shoulder_end`: Token supply range for linear price growth
/// - `tail_start`: Token supply where max price is reached
/// - `permissions`: Trading restrictions and feature flags
/// 
/// # Access Control
/// 
/// Only the market group admin can create new markets.
/// 
/// # Created Accounts
/// 
/// - Market account storing price curve and state
/// - Token mint for the market's synthetic token
/// - Option token mint for exercisable options
/// - Liquidity vault holding backing collateral
/// - Revenue escrow accounts for fee collection
#[derive(Accounts)]
pub struct MarketLinearInitAccounts<'info> {
    /// Account paying for the creation of new accounts and transaction fees.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Market group admin authorizing the creation of this new market.
    #[account(mut, signer)]
    pub group_admin: AccountInfo<'info>,
    /// Seed signer used to derive the market_meta PDA address.
    #[account(signer)]
    pub seed: AccountInfo<'info>,
    /// Tenant account that owns the market group.
    pub tenant: AccountInfo<'info>,
    /// Market group account that will contain this market.
    /// Must be owned by the tenant and administered by group_admin.
    pub market_group: AccountInfo<'info>,
    /// Mint of the main token (e.g., USDC, SOL) used as the market's base currency.
    pub mint_main: AccountInfo<'info>,
    /// The token mint for this market's derivative token.
    /// This account must be created in a previous instruction
    /// With supply set to zero
    /// And mint authority assigned to the market_meta
    pub mint_token: AccountInfo<'info>,
    /// Mint for option tokens that can be exercised to purchase market tokens.
    #[account(mut)]
    pub mint_options: AccountInfo<'info>,
    /// Liquidity vault holding the main token reserves for this market.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow account for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow account for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// The linear market account storing price curve and state data.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Market metadata account storing configuration and token references.
    #[account(mut)]
    pub market_meta: AccountInfo<'info>,
    /// System program for creating new accounts.
    pub system_program: AccountInfo<'info>,
    /// Token program for the market's derivative token operations.
    pub token_program: AccountInfo<'info>,
    /// Token program interface for the main token operations.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Initialize a linear market with Dutch auction price boost.
/// 
/// Creates a linear market with an additional Dutch auction mechanism that provides
/// temporary price boosts. The boost decays over time from a maximum multiplier down
/// to 1x (no boost).
/// 
/// # Arguments
/// 
/// * `market_linear_init_with_dutch_args` - Configuration containing:
/// - All standard linear market parameters (floor, target, slopes, etc.)
/// - `dutch_numerator` / `dutch_denominator`: Maximum price boost multiplier
/// - `dutch_duration`: Time in seconds for boost to decay from max to 1x
/// - `dutch_start`: Unix timestamp when the Dutch auction begins
/// 
/// # Dutch Auction Mechanics
/// 
/// - Initial boost: price × (dutch_numerator / dutch_denominator)
/// - Linear decay over dutch_duration seconds
/// - After duration expires, boost remains at 1x (no effect)
/// - Useful for token launches to incentivize early buyers
/// 
/// # Access Control
/// 
/// Only the market group admin can create new markets.
#[derive(Accounts)]
pub struct MarketLinearInitWithDutchAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    #[account(mut, signer)]
    pub group_admin: AccountInfo<'info>,
    #[account(signer)]
    pub seed: AccountInfo<'info>,
    pub tenant: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub mint_main: AccountInfo<'info>,
    /// The token account for the market
    /// This account must be created in a previous instruction
    /// With supply set to zero
    /// And mint authority assigned to the market_meta
    pub mint_token: AccountInfo<'info>,
    #[account(mut)]
    pub mint_options: AccountInfo<'info>,
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub market_meta: AccountInfo<'info>,
    pub system_program: AccountInfo<'info>,
    pub token_program: AccountInfo<'info>,
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Mint option tokens by depositing market tokens.
/// 
/// Converts market tokens into option tokens at a 1:1 ratio. Option tokens represent
/// the right to purchase market tokens at the floor price by depositing the main
/// backing token (e.g., USDC).
/// 
/// # Arguments
/// 
/// * `amount` - Number of market tokens to convert into options
/// 
/// # Requirements
/// 
/// - User must have sufficient market token balance
/// - Market must allow option minting (check permissions)
/// 
/// # Use Cases
/// 
/// - Hedge against price increases by locking in floor price
/// - Create structured products with downside protection
/// - Enable secondary markets for price speculation
#[derive(Accounts)]
pub struct MintOptionsAccounts<'info> {
    /// Market group admin authorized to mint options.
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    /// Market metadata linking to the options mint.
    pub market_meta: AccountInfo<'info>,
    /// Market group that must be administered by the signer.
    pub market_group: AccountInfo<'info>,
    /// Mint for option tokens to be created.
    #[account(mut)]
    pub mint_options: AccountInfo<'info>,
    /// Destination token account to receive minted options.
    #[account(mut)]
    pub options_dst: AccountInfo<'info>,
    /// Token program for minting option tokens.
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Collect accumulated trading fees from a market group.
/// 
/// Transfers fee revenue from the group's escrow account to the admin's wallet.
/// Fees accumulate from all trading operations (buy, sell, borrow, exercise) across
/// all markets in the group.
/// 
/// # Arguments
/// 
/// * `amount` - Amount to collect:
/// - `FullOrPartialU64::Full`: Collect entire escrow balance
/// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
/// 
/// # Access Control
/// 
/// Only the market group admin can collect revenue.
/// 
/// # Fee Distribution
/// 
/// Trading fees are split between:
/// - Tenant: Platform-level fee (set during tenant creation)
/// - Market Group: Admin fee (set during group creation)
/// 
/// This instruction collects only the group's portion.
#[derive(Accounts)]
pub struct MarketGroupCollectRevAccounts<'info> {
    /// Market group admin authorized to collect revenue.
    #[account(mut, signer)]
    pub group_admin: AccountInfo<'info>,
    /// Market group that has accumulated revenue.
    pub market_group: AccountInfo<'info>,
    /// Market metadata linking to the revenue escrow account.
    pub market_meta: AccountInfo<'info>,
    /// Mint of the main token for revenue collection.
    pub mint_main: AccountInfo<'info>,
    /// Revenue escrow account holding accumulated fees for the market group.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Destination token account to receive collected revenue.
    #[account(mut)]
    pub rev_dst: AccountInfo<'info>,
    /// Token program for transferring the revenue.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Collect accumulated platform fees from a tenant.
/// 
/// Transfers platform fee revenue from the tenant's escrow account to the admin's wallet.
/// Platform fees accumulate from all trading operations (buy, sell, borrow, exercise) across
/// all markets under this tenant.
/// 
/// # Arguments
/// 
/// * `amount` - Amount to collect:
/// - `FullOrPartialU64::Full`: Collect entire escrow balance
/// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
/// 
/// # Access Control
/// 
/// Only the tenant admin can collect platform revenue.
/// 
/// # Fee Distribution
/// 
/// Trading fees are split between:
/// - Tenant: Platform-level fee (set during tenant creation)
/// - Market Group: Admin fee (set during group creation)
/// 
/// This instruction collects only the tenant's platform fee portion.
#[derive(Accounts)]
pub struct TenantCollectRevAccounts<'info> {
    /// Root authority (the program itself) authorized to collect platform revenue.
    #[account(mut, signer)]
    pub root: AccountInfo<'info>,
    /// Market metadata linking to the revenue escrow account.
    pub market_meta: AccountInfo<'info>,
    /// Mint of the main token for revenue collection.
    pub mint_main: AccountInfo<'info>,
    /// Revenue escrow account holding accumulated platform fees for the tenant.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Destination token account to receive collected platform revenue.
    #[account(mut)]
    pub rev_dst: AccountInfo<'info>,
    /// Token program for transferring the revenue.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
/// 
/// Raise the market floor price while preserving bonding curve area.
/// 
/// Increases the minimum (floor) price of the market token while maintaining the
/// total area under the price curve. This ensures the market's total value capacity
/// remains constant while providing price support.
/// 
/// # Arguments
/// 
/// * `new_floor` - New minimum price per token (must be higher than current)
/// * `new_shoulder_end` - New token supply where shoulder segment ends
/// 
/// # Curve Adjustment
/// 
/// When the floor rises:
/// - Floor segment moves up to new price level
/// - Shoulder segment becomes steeper to preserve area
/// - Tail segment adjusts to maintain continuity
/// 
/// # Requirements
/// 
/// - Market must have excess liquidity to support higher floor
/// - New floor must be greater than current floor
/// - Curve area preservation must be mathematically valid
/// 
/// # Access Control
/// 
/// Can be triggered by authorized operators or through automated mechanisms.
#[derive(Accounts)]
pub struct RaiseFloorPreserveAreaAccounts<'info> {
    /// Market group admin authorized to adjust floor parameters.
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    /// Market group that must be administered by the signer.
    pub market_group: AccountInfo<'info>,
    /// Market metadata linking to the market group.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account whose floor price will be raised.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
/// 
/// Raise the floor price with additional validation checks.
/// 
/// Similar to `raise_floor_preserve_area` but includes extra safety checks to ensure
/// the operation maintains market integrity. Validates curve parameters and liquidity
/// requirements before applying changes.
/// 
/// # Arguments
/// 
/// * `args` - Parameters including:
/// - `new_floor`: Target floor price
/// - `new_shoulder_end`: Adjusted shoulder endpoint
/// - `max_deviation_bps`: Maximum allowed deviation in basis points
/// 
/// # Additional Checks
/// 
/// - Verifies sufficient backing liquidity exists
/// - Ensures curve area preservation within tolerance
/// - Validates no tokens would be instantly profitable to redeem
/// - Checks market state consistency after adjustment
/// 
/// # Use Cases
/// 
/// - Automated floor raising based on market conditions
/// - Protocol-driven price support mechanisms
/// - Treasury management operations
#[derive(Accounts)]
pub struct RaiseFloorPreserveAreaCheckedAccounts<'info> {
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Raise the floor and preserve the area of the market
/// This instruction takes in constraints
/// * `new_floor` - The new floor price (must be greater than the current floor)
/// * `new_shoulder_end` - The new shoulder end (must be greater than the current shoulder end)
/// * `min_liq_ratio` - The minimum liquidity ratio (greater than or equal to 0.0)
/// * `max_area_shrinkage_tolerance_units` - The maximum token units that the total area of the curve is allowed to shrink by
/// This is set by the client to restrict overly aggressive floor raising, with a tolerance to account for "slippage"
/// 
/// # Access Control
/// Only the market group admin can raise the floor price.
#[derive(Accounts)]
pub struct RaiseFloorPreserveAreaChecked2Accounts<'info> {
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// DEPRECATED: use raise_floor_from_excess_liquidity2 instead, as it is more secure
/// 
/// Raise the floor price using excess market liquidity.
/// 
/// Automatically increases the floor price when the market has accumulated excess
/// backing liquidity beyond what's needed for the current token supply. This provides
/// organic price appreciation based on market performance.
/// 
/// # Arguments
/// 
/// * `floor_increase_ratio` - Percentage increase for the floor price (as decimal)
/// - 0.1 = 10% increase
/// - 0.05 = 5% increase
/// - Must be positive and reasonable (typically < 0.5)
/// 
/// # Mechanism
/// 
/// 1. Calculates available excess liquidity (cash above backing requirements)
/// 2. Determines maximum sustainable floor increase
/// 3. Applies requested ratio (capped by available excess)
/// 4. Adjusts curve parameters to preserve total area
/// 
/// # Requirements
/// 
/// - Market must have excess liquidity
/// - Floor increase must be sustainable given current token supply
/// - Market permissions must allow floor raising
/// 
/// # Benefits
/// 
/// - Rewards token holders when market performs well
/// - Creates deflationary pressure through higher floor
/// - Maintains full backing at new price levels
#[derive(Accounts)]
pub struct RaiseFloorFromExcessLiquidityAccounts<'info> {
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Raise the floor price using excess market liquidity.
/// 
/// Automatically increases the floor price when the market has accumulated excess
/// backing liquidity beyond what's needed for the current token supply. This provides
/// organic price appreciation based on market performance.
/// 
/// # Arguments
/// 
/// * `args` - Parameters including:
/// - `max_new_floor`: The maximum new floor that is allowed
/// - `increase_ratio_micro_basis_points`: The amount to increase the floor by, in micro basis points
/// 
/// # Access Control
/// 
/// Only the market group admin can raise the floor price.
/// 
/// # Use Cases
/// - Automated floor raising based on market conditions
/// - Protocol-driven price support mechanisms
/// - Treasury management operations
#[derive(Accounts)]
pub struct RaiseFloorFromExcessLiquidityCheckedAccounts<'info> {
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Update market permissions and feature flags.
/// 
/// Controls which operations are allowed on a market. Can be used to pause trading,
/// disable specific features, or adjust market behavior.
/// 
/// # Arguments
/// 
/// * `new_flags` - New permission set including:
/// - `can_buy`: Allow token purchases
/// - `can_sell`: Allow token sales
/// - `can_borrow`: Allow borrowing against collateral
/// - `can_add_liquidity`: Allow liquidity donations
/// - `can_remove_liquidity`: Allow liquidity removal
/// - `can_open_position`: Allow new position creation
/// - `can_close_position`: Allow position closure
/// - `can_change_fees`: Allow fee adjustments
/// 
/// # Access Control
/// 
/// Only the market group admin can change market flags.
/// 
/// # Use Cases
/// 
/// - Emergency pause during security incidents
/// - Gradual feature rollout
/// - Market maintenance windows
/// - Compliance-driven restrictions
#[derive(Accounts)]
pub struct MarketFlagsChangeAccounts<'info> {
    /// Market group admin authorized to change market permissions.
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    /// Market group that must be administered by the signer.
    pub market_group: AccountInfo<'info>,
    /// Market metadata whose permissions will be updated.
    #[account(mut)]
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Update fee structure for all markets in a group.
/// 
/// Changes the fee rates charged on trading operations. New fees apply to all future
/// transactions across all markets within the group.
/// 
/// # Arguments
/// 
/// * `new_fees` - Updated fee structure:
/// - `buy`: Fee on token purchases (micro basis points)
/// - `sell`: Fee on token sales (micro basis points)
/// - `borrow`: Fee on borrowing operations (micro basis points)
/// - `exercise`: Fee on option exercise (micro basis points)
/// 
/// # Fee Calculation
/// 
/// Fees are specified in micro basis points where:
/// - 1 micro bp = 1/100 of a basis point = 0.0001%
/// - 100 micro bps = 1 basis point = 0.01%
/// - 10,000 micro bps = 100 basis points = 1%
/// - Example: 50 micro bps = 0.5 basis points = 0.005% fee
/// 
/// # Access Control
/// 
/// Only the market group admin can change fees.
/// 
/// # Considerations
/// 
/// - Changes affect all markets in the group immediately
/// - Cannot exceed maximum fee limits set by protocol
/// - Platform (tenant) fees are added on top of group fees
#[derive(Accounts)]
pub struct MarketGroupChangeFeesAccounts<'info> {
    /// Market group admin authorized to change fees.
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    /// Market group account whose fees will be updated.
    #[account(mut)]
    pub market_group: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Initialize a personal position account for market interaction.
/// 
/// Creates a user-specific account that tracks collateral deposits and debt obligations
/// for a particular market. Required before performing borrow operations or using
/// collateral-based features.
/// 
/// # Position Features
/// 
/// Personal positions enable:
/// - Collateral deposits (market tokens as collateral)
/// - Borrowing against collateral (up to LTV limits)
/// - Tracking debt obligations and interest
/// - Liquidation protection through collateralization
/// 
/// # Account Structure
/// 
/// - Unique per user per market
/// - Stores collateral and debt balances
/// - Tracks last update timestamp for interest
/// - Immutable market and owner references
/// 
/// # One-Time Setup
/// 
/// Each user needs only one position per market. Attempting to create a duplicate
/// will fail. The position persists until explicitly closed.
#[derive(Accounts)]
pub struct PersonalPositionInitAccounts<'info> {
    /// Account paying for the personal position and escrow account creation.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// The owner who will control the personal position.
    pub owner: AccountInfo<'info>,
    /// Market metadata identifying which market this position belongs to.
    pub market_meta: AccountInfo<'info>,
    /// Mint for the market tokens that can be deposited as collateral.
    pub mint_token: AccountInfo<'info>,
    /// The new personal position account being initialized.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Escrow token account for holding collateral tokens.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Token program for creating the escrow account.
    pub token_program: AccountInfo<'info>,
    /// System program for creating new accounts.
    pub system_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// DEPRECATED: use donate_liquidity2 instead, as v2 gets logged by the indexer
/// 
/// Donate backing liquidity to the market.
/// 
/// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
/// market tokens in return. This creates excess liquidity that can be used to raise
/// the floor price or improve market stability.
/// 
/// # Arguments
/// 
/// * `amount` - Amount of main tokens to donate
/// 
/// # Effects
/// 
/// - Increases market's cash balance
/// - Creates excess liquidity (cash > backing requirements)
/// - Enables floor price increases
/// - Benefits all token holders through improved backing
/// 
/// # Use Cases
/// 
/// - Protocol treasury supporting market stability
/// - Community-funded price support
/// - Grants or subsidies to bootstrap markets
/// - Creating buffer for market operations
/// 
/// # Note
/// 
/// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
#[derive(Accounts)]
pub struct DonateLiquidityAccounts<'info> {
    /// Donor of the liquidity
    /// Account providing main tokens to boost market liquidity.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Market metadata with all market configuration and references.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account to update cash balance.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Source account containing main tokens to donate.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// The liquidity vault for the main token in the market
    /// Receives the donated tokens to increase market reserves.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Mint for the main token being donated.
    pub mint_main: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
}

/// Donate backing liquidity to the market.
/// 
/// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
/// market tokens in return. This creates excess liquidity that can be used to raise
/// the floor price or improve market stability.
/// 
/// # Arguments
/// 
/// * `amount` - Amount of main tokens to donate
/// 
/// # Effects
/// 
/// - Increases market's cash balance
/// - Creates excess liquidity (cash > backing requirements)
/// - Enables floor price increases
/// - Benefits all token holders through improved backing
/// 
/// # Use Cases
/// 
/// - Protocol treasury supporting market stability
/// - Community-funded price support
/// - Grants or subsidies to bootstrap markets
/// - Creating buffer for market operations
/// 
/// # Note
/// 
/// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
#[derive(Accounts)]
pub struct DonateLiquidity2Accounts<'info> {
    /// Donor of the liquidity
    /// Account providing main tokens to boost market liquidity.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Market metadata with all market configuration and references.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account to update cash balance.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Source account containing main tokens to donate.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// The liquidity vault for the main token in the market
    /// Receives the donated tokens to increase market reserves.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Mint for the main token being donated.
    pub mint_main: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Buy market tokens using exact amount of main tokens.
/// 
/// Purchases market tokens by depositing a specific amount of main tokens (e.g., USDC).
/// The number of tokens received depends on the current price curve position. Includes
/// slippage protection through minimum output requirement.
/// 
/// # Arguments
/// 
/// * `cash_in` - Exact amount of main tokens to spend
/// * `min_token_out` - Minimum market tokens to receive (reverts if not met)
/// 
/// # Price Calculation
/// 
/// Token price follows the bonding curve:
/// - Floor segment: Constant price at floor level
/// - Shoulder segment: Linear price increase
/// - Tail segment: Constant price at maximum
/// - Dutch boost: Temporary multiplier if active
/// 
/// # Fees
/// 
/// Buy fee is deducted from input amount:
/// - Platform fee (tenant level)
/// - Group fee (market group level)
/// - Net amount used for token purchase
/// 
/// # Slippage Protection
/// 
/// Transaction reverts if `tokens_received < min_token_out`
#[derive(Accounts)]
pub struct BuyWithExactCashInAccounts<'info> {
    /// The trader buying tokens from the market.
    #[account(mut, signer)]
    pub signer: AccountInfo<'info>,
    /// Tenant account for platform fee distribution.
    pub tenant: AccountInfo<'info>,
    /// Market group containing fee configuration.
    pub market_group: AccountInfo<'info>,
    /// Market metadata with all market configuration and references.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account containing price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Mint for the market's derivative token.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token used as payment.
    pub mint_main: AccountInfo<'info>,
    /// Destination token account to receive the purchased market tokens.
    #[account(mut)]
    pub token_dst: AccountInfo<'info>,
    /// Source account containing main tokens for payment.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// Market's liquidity vault receiving the main token payment.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Buy market tokens and immediately deposit as collateral.
/// 
/// Combines token purchase with collateral deposit in a single atomic transaction.
/// Useful for users who want to immediately use purchased tokens as collateral for
/// borrowing operations.
/// 
/// # Arguments
/// 
/// * `cash_in` - Exact amount of main tokens to spend
/// * `min_token_out` - Minimum market tokens to receive
/// 
/// # Transaction Flow
/// 
/// 1. Deduct fees from input amount
/// 2. Purchase tokens at current curve price
/// 3. Deposit all tokens into personal position
/// 4. Update position's collateral balance
/// 
/// # Requirements
/// 
/// - Personal position must exist (call `personal_position_init` first)
/// - Sufficient main token balance
/// - Market must allow buying and deposits
/// 
/// # Benefits
/// 
/// - Single transaction reduces costs
/// - Atomic operation prevents MEV
/// - Immediate collateral availability
#[derive(Accounts)]
pub struct BuyWithExactCashInAndDepositAccounts<'info> {
    /// The trader buying tokens and depositing them as collateral.
    #[account(mut, signer)]
    pub owner: AccountInfo<'info>,
    /// Tenant account for platform fee collection.
    pub tenant: AccountInfo<'info>,
    /// Market group that owns this market.
    pub market_group: AccountInfo<'info>,
    /// Market metadata containing configuration and linked accounts.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account with price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position that will receive the purchased tokens as collateral.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Escrow account that will receive the purchased tokens as collateral.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Mint for the market's derivative token being purchased.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token used as payment.
    pub mint_main: AccountInfo<'info>,
    /// Temporary destination for purchased tokens before deposit to escrow.
    #[account(mut)]
    pub token_dst: AccountInfo<'info>,
    /// Source account containing main tokens for payment.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// Liquidity vault receiving the main token payment.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Buy market tokens and immediately deposit as collateral with debt.
/// 
/// Combines token purchase with collateral deposit in a single atomic transaction.
/// Useful for users who want to immediately use purchased tokens as collateral for
/// borrowing operations.
/// 
/// # Arguments
/// 
/// * `args` - Arguments for the transaction
/// - `exact_cash_in` - Exact amount of cash to spend on tokens
/// - `min_token_received` - Minimum acceptable tokens to receive (slippage protection)
/// - `new_acquired_debt` - New debt amount to take on
#[derive(Accounts)]
pub struct BuyWithExactCashInAndDepositWithDebtAccounts<'info> {
    /// The trader buying tokens and depositing them as collateral.
    #[account(mut, signer)]
    pub owner: AccountInfo<'info>,
    /// Tenant account for platform fee collection.
    pub tenant: AccountInfo<'info>,
    /// Market group that owns this market.
    pub market_group: AccountInfo<'info>,
    /// Market metadata containing configuration and linked accounts.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account with price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position that will receive the purchased tokens as collateral.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Escrow account that will receive the purchased tokens as collateral.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Mint for the market's derivative token being purchased.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token used as payment.
    pub mint_main: AccountInfo<'info>,
    /// Source account containing main tokens for payment.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// Liquidity vault receiving the main token payment.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Sell exact amount of market tokens for main tokens.
/// 
/// Sells a specific number of market tokens and receives main tokens (e.g., USDC)
/// based on the current bonding curve price. Includes slippage protection through
/// minimum output requirement.
/// 
/// # Arguments
/// 
/// * `amount_in` - Exact number of market tokens to sell
/// * `cash_out_min` - Minimum main tokens to receive (reverts if not met)
/// 
/// # Price Calculation
/// 
/// Sell price follows bonding curve in reverse:
/// - Reduces token supply, moving down the curve
/// - Higher supplies sell at higher prices first
/// - Cannot sell below floor price
/// 
/// # Fees
/// 
/// Sell fee is deducted from output amount:
/// - Gross proceeds calculated from curve
/// - Platform and group fees deducted
/// - Net amount sent to seller
/// 
/// # Market Impact
/// 
/// Large sells may experience price slippage as they move down the curve.
/// Consider breaking into smaller transactions for better execution.
#[derive(Accounts)]
pub struct SellWithExactTokenInAccounts<'info> {
    /// The trader selling tokens back to the market.
    #[account(mut, signer)]
    pub user: AccountInfo<'info>,
    /// Tenant account for platform fee distribution.
    pub tenant: AccountInfo<'info>,
    /// Market group containing fee configuration.
    pub market_group: AccountInfo<'info>,
    /// Market metadata with all market configuration and references.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account containing price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Market's liquidity vault providing main tokens for the sale.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Mint for the market's derivative token being sold.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token received from the sale.
    pub mint_main: AccountInfo<'info>,
    /// Destination account to receive main tokens from the sale.
    #[account(mut)]
    pub main_dst: AccountInfo<'info>,
    /// Source account containing market tokens to sell.
    #[account(mut)]
    pub token_src: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Withdraw collateral and sell tokens in one transaction.
/// 
/// Atomically withdraws market tokens from a personal position and sells them for
/// main tokens. Useful for exiting collateralized positions or taking profits.
/// 
/// # Arguments
/// 
/// * `amount_in` - Number of tokens to withdraw and sell
/// * `cash_out_min` - Minimum main tokens to receive
/// 
/// # Transaction Flow
/// 
/// 1. Withdraw tokens from personal position
/// 2. Check position remains healthy (if debt exists)
/// 3. Sell tokens on bonding curve
/// 4. Transfer proceeds to user
/// 
/// # Position Health
/// 
/// If position has outstanding debt:
/// - Remaining collateral must maintain required LTV
/// - Transaction reverts if withdrawal would enable liquidation
/// - Consider repaying debt before large withdrawals
/// 
/// # Use Cases
/// 
/// - Taking profits while maintaining position
/// - Reducing exposure during market volatility
/// - Exiting positions efficiently
#[derive(Accounts)]
pub struct SellWithExactTokenInAfterWithdrawAccounts<'info> {
    /// Owner of the personal position withdrawing and selling tokens.
    #[account(mut, signer)]
    pub owner: AccountInfo<'info>,
    /// Tenant account for platform fee collection.
    pub tenant: AccountInfo<'info>,
    /// Market group that owns this market.
    pub market_group: AccountInfo<'info>,
    /// Market metadata containing configuration and linked accounts.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account with price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position from which collateral will be withdrawn.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Liquidity vault sending out main tokens from the sale.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Mint for the market tokens being sold.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token received from sale.
    pub mint_main: AccountInfo<'info>,
    /// Destination account to receive main tokens from sale.
    #[account(mut)]
    pub main_dst: AccountInfo<'info>,
    /// Source account for tokens (will be the escrow after withdrawal).
    #[account(mut)]
    pub token_src: AccountInfo<'info>,
    /// Escrow account from which tokens are withdrawn before selling.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Deposit market tokens as collateral into personal position.
/// 
/// Adds market tokens to your position's collateral balance, enabling borrowing
/// operations. Deposited tokens remain locked until withdrawn or liquidated.
/// 
/// # Arguments
/// 
/// * `amount` - Number of market tokens to deposit
/// 
/// # Collateral Benefits
/// 
/// - Enables borrowing main tokens up to LTV limit
/// - Earns potential appreciation if floor price rises
/// - Protects position from liquidation
/// - Can be withdrawn anytime (if position healthy)
/// 
/// # Requirements
/// 
/// - Personal position must exist
/// - Sufficient token balance in wallet
/// - Market must allow deposits
#[derive(Accounts)]
pub struct DepositAccounts<'info> {
    /// The depositor can be anyone
    /// They are depositing tokens into the personal position's escrow.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Market metadata identifying which market these tokens belong to.
    pub market_meta: AccountInfo<'info>,
    /// Mint for the market tokens being deposited.
    pub mint_token: AccountInfo<'info>,
    /// Linear market account to update collateral tracking.
    /// Constrained by market_meta
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position receiving the collateral deposit.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Escrow token account holding the position's collateral.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Source token account containing tokens to deposit.
    #[account(mut)]
    pub token_src: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Withdraw collateral from personal position.
/// 
/// Removes market tokens from collateral, returning them to your wallet. Withdrawal
/// is only allowed if the position remains healthy after removal.
/// 
/// # Arguments
/// 
/// * `amount` - Number of market tokens to withdraw
/// 
/// # Health Requirements
/// 
/// If position has debt:
/// - Remaining collateral value must exceed debt × (1 / LTV)
/// - Example: $1000 debt at 80% LTV requires $1250 collateral
/// - Transaction reverts if health check fails
/// 
/// # Full Withdrawal
/// 
/// To withdraw all collateral:
/// 1. Repay all outstanding debt first
/// 2. Then withdraw full collateral balance
#[derive(Accounts)]
pub struct WithdrawAccounts<'info> {
    /// Owner of the personal position withdrawing collateral.
    #[account(mut, signer)]
    pub owner: AccountInfo<'info>,
    /// Market metadata identifying which market these tokens belong to.
    pub market_meta: AccountInfo<'info>,
    /// Mint for the market tokens being withdrawn.
    pub mint_token: AccountInfo<'info>,
    /// Linear market account to update collateral tracking.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position from which collateral is being withdrawn.
    /// Must be owned by the signer and have no outstanding debt.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Escrow token account holding the position's collateral.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Destination token account to receive withdrawn tokens.
    #[account(mut)]
    pub token_dst: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Borrow main tokens against deposited collateral.
/// 
/// Takes a loan in main tokens (e.g., USDC) using market tokens as collateral.
/// Borrowed amount is limited by position's collateral value and market LTV ratio.
/// 
/// # Arguments
/// 
/// * `amount` - Amount of main tokens to borrow
/// 
/// # Borrowing Limits
/// 
/// Maximum borrow = Collateral Value × LTV Ratio
/// - Collateral valued at current floor price
/// - LTV typically 50-80% depending on market
/// - Cannot exceed available market liquidity
/// 
/// # Interest Accrual
/// 
/// - Interest calculated per-second at market rate
/// - Compounds continuously on outstanding debt
/// - Rate may vary based on utilization
/// 
/// # Liquidation Risk
/// 
/// Position can be liquidated if:
/// - Market token price drops significantly
/// - Accumulated interest pushes debt above limit
/// - Market LTV parameters change
/// 
/// Monitor position health regularly to avoid liquidation.
#[derive(Accounts)]
pub struct BorrowAccounts<'info> {
    /// Owner of the personal position borrowing funds.
    #[account(mut, signer)]
    pub owner: AccountInfo<'info>,
    /// Tenant account for platform fee distribution.
    pub tenant: AccountInfo<'info>,
    /// Market group containing borrow fee configuration.
    pub market_group: AccountInfo<'info>,
    /// Market metadata with all market configuration and references.
    pub market_meta: AccountInfo<'info>,
    /// Market's liquidity vault providing the borrowed funds.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Mint for the main token being borrowed.
    pub mint_main: AccountInfo<'info>,
    /// Destination account to receive borrowed main tokens.
    #[account(mut)]
    pub main_dst: AccountInfo<'info>,
    /// Linear market account to update liquidity and debt tracking.
    /// Constrained by market_meta
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position using collateral to secure the loan.
    /// Must have sufficient collateral for the requested borrow amount.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Repay borrowed main tokens to reduce debt.
/// 
/// Repays outstanding debt in main tokens, reducing position's obligations and
/// improving health factor. Can repay partial or full amounts.
/// 
/// # Arguments
/// 
/// * `amount` - Amount of main tokens to repay
/// 
/// # Repayment Order
/// 
/// Payments apply to:
/// 1. Accrued interest first
/// 2. Principal debt second
/// 
/// # Benefits of Repayment
/// 
/// - Reduces liquidation risk
/// - Stops interest accrual on repaid amount
/// - Frees up borrowing capacity
/// - Enables collateral withdrawal
/// 
/// # Full Repayment
/// 
/// To close position completely:
/// 1. Repay all debt including accrued interest
/// 2. Withdraw all collateral
/// 3. Position can then be closed if desired
#[derive(Accounts)]
pub struct RepayAccounts<'info> {
    /// The account repaying the debt (can be anyone, not just the position owner).
    #[account(mut, signer)]
    pub repayer: AccountInfo<'info>,
    /// Market metadata with all market configuration and references.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account to update liquidity and debt tracking.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position whose debt is being repaid.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Mint for the main token being repaid.
    pub mint_main: AccountInfo<'info>,
    /// Source account containing main tokens for repayment.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// Market's liquidity vault receiving the repayment.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Withdraw collateral, sell it, and optionally repay debt from proceeds.
/// 
/// Atomically combines withdraw, sell, and repay operations. Withdraws collateral tokens
/// from personal position, sells them back to the market, optionally repays debt from
/// the proceeds, and transfers remaining cash to the user.
/// 
/// # Arguments
/// 
/// * `args.collateral_reduce_by` - Amount of collateral tokens to withdraw and sell
/// * `args.debt_reduce_by` - Amount of debt to repay from sale proceeds (can be 0)
/// * `args.min_cash_to_user` - Minimum cash to receive after repaying debt (slippage protection)
/// 
/// # Operation Flow
/// 
/// 1. Withdraw collateral from position
/// 2. Sell withdrawn collateral to market
/// 3. Repay debt from sale proceeds (if debt_reduce_by > 0)
/// 4. Transfer remaining cash to user
/// 
/// # Slippage Protection
/// 
/// Transaction fails if:
/// - Sale proceeds < debt_reduce_by + min_cash_to_user
/// - Protects against unfavorable price movements
/// 
/// # Debt Repayment
/// 
/// - Debt repayment is optional (debt_reduce_by can be 0)
/// - If repaying, permission checks ensure repay is allowed
/// - Remaining sale proceeds go to user after repayment
/// 
/// # Use Cases
/// 
/// - Close leveraged position: withdraw all collateral, sell, repay all debt
/// - Partial deleverage: reduce position and debt simultaneously
/// - Take profit: withdraw and sell collateral, keep debt unchanged (debt_reduce_by = 0)
#[derive(Accounts)]
pub struct WithdrawSellAndRepayAccounts<'info> {
    /// Owner of the personal position performing the operation.
    #[account(mut, signer)]
    pub owner: AccountInfo<'info>,
    /// Tenant account for platform fee collection.
    pub tenant: AccountInfo<'info>,
    /// Market group that owns this market.
    pub market_group: AccountInfo<'info>,
    /// Market metadata containing configuration and linked accounts.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account with price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position from which collateral is being withdrawn.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Escrow account holding the position's collateral tokens.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Mint for the market's derivative token being sold.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token received from the sale.
    pub mint_main: AccountInfo<'info>,
    /// Destination account to receive main tokens from the sale (after debt repayment).
    #[account(mut)]
    pub main_dst: AccountInfo<'info>,
    /// Liquidity vault that provides cash for the sale.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Exercise option tokens to purchase market tokens at floor price.
/// 
/// Converts option tokens into market tokens by paying the floor price in main tokens.
/// This allows option holders to acquire tokens at a fixed price regardless of current
/// market price.
/// 
/// # Arguments
/// 
/// * `amount` - Number of option tokens to exercise
/// 
/// # Economics
/// 
/// For each option token:
/// - Pay: 1 unit of main token × floor price
/// - Receive: 1 market token
/// - Burn: 1 option token
/// 
/// # Profitability
/// 
/// Profitable when: Current Price > Floor Price + Exercise Fee
/// - Check current bonding curve price
/// - Account for exercise fees
/// - Consider immediate sell vs holding
/// 
/// # Requirements
/// 
/// - Sufficient option token balance
/// - Sufficient main tokens for payment
/// - Market must allow option exercise
#[derive(Accounts)]
pub struct ExerciseOptionsAccounts<'info> {
    /// The account exercising options and paying the exercise price.
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    /// Tenant account for platform fee distribution.
    pub tenant: AccountInfo<'info>,
    /// Market group containing exercise option fee configuration.
    pub market_group: AccountInfo<'info>,
    /// Market metadata with all market configuration and references.
    pub market_meta: AccountInfo<'info>,
    /// Linear market account to update supply tracking.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Source account containing main tokens to pay exercise price.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// Source account containing option tokens to burn.
    #[account(mut)]
    pub options_src: AccountInfo<'info>,
    /// Destination account to receive market tokens.
    #[account(mut)]
    pub token_dst: AccountInfo<'info>,
    /// Market's liquidity vault receiving the exercise payment.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Mint for option tokens being burned.
    #[account(mut)]
    pub mint_options: AccountInfo<'info>,
    /// Mint for market tokens being received.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for main tokens used as payment.
    pub mint_main: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Token program for option and market tokens.
    pub token_program: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Redeem market tokens at the guaranteed floor price.
/// 
/// Allows token holders to exit at the floor price when market price is at or near
/// the floor. This provides downside protection and ensures minimum redemption value.
/// 
/// # Arguments
/// 
/// * `amount_tokens_in` - Number of market tokens to redeem
/// 
/// # Redemption Limits
/// 
/// Maximum redeemable = Tail Width = (tail_start - shoulder_end)
/// - Protects bonding curve integrity
/// - Ensures sufficient liquidity for all holders
/// - Resets as tokens are bought back
/// 
/// # Price Guarantee
/// 
/// Receives: Floor Price × Tokens - Fees
/// - Always redeems at floor regardless of curve position
/// - Sell fees still apply (platform + group)
/// - Net proceeds = floor_price × tokens × (1 - total_fee_rate)
/// 
/// # Use Cases
/// 
/// - Exit strategy during market downturns
/// - Arbitrage when market price < floor
/// - Risk management for large positions
#[derive(Accounts)]
pub struct RedeemAtFloorAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    pub tenant: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    pub mint_main: AccountInfo<'info>,
    #[account(mut)]
    pub main_dst: AccountInfo<'info>,
    #[account(mut)]
    pub token_src: AccountInfo<'info>,
    pub token_program_main: AccountInfo<'info>,
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Initialize a multi-curve market with Dutch auction configuration.
/// 
/// Creates a market using a multi-segment bonding curve that provides more flexibility
/// than linear markets. Supports variable-length price curves with multiple segments,
/// each with its own slope. Includes Dutch auction for initial price discovery.
/// 
/// # Arguments
/// 
/// * `args` - Configuration including:
/// - `floor`: Base price per token
/// - `target`: Maximum price per token
/// - `shoulder_start` / `shoulder_end`: Range for initial linear segment
/// - `tail_start`: Beginning of constant max price segment
/// - `middle_segments`: Array of intermediate curve segments
/// - Dutch auction parameters (multiplier, duration, start time)
/// 
/// # Multi-Curve Advantages
/// 
/// - Flexible price discovery through custom segments
/// - Better modeling of complex tokenomics
/// - Smooth transitions between price regions
/// - Support for non-linear growth patterns
/// 
/// # Segment Structure
/// 
/// 1. Floor: Constant price from 0 to shoulder_start
/// 2. First shoulder: Linear from shoulder_start to first middle segment
/// 3. Middle segments: Variable slopes and ranges (can be empty)
/// 4. Final shoulder: From last middle segment to shoulder_end
/// 5. Tail: Constant max price from tail_start onward
/// 
/// # Access Control
/// 
/// Only the market group admin can create new markets.
#[derive(Accounts)]
pub struct MultiMarketInitWithDutchAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    #[account(signer)]
    pub group_admin: AccountInfo<'info>,
    #[account(signer)]
    pub seed: AccountInfo<'info>,
    pub tenant: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub mint_main: AccountInfo<'info>,
    /// The token account for the market
    /// This account must be created in a previous instruction
    /// With supply set to zero
    /// And mint authority assigned to the market_meta
    pub mint_token: AccountInfo<'info>,
    #[account(mut)]
    pub mint_options: AccountInfo<'info>,
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub market_meta: AccountInfo<'info>,
    pub system_program: AccountInfo<'info>,
    pub token_program: AccountInfo<'info>,
    pub token_program_main: AccountInfo<'info>,
}

/// Raise floor price for multi-curve markets with validation.
/// 
/// Increases the minimum token price while preserving the total area under the
/// multi-segment curve. More complex than linear markets due to multiple segments
/// requiring coordinated adjustment.
/// 
/// # Arguments
/// 
/// * `args` - Parameters including:
/// - `new_floor`: Target floor price
/// - `new_shoulder_end`: Adjusted endpoint for price curve
/// - `new_middle_segments`: Recalculated intermediate segments
/// - `max_deviation_bps`: Tolerance for area preservation
/// 
/// # Segment Adjustment
/// 
/// When floor rises:
/// 1. All segments shift up by floor delta
/// 2. Slopes adjust to maintain total area
/// 3. Segment boundaries may compress
/// 4. Continuity preserved at all transitions
/// 
/// # Validation Checks
/// 
/// - Area preservation within tolerance
/// - Sufficient backing liquidity
/// - Valid segment progression (monotonic)
/// - No instant arbitrage opportunities
/// 
/// # Complexity Note
/// 
/// Multi-curve floor raising requires careful calculation to maintain curve
/// properties across all segments while preserving economic invariants.
#[derive(Accounts)]
pub struct RaiseFloorPreserveAreaCheckedMultiAccounts<'info> {
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
}

/// Buy from multi-curve market and deposit as collateral.
/// 
/// Purchases tokens from a multi-segment bonding curve and immediately deposits them
/// into a personal position. Combines acquisition and collateralization in one step.
/// 
/// # Arguments
/// 
/// * `cash_in` - Exact amount of main tokens to spend
/// * `min_token_out` - Minimum tokens to receive (slippage protection)
/// 
/// # Multi-Curve Pricing
/// 
/// Price depends on current supply position:
/// - Traverses multiple segments with different slopes
/// - Large buys may span several segments
/// - Each segment calculated independently
/// - Dutch boost applies if active
/// 
/// # Atomic Benefits
/// 
/// - Single transaction for buy + deposit
/// - Reduces transaction costs
/// - Prevents front-running between operations
/// - Immediate collateral availability
/// 
/// # Requirements
/// 
/// - Personal position must exist
/// - Market must allow buying and deposits
/// - Sufficient main token balance
#[derive(Accounts)]
pub struct BuyWithExactCashInAndDepositMultiAccounts<'info> {
    /// The trader buying tokens and depositing them as collateral.
    #[account(mut, signer)]
    pub owner: AccountInfo<'info>,
    /// Tenant account for platform fee collection.
    pub tenant: AccountInfo<'info>,
    /// Market group that owns this market.
    pub market_group: AccountInfo<'info>,
    /// Market metadata containing configuration and linked accounts.
    pub market_meta: AccountInfo<'info>,
    /// Multi-curve market account with price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Personal position that will receive the purchased tokens as collateral.
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    /// Escrow account that will receive the purchased tokens as collateral.
    #[account(mut)]
    pub escrow: AccountInfo<'info>,
    /// Mint for the market's derivative token being purchased.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token used as payment.
    pub mint_main: AccountInfo<'info>,
    /// Temporary destination for purchased tokens before deposit to escrow.
    #[account(mut)]
    pub token_dst: AccountInfo<'info>,
    /// Source account containing main tokens for payment.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// Liquidity vault receiving the main token payment.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Buy tokens from a multi-curve market.
/// 
/// Purchases market tokens using a multi-segment bonding curve that can model
/// complex price dynamics. Supports large purchases that span multiple curve
/// segments with different characteristics.
/// 
/// # Arguments
/// 
/// * `cash_in` - Exact amount of main tokens to spend
/// * `min_token_out` - Minimum tokens required (reverts if not met)
/// 
/// # Execution Across Segments
/// 
/// Large purchases may traverse multiple segments:
/// 1. Start at current supply position
/// 2. Buy at current segment's price/slope
/// 3. If segment exhausted, continue to next
/// 4. Accumulate tokens from each segment
/// 5. Stop when cash exhausted or curve end reached
/// 
/// # Price Impact
/// 
/// - Each segment may have different price sensitivity
/// - Steeper slopes mean higher price impact
/// - Consider breaking very large orders
/// 
/// # Fees
/// 
/// Standard fee structure applies:
/// - Platform fee to tenant
/// - Group fee to market admin
/// - Deducted from input amount
#[derive(Accounts)]
pub struct BuyWithExactCashInMultiAccounts<'info> {
    /// The buyer purchasing market tokens.
    #[account(mut, signer)]
    pub signer: AccountInfo<'info>,
    /// Tenant account for platform fee collection.
    pub tenant: AccountInfo<'info>,
    /// Market group that owns this market.
    pub market_group: AccountInfo<'info>,
    /// Market metadata containing configuration and linked accounts.
    pub market_meta: AccountInfo<'info>,
    /// Multi-curve market account with price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Mint for the market's derivative token.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token used as payment.
    pub mint_main: AccountInfo<'info>,
    /// Destination token account to receive purchased tokens.
    #[account(mut)]
    pub token_dst: AccountInfo<'info>,
    /// Source account containing main tokens for payment.
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    /// Liquidity vault receiving the main tokens.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Sell tokens to a multi-curve market.
/// 
/// Sells market tokens back to the protocol following the multi-segment bonding curve
/// in reverse. Large sales may span multiple segments with varying price impacts.
/// 
/// # Arguments
/// 
/// * `amount_in` - Exact number of tokens to sell
/// * `cash_out_min` - Minimum main tokens to receive
/// 
/// # Multi-Segment Execution
/// 
/// Sells work backwards through curve:
/// 1. Start at current supply position
/// 2. Sell into current segment at its price
/// 3. If more to sell, move to previous segment
/// 4. Continue until all tokens sold
/// 5. Cannot sell below floor price
/// 
/// # Price Discovery
/// 
/// - Higher supplies sell first (higher prices)
/// - Price decreases as supply reduces
/// - Each segment has independent characteristics
/// - Floor provides absolute minimum
/// 
/// # Slippage Considerations
/// 
/// Multi-curve markets may have:
/// - Variable liquidity across segments
/// - Sudden price changes at boundaries
/// - Different impacts in different regions
#[derive(Accounts)]
pub struct SellWithExactTokenInMultiAccounts<'info> {
    /// User selling market tokens back to the protocol.
    #[account(mut, signer)]
    pub user: AccountInfo<'info>,
    /// Tenant account for platform fee collection.
    pub tenant: AccountInfo<'info>,
    /// Market group that owns this market.
    pub market_group: AccountInfo<'info>,
    /// Market metadata containing configuration and linked accounts.
    pub market_meta: AccountInfo<'info>,
    /// Multi-curve market account with price curve and state.
    #[account(mut)]
    pub market: AccountInfo<'info>,
    /// Revenue escrow for market group admin fees.
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    /// Revenue escrow for tenant platform fees.
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    /// Liquidity vault sending out main tokens.
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    /// Mint for the market tokens being sold.
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    /// Mint for the main token received from sale.
    pub mint_main: AccountInfo<'info>,
    /// Destination account to receive main tokens from sale.
    #[account(mut)]
    pub main_dst: AccountInfo<'info>,
    /// Source account containing market tokens to sell.
    #[account(mut)]
    pub token_src: AccountInfo<'info>,
    /// Token program for the main token.
    pub token_program_main: AccountInfo<'info>,
    /// Token program for the market's derivative token.
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Exercise options in a multi-curve market.
/// 
/// Converts option tokens to market tokens at the floor price, regardless of the
/// current position on the multi-segment curve. Options provide downside protection
/// in volatile multi-curve markets.
/// 
/// # Arguments
/// 
/// * `amount` - Number of option tokens to exercise
/// 
/// # Exercise Mechanics
/// 
/// Same as linear markets:
/// - Pay floor price per option in main tokens
/// - Receive one market token per option
/// - Options are burned
/// 
/// # Multi-Curve Considerations
/// 
/// - Floor price is constant across all segments
/// - Current curve position doesn't affect exercise
/// - Especially valuable when price is in higher segments
/// - Provides arbitrage during market dislocations
/// 
/// # Strategic Use
/// 
/// In multi-curve markets, options help:
/// - Navigate complex price dynamics
/// - Profit from segment transitions
/// - Hedge against curve adjustments
#[derive(Accounts)]
pub struct ExerciseOptionsMultiAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    pub tenant: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    #[account(mut)]
    pub options_src: AccountInfo<'info>,
    #[account(mut)]
    pub token_dst: AccountInfo<'info>,
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    #[account(mut)]
    pub mint_options: AccountInfo<'info>,
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    pub mint_main: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    pub token_program: AccountInfo<'info>,
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Repay debt in a multi-curve market.
/// 
/// Repays borrowed main tokens to reduce debt obligations in a personal position.
/// Multi-curve markets may have different interest dynamics based on utilization
/// across curve segments.
/// 
/// # Arguments
/// 
/// * `amount` - Amount of main tokens to repay
/// 
/// # Interest Considerations
/// 
/// Multi-curve markets may feature:
/// - Variable rates based on curve position
/// - Different risk profiles across segments
/// - Dynamic rate adjustments
/// 
/// # Repayment Priority
/// 
/// Same as linear markets:
/// 1. Accrued interest first
/// 2. Principal balance second
/// 3. Excess returned to payer
/// 
/// # Position Management
/// 
/// Regular repayments recommended to:
/// - Maintain healthy LTV ratios
/// - Reduce liquidation risk
/// - Take advantage of rate changes
#[derive(Accounts)]
pub struct RepayMultiAccounts<'info> {
    #[account(mut, signer)]
    pub repayer: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub personal_position: AccountInfo<'info>,
    pub mint_main: AccountInfo<'info>,
    #[account(mut)]
    pub main_src: AccountInfo<'info>,
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    pub token_program_main: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Redeem tokens at floor price in multi-curve market.
/// 
/// Provides guaranteed exit at the floor price for multi-curve market tokens.
/// Essential safety mechanism given the complexity of multi-segment pricing.
/// 
/// # Arguments
/// 
/// * `amount_tokens_in` - Number of tokens to redeem at floor
/// 
/// # Redemption in Complex Markets
/// 
/// Multi-curve considerations:
/// - Floor constant across all segments
/// - Redemption bypasses curve complexity
/// - Same tail width limits apply
/// - Critical during segment transitions
/// 
/// # Maximum Redemption
/// 
/// Limited to tail width: (tail_start - shoulder_end)
/// - Protects curve integrity
/// - Ensures fair access for all holders
/// - Resets as market activity continues
/// 
/// # Use Cases
/// 
/// Especially important in multi-curve markets for:
/// - Exiting during curve adjustments
/// - Arbitrage across segments
/// - Risk management in complex dynamics
/// - Guaranteed liquidity provision
#[derive(Accounts)]
pub struct RedeemAtFloorMultiAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    pub tenant: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_group: AccountInfo<'info>,
    #[account(mut)]
    pub rev_escrow_tenant: AccountInfo<'info>,
    #[account(mut)]
    pub liq_vault_main: AccountInfo<'info>,
    #[account(mut)]
    pub mint_token: AccountInfo<'info>,
    pub mint_main: AccountInfo<'info>,
    #[account(mut)]
    pub main_dst: AccountInfo<'info>,
    #[account(mut)]
    pub token_src: AccountInfo<'info>,
    pub token_program_main: AccountInfo<'info>,
    pub token_program: AccountInfo<'info>,
    #[account(mut)]
    pub log_account: AccountInfo<'info>,
    pub mayflower_program: AccountInfo<'info>,
}

/// Modify the price curve's sensitivity to supply changes at the current token supply level.
/// 
/// Allows market administrators to dynamically adjust how quickly the token price changes
/// in response to supply increases. The modification is applied at the current token supply
/// level and affects the curve's behavior for all future supply levels beyond that point.
/// 
/// # Arguments
/// 
/// * `args` - Curve modification parameters including:
/// - `multiplier`: Magnitude of slope change (0.0 < multiplier < 1.0)
/// - `new_middle_segment_count`: Expected number of middle segments after modification
/// - `increase`: Whether to increase (true) or decrease (false) sensitivity
/// 
/// # How it works
/// 
/// The function modifies the curve's vertex structure by either:
/// - **Inserting a new vertex** at the current supply level if it falls within the final segment
/// - **Removing the last vertex** if the current supply is not in the final segment and the
/// sensitivity direction doesn't match the final segment's current direction
/// 
/// # Sensitivity Direction
/// 
/// - **`increase = true`** (`SensitivityDirection::Higher`): Makes the curve more sensitive to supply changes
/// - Results in steeper slopes = faster price increases as supply grows
/// - Useful for encouraging early adoption or responding to high demand
/// 
/// - **`increase = false`** (`SensitivityDirection::Lower`): Makes the curve less sensitive to supply changes
/// - Results in gentler slopes = slower price increases as supply grows
/// - Useful for risk management or stabilizing prices in volatile conditions
/// 
/// # Multiplier Effect
/// 
/// The `multiplier` parameter (0.0 < multiplier < 1.0) determines the magnitude of change:
/// - For `Higher` direction: new_slope = current_slope × (1 + multiplier)
/// - For `Lower` direction: new_slope = current_slope × (1 - multiplier)
/// 
/// # Access Control
/// 
/// Only the market group admin can modify curves.
/// 
/// # Use Cases
/// 
/// - **Market Making**: Adjust sensitivity based on trading volume or market volatility
/// - **Risk Management**: Reduce sensitivity in high-supply regions to prevent extreme price swings
/// - **Liquidity Provision**: Increase sensitivity in low-supply regions to encourage early adoption
/// - **Dynamic Pricing**: Respond to market conditions by modifying curve behavior
/// 
/// # Constraints
/// 
/// - `multiplier` must be between 0.0 and 1.0 (exclusive)
/// - The function preserves curve continuity at segment boundaries
/// - Modifications only affect the curve beyond the current supply level
/// - The account must be reallocated to accommodate the new segment count
/// 
/// # Safety Considerations
/// 
/// - Changes are irreversible once applied
/// - The operation will panic if the actual number of middle segments after modification
/// doesn't match the expected `new_middle_segment_count`
/// - Consider market impact before significant changes
/// - Monitor market behavior after curve changes
#[derive(Accounts)]
pub struct ModifyCurveMultiAccounts<'info> {
    #[account(mut, signer)]
    pub payer: AccountInfo<'info>,
    #[account(mut, signer)]
    pub admin: AccountInfo<'info>,
    pub market_group: AccountInfo<'info>,
    pub market_meta: AccountInfo<'info>,
    #[account(mut)]
    pub market: AccountInfo<'info>,
    pub system_program: AccountInfo<'info>,
}

// Account structures
#[account]
pub struct LogAccount {
    pub counter: u64,
    pub bump: [u8; 1],
}

/// Market group account managing a collection of related markets with shared fee structures.
/// 
/// A MarketGroup acts as an intermediate administrative layer between a Tenant and individual
/// Markets. It defines the fee structure that applies to all markets within the group and
/// manages permissions for market operations. Multiple markets can belong to the same group,
/// sharing common fee configurations while maintaining independent bonding curves and liquidity.
/// 
/// # Ownership Hierarchy
/// - Owned by a single Tenant account
/// - Owns multiple MarketMeta accounts (which reference specific Market implementations)
/// - Controls fee distribution between market group admin and tenant platform
/// 
/// # Fee Management
/// The MarketGroup defines four types of fees that apply to all its markets:
/// - Buy fees: charged when purchasing tokens from the market
/// - Sell fees: charged when selling tokens back to the market
/// - Borrow fees: charged when borrowing against collateral
/// - Exercise option fees: charged when exercising token options
/// 
/// Fees collected are split between the market group admin and the tenant based on
/// the tenant's platform fee configuration.
#[account]
pub struct MarketGroup {
    /// The tenant account that owns this market group.
    /// All markets in this group must belong to the same tenant.
    pub tenant: Pubkey,
    /// The admin public key with control over this market group.
    /// Can update group settings, manage fees, and create new markets.
    pub admin: Pubkey,
    /// The proposed new admin for ownership transfer (None if no transfer pending).
    /// Requires acceptance by the proposed admin to complete the transfer.
    pub proposed_admin: Option<Pubkey>,
    /// PDA metadata containing the seed and bump used to derive this account's address.
    /// Used for signing operations and address verification.
    pub pda_meta: PdaMeta,
    /// Fee configuration for all markets within this group.
    /// Contains buy, sell, borrow, and exercise option fee rates.
    pub fees: Fees,
}

/// Market implementation using a linear bonding curve with shoulder configuration.
/// 
/// MarketLinear implements a two-segment linear price curve that provides dynamic pricing
/// for token purchases and sales. The curve consists of a steeper "shoulder" segment at
/// low supply levels (providing higher initial prices) and a gentler "tail" segment for
/// the bulk of the supply range.
/// 
/// # Bonding Curve Design
/// The linear market uses a piecewise linear function:
/// - Shoulder segment: Higher slope (m1) from 0 to shoulder point
/// - Tail segment: Lower slope (m2) from shoulder point onwards
/// - Floor price: Minimum price below which tokens cannot trade
/// 
/// # Use Cases
/// - Simple bonding curve markets with predictable price dynamics
/// - Markets requiring a price premium for early adopters
/// - Token launches with controlled price discovery
/// 
/// # Relationship to MarketMeta
/// Each MarketLinear is paired with exactly one MarketMeta account that contains
/// the market's configuration, token mints, vaults, and permissions.
#[account]
pub struct MarketLinear {
    /// Reference to the MarketMeta account containing shared market configuration.
    /// Links this market implementation to its metadata and token mints.
    pub market_meta: Pubkey,
    /// Current state of the market including liquidity, debt, supply, and collateral.
    /// Tracks all dynamic values that change during market operations.
    pub state: MarketState,
    /// Serialized linear price curve parameters defining market pricing.
    /// Contains slopes, floor price, and shoulder configuration for the bonding curve.
    pub price_curve: LinearPriceCurveSerialized,
}

/// Market metadata account containing configuration shared across all market implementations.
/// 
/// MarketMeta serves as the central configuration hub for a market, storing references to
/// all associated accounts (tokens, vaults, escrows) and operational parameters. It acts
/// as a bridge between the market's administrative structure (Tenant/MarketGroup) and its
/// implementation (MarketLinear or MarketMultiCurve).
/// 
/// # Key Relationships
/// - References its parent MarketGroup for fee configurations
/// - Referenced by exactly one Market implementation (Linear or MultiCurve)
/// - Controls three token mints: main (collateral), token (traded), and options
/// - Manages liquidity vault and revenue distribution escrows
/// 
/// # Permissions System
/// MarketMeta includes a flexible permissions bitfield that controls which operations
/// are allowed on the market. This enables fine-grained control over market functionality,
/// allowing administrators to disable specific features during maintenance or in response
/// to market conditions.
/// 
/// # Dutch Auction
/// Markets can optionally use a Dutch auction mechanism at launch, providing time-based
/// price incentives to early participants. The auction boost decreases over time according
/// to the configured parameters.
#[account]
pub struct MarketMeta {
    /// Mint for the main backing token (the cash token).
    /// This is the token used as collateral and for liquidity (e.g., USDC, SOL).
    pub mint_main: Pubkey,
    /// Mint for the token being traded in this market.
    /// This is the derivative token that users can buy/sell/borrow.
    pub mint_token: Pubkey,
    /// Mint for the options token associated with this market.
    /// Options tokens can be minted and later exercised to purchase the traded token.
    pub mint_options: Pubkey,
    /// The market group that this market belongs to.
    /// Determines fee structure and admin permissions for this market.
    pub market_group: Pubkey,
    /// The market account (Linear or MultiCurve) associated with this metadata.
    /// Ensures a 1:1 relationship between market and market meta accounts.
    pub market: Pubkey,
    /// The token program ID for the main token.
    /// Usually SPL Token or Token-2022, used for CPI calls.
    pub token_program_main: Pubkey,
    /// Vault that holds the liquidity pool for the main token.
    /// All market liquidity (cash) is stored here.
    pub liq_vault_main: Pubkey,
    /// Revenue escrow account for the market group.
    /// Collects group admin's share of fees from market operations.
    pub rev_escrow_group: Pubkey,
    /// Revenue escrow account for the tenant.
    /// Collects platform fees allocated to the tenant.
    pub rev_escrow_tenant: Pubkey,
    /// PDA metadata containing the seed and bump used to derive this account's address.
    /// Used for signing operations when the market acts as an authority.
    pub pda_meta: PdaMeta,
    /// Number of decimal places for the main token.
    /// Used for precise calculations and proper display formatting.
    pub decimals: u8,
    /// Bitfield controlling which operations are permitted on this market.
    /// Allows fine-grained control over market functionality.
    pub permissions: MarketPermissions,
    /// Unix timestamp when the market becomes active.
    /// Trading operations are restricted before this time.
    pub start_time: u64,
    /// Configuration for Dutch auction price boost mechanism.
    /// Provides time-based price incentives after market launch.
    pub dutch_config: DutchConfigSerialized,
}

/// Market implementation using a multi-segment bonding curve with dynamic complexity.
/// 
/// MarketMultiCurve extends the linear market concept by supporting multiple linear segments,
/// allowing for more sophisticated price curves that can adapt over time. This is particularly
/// useful when the floor price is raised, as the curve can maintain area-under-curve invariants
/// by adding intermediate segments.
/// 
/// # Advanced Bonding Curve
/// The multi-curve market supports:
/// - Initial shoulder segment with configurable slope multiplier
/// - Dynamic middle segments added when floor is raised
/// - Final tail segment extending to maximum supply
/// - Area preservation during floor adjustments
/// 
/// # Use Cases
/// - Markets requiring complex price dynamics
/// - Adaptive curves that evolve with market conditions
/// - Floor raising with liquidity preservation
/// - Multi-phase token distribution strategies
/// 
/// # Dynamic Segment Management
/// When the floor is raised, the curve automatically adds middle segments to:
/// - Preserve the total area under the curve (maintaining market cap)
/// - Ensure price continuity at segment boundaries
/// - Maintain monotonic price increases
#[account]
pub struct MarketMultiCurve {
    /// Reference to the MarketMeta account containing shared market configuration.
    /// Links this market implementation to its metadata and token mints.
    pub market_meta: Pubkey,
    /// Current state of the market including liquidity, debt, supply, and collateral.
    /// Tracks all dynamic values that change during market operations.
    pub state: MarketState,
    /// Serialized multi-segment price curve with dynamic middle segments.
    /// Supports complex bonding curves with multiple linear segments.
    pub price_curve: MultiPriceCurveSerialized,
}

/// Personal position account tracking an individual user's collateral and debt in a market.
/// 
/// PersonalPosition represents a user's borrowing position within a specific market. It tracks
/// both the collateral deposited (in market tokens) and any outstanding debt (in main tokens
/// like USDC). This account enables collateralized borrowing, where users can deposit market
/// tokens and borrow main tokens against them.
/// 
/// # Collateralization Model
/// - Users deposit market tokens as collateral into an escrow account
/// - Against this collateral, users can borrow main tokens (e.g., USDC)
/// - The maximum borrowing capacity depends on the market's collateralization ratio
/// - Collateral remains locked until all debt is repaid
/// 
/// # Account Lifecycle
/// 1. Created when a user first deposits collateral or borrows
/// 2. Persists as long as there's collateral or debt
/// 3. Can be closed when both collateral and debt reach zero
/// 
/// # Security
/// - Only the owner can perform operations on their position
/// - Collateral is held in a separate escrow account for security
/// - Position is tied to a specific market and cannot be transferred
#[account]
pub struct PersonalPosition {
    /// The market metadata account this position belongs to.
    /// Determines which market's tokens can be deposited and borrowed against.
    pub market_meta: Pubkey,
    /// The owner's public key who controls this position.
    /// Only the owner can deposit, withdraw, borrow, or repay.
    pub owner: Pubkey,
    /// The escrow token account holding deposited collateral tokens.
    /// Tokens are locked here while being used as collateral for borrowing.
    pub escrow: Pubkey,
    /// Amount of market tokens deposited as collateral.
    /// Can be withdrawn if debt is zero, or used to secure borrows.
    pub deposited_token_balance: u64,
    /// Amount of main tokens (e.g., USDC) currently borrowed against collateral.
    /// Must be repaid before collateral can be withdrawn.
    pub debt: u64,
    /// The PDA bump seed used to derive this account's address.
    /// Stored to avoid recalculation during operations.
    pub bump: [u8; 1],
}

/// Tenant account representing a platform operator or protocol administrator.
/// 
/// The Tenant is the top-level entity in the Mayflower protocol hierarchy. Each tenant
/// can manage multiple market groups, set platform-wide fees, and control permissions
/// for market group creation. Tenants enable multi-tenancy within the protocol, allowing
/// different operators to run their own instances with custom configurations.
/// 
/// # Account Hierarchy
/// ```
/// Tenant (Platform Operator)
/// └── MarketGroup (Fee Configuration)
/// └── MarketMeta (Market Configuration)
/// └── Market (Linear or MultiCurve Implementation)
/// ```
/// 
/// # Key Responsibilities
/// - Platform fee collection across all markets under this tenant
/// - Control over market group creation permissions
/// - Admin transfer and succession management
/// - Platform-level configuration and governance
#[account]
pub struct Tenant {
    /// The seed public key used to derive this tenant's PDA address.
    /// This ensures deterministic address generation and prevents duplicate tenants.
    pub seed: Pubkey,
    /// The PDA bump seed used to derive this account's address.
    /// Stored to avoid recalculation during CPI calls.
    pub bump: [u8; 1],
    /// The admin public key with control to create market groups.
    pub admin: Pubkey,
    /// The proposed new admin for ownership transfer (None if no transfer pending).
    /// Requires acceptance by the proposed admin to complete the transfer.
    pub proposed_admin: Option<Pubkey>,
    /// Platform fee rate in micro basis points (1 micro bp = 1/100 bp = 0.0001%).
    /// Applied to transactions within markets under this tenant.
    pub platform_fee_micro_bps: u32,
    /// Whether market groups can be created without explicit permission from the tenant admin.
    /// When true, any user can create market groups under this tenant.
    pub permissionless_group_creation: bool,
}

// Type structures
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct BuyWithExactCashInAndDepositEvent {
    /// The account that purchased tokens and deposited them as collateral.
    pub trader: Pubkey,
    /// The address of the market metadata account.
    pub market_meta: Pubkey,
    /// The address of the personal position account.
    pub personal_position: Pubkey,
    /// The amount of market tokens purchased.
    pub token_out: u64,
    /// The amount of main tokens paid by the trader (excluding fees).
    pub net_cash_in: u64,
    /// The fee amount allocated to the market group admin.
    pub fee_market_group: u64,
    /// The fee amount allocated to the platform.
    pub fee_platform: u64,
    /// The new market price after the purchase and deposit.
    pub new_market_price: DecimalSerialized,
    /// The new balance of the personal position after the purchase and deposit.
    pub new_personal_position_balance: u64,
}

/// Snapshot of the complete state of a market at a specific point in time.
/// This struct captures all relevant market data for off-chain analysis and record-keeping.
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MarketStateSnapshot {
    /// The market metadata account address for this market.
    /// This is the PDA that stores configuration and references to all associated accounts.
    pub market_metadata_address: Pubkey,
    /// Total amount of market tokens deposited as collateral across all personal positions.
    /// These tokens are held in escrow and can be withdrawn if debt obligations are met.
    pub total_market_deposited_collateral: u64,
    /// Total amount of main tokens (e.g., USDC, SOL) in the market's liquidity pool.
    /// This is the reserve available for purchases, borrows, and redemptions.
    pub total_main_token_in_liquidity_pool: u64,
    /// Total debt owed to the market across all personal positions.
    /// Represents main tokens that were borrowed and must be repaid.
    pub total_market_debt: u64,
    /// The floor price of the market (minimum price at supply = 0).
    /// This is the lowest price at which tokens can be sold back to the market.
    pub floor_price: DecimalSerialized,
    /// The current market price (marginal price at current supply).
    /// This is the price for buying the next infinitesimal amount of tokens.
    pub market_price: DecimalSerialized,
    /// The area under the price curve from 0 to current supply.
    /// Measured in token units, represents the total value locked in the curve.
    pub area_under_curve: u64,
    /// Total supply of market tokens currently minted and in circulation.
    /// This includes tokens in personal positions (collateral) and tokens held by traders.
    pub token_supply: u64,
    /// Unix timestamp (in seconds) when this snapshot was created.
    pub unix_timestamp: u64,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct SellWithExactTokenInAfterWithdrawEvent {
    /// The account that sold tokens back to the market.
    pub trader: Pubkey,
    /// The address of the market metadata account.
    pub market_meta: Pubkey,
    /// The amount of market tokens burned in the sale.
    pub token_in: u64,
    /// The amount of main tokens received by the trader after fees.
    /// This is the net amount transferred to the trader.
    pub net_cash_out: u64,
    /// The fee amount allocated to the platform.
    pub fee_platform: u64,
    /// The fee amount allocated to the market group admin.
    pub fee_market_group: u64,
    /// The new balance of the personal position
    pub new_personal_position_balance: u64,
    /// The address of the personal position account.
    pub personal_position: Pubkey,
    /// The new market price after the sell.
    pub new_market_price: DecimalSerialized,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct ModifyCurveArgs {
    /// The multiplier to apply to the curve (between 0.0 and 1.0)
    pub multiplier: f32,
    /// The new number of middle segments
    pub new_middle_segment_count: u8,
    /// If true, the sensitivity direction is higher, otherwise it is lower
    pub increase: bool,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MultiMarketInitWithDutchArgs {
    pub shoulder_slope_scalar: f64,
    pub main_slope: f64,
    pub f: f32,
    pub start_time: u64,
    pub dutch_config: DutchConfigSerialized,
    pub permissions: MarketPermissions,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct RaiseFloorPreserveAreaCheckedMultiArgs {
    /// The ratio of the floor increase (greater than 0.0)
    pub floor_increase_ratio: DecimalSerialized,
    /// The new shoulder end (must be greater than the current shoulder end)
    pub new_shoulder_end: u64,
    /// The minimum liquidity ratio (greater than or equal to 0.0)
    /// This is the ratio of the liqudity after the shoulder end to the liquidity of the shoulder
    pub min_liq_ratio: DecimalSerialized,
    /// If true, there was no way to raise the floor without backtracking from a vertex,
    /// extending the a neighbor segment backwards
    /// 
    /// This happens if the shoulder must sweep forward over segments that increase in slope
    /// and there is no solution, since the shoulder slope increases when it intersects the new higher slope
    /// the area under the curve would be too small
    pub must_backtrack: bool,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct BuyWithExactCashInAndDepositWithDebtArgs {
    /// Exact amount of cash to spend on tokens
    pub exact_cash_in: u64,
    /// Minimum acceptable tokens to receive (slippage protection)
    pub min_token_received: u64,
    /// New debt amount to take on
    pub new_acquired_debt: u64,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MarketLinearInitWithDutchArgs {
    pub x2: u64,
    pub m2: DecimalSerialized,
    pub m1: DecimalSerialized,
    pub f: DecimalSerialized,
    pub b2: DecimalSerialized,
    pub start_time: u64,
    pub dutch_config: DutchConfigSerialized,
    pub permissions: MarketPermissions,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MarketLinearArgs {
    pub x2: u64,
    pub m2: DecimalSerialized,
    pub m1: DecimalSerialized,
    pub f: DecimalSerialized,
    pub b2: DecimalSerialized,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct RaiseFloorFromExcessLiquidityCheckedArgs {
    /// the maximum new floor that is allowed
    pub max_new_floor: DecimalSerialized,
    /// the amount to increase the floor by
    pub increase_ratio_micro_basis_points: u32,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct RaiseFloorPreserveAreaCheckedArgs2 {
    /// The maximum new floor price (must be greater than the current floor)
    pub max_new_floor: DecimalSerialized,
    /// The increase ratio
    pub floor_increase_ratio: DecimalSerialized,
    /// The new shoulder end (must be greater than the current shoulder end)
    pub new_shoulder_end: u64,
    /// The minimum liquidity ratio (greater than or equal to 0.0)
    /// This is the ratio of the liqudity after the shoulder end to the liquidity of the shoulder
    /// if the ratio is 0.0, then the floor is permitted to rise such that the new shoulder is equal to supply
    pub min_liq_ratio: DecimalSerialized,
    /// the maximum token units that the total area of the curve is allowed to shrink by
    /// this is set by the client to restrict overly aggressive floor raising, with a tolerance to account for "slippage"
    pub max_area_shrinkage_tolerance_units: u64,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct RaiseFloorPreserveAreaCheckedArgs {
    /// The ratio of the floor increase (greater than 0.0)
    pub floor_increase_ratio: DecimalSerialized,
    /// The new shoulder end (must be greater than the current shoulder end)
    pub new_shoulder_end: u64,
    /// The minimum liquidity ratio (greater than or equal to 0.0)
    /// This is the ratio of the liqudity after the shoulder end to the liquidity of the shoulder
    pub min_liq_ratio: DecimalSerialized,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct WithdrawSellAndRepayArgs {
    /// Amount of collateral to withdraw and sell
    pub collateral_reduce_by: u64,
    /// Amount of debt to repay from sale proceeds
    pub debt_reduce_by: u64,
    /// Minimum cash to receive after repaying debt (slippage protection)
    pub min_cash_to_user: u64,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MarketGroupInitArgs {
    pub fees: Fees,
    pub group_admin: Pubkey,
}

/// Wrapper for serializing and deserializing high-precision decimal values.
/// 
/// Solana accounts require all data to be serialized as bytes. This struct provides
/// a bridge between Rust's Decimal type (used for precise financial calculations)
/// and the byte array representation stored on-chain.
/// 
/// # Usage
/// - Serialize: Convert Decimal to 16-byte array for storage
/// - Deserialize: Reconstruct Decimal from stored bytes
/// - Preserves full decimal precision across serialization
/// 
/// # Why This Matters
/// Financial calculations require high precision to avoid rounding errors that could
/// accumulate over thousands of transactions. The 16-byte representation maintains
/// the full 128-bit precision of the Decimal type.
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct DecimalSerialized {
    /// Serialized Decimal value as a 16-byte array.
    /// Used for storing fixed-point decimal numbers in Solana accounts.
    pub val: [u8; 16],
}

/// Metadata for Program Derived Address (PDA) accounts.
/// 
/// PDAs are deterministically derived addresses that can only be controlled by the program.
/// This struct stores the components needed to derive and verify PDA addresses, enabling
/// efficient Cross-Program Invocations (CPIs) without recomputing the address.
/// 
/// # PDA Derivation
/// Solana PDAs are derived from:
/// 1. A string seed (defined per account type)
/// 2. A unique seed (usually a Pubkey)
/// 3. A bump seed (ensures the address is off-curve)
/// 
/// # Performance Optimization
/// Storing the bump seed avoids expensive recomputation during CPIs, as finding the bump
/// requires iterating through possible values until finding one that produces an off-curve point.
/// 
/// # Security
/// PDAs cannot be controlled by external signers, making them ideal for program-controlled
/// accounts like escrows, vaults, and authority accounts.
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct PdaMeta {
    /// The PDA bump seed used to derive the account address.
    /// Stored to enable efficient CPI calls without recomputation.
    pub bump: [u8; 1],
    /// The seed public key used as input to the PDA derivation.
    /// Combined with string seeds and bump to create unique addresses.
    pub seed: Pubkey,
}

/// Fee configuration structure for market operations within a market group.
/// 
/// All fees are denominated in micro-basis points (micro-bps), where:
/// - 1 micro-bp = 1/100 of a basis point = 0.0001%
/// - 100 micro-bps = 1 basis point = 0.01%
/// - 10,000 micro-bps = 100 basis points = 1%
/// 
/// This granular fee precision allows for fine-tuned economic models while maintaining
/// integer arithmetic for computational efficiency on-chain.
/// 
/// # Example
/// A buy fee of 250 micro-bps equals 2.5 basis points or 0.025% of the transaction amount.
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct Fees {
    /// Fee charged when buying tokens from the market (in micro basis points).
    /// Applied to the purchase amount before tokens are transferred.
    pub buy: u32,
    /// Fee charged when selling tokens back to the market (in micro basis points).
    /// Applied to the sale proceeds before main tokens are transferred.
    pub sell: u32,
    /// Fee charged when borrowing against collateral (in micro basis points).
    /// Applied to the borrowed amount at the time of borrowing.
    pub borrow: u32,
    /// Fee charged when exercising options to purchase tokens (in micro basis points).
    /// Applied to the option exercise amount.
    pub exercise_option: u32,
}

/// Serialized representation of a linear bonding curve with shoulder configuration.
/// 
/// This structure stores the parameters that define a two-segment linear price curve.
/// The curve provides higher prices at low supply (shoulder) and more gradual price
/// increases at higher supply (tail), creating favorable conditions for early participants
/// while maintaining sustainable economics at scale.
/// 
/// # Curve Equation
/// ```text
/// if x < x2 (shoulder region):
/// price = floor + m1 * x
/// else (tail region):
/// price = floor + m2 * x + b2
/// ```
/// 
/// # Parameters
/// - `floor`: Minimum price guarantee
/// - `m1`: Shoulder slope (typically steeper)
/// - `m2`: Tail slope (typically gentler)
/// - `x2`: Transition point from shoulder to tail
/// - `b2`: Y-intercept adjustment for tail segment continuity
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct LinearPriceCurveSerialized {
    /// Minimum price floor for the token (serialized Decimal).
    /// Price cannot fall below this value regardless of supply.
    pub floor: [u8; 16],
    /// Slope of the shoulder segment (m1, serialized Decimal).
    /// Steeper initial slope providing higher prices at low supply.
    pub m1: [u8; 16],
    /// Slope of the main segment (m2, serialized Decimal).
    /// Gentler slope for bulk of the curve after shoulder point.
    pub m2: [u8; 16],
    /// X-coordinate where shoulder transitions to main slope (supply units).
    /// Defines the breakpoint between steep and gentle price curves.
    pub x2: u64,
    /// Y-intercept of the main segment (b2, serialized Decimal).
    /// Determines vertical offset of the main price curve.
    pub b2: [u8; 16],
}

/// Bitfield structure managing market operation permissions.
/// 
/// Uses a compact 16-bit representation where each bit corresponds to a specific
/// market operation. This allows for efficient storage and checking of multiple
/// permissions simultaneously. All permissions default to enabled (0xFFFF) for
/// new markets.
/// 
/// # Permission Management
/// - Individual bits can be toggled without affecting others
/// - Permissions are checked before each corresponding operation
/// - Failed permission checks return specific error codes for debugging
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MarketPermissions {
    /// Bitfield value storing all permission flags.
    /// Each bit represents a different permission from the MarketPermission enum.
    pub val: u16,
}

/// Configuration for Dutch auction fee boost mechanism.
/// 
/// Implements a time-decaying fee boost that increases trading fees immediately
/// after market launch, gradually decreasing to normal fees over the auction duration.
/// This mechanism incentivizes early liquidity provision and helps with price discovery.
/// 
/// # Auction Mechanics
/// The boost follows an exponential decay curve:
/// - Maximum fee boost (`init_boost`) at t=0 (market launch)
/// - Boost value is added directly to the base_fee: `effective_fee = base_fee + boost`
/// - Gradually decreases over `duration` seconds
/// - Curvature parameter controls the decay shape
/// - Boost reaches 0 after duration expires
/// - Effective fee is capped to stay in range [0, 1.0) - strictly less than 100%
/// 
/// # Safety
/// All float parameters are validated to prevent NaN, infinity, and overflow conditions
/// that could compromise market operations. init_boost must be in range [0, 1.0).
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct DutchConfigSerialized {
    /// Initial fee boost value at market launch (added directly to base_fee).
    /// Must be in range [0, 1.0) and gradually decays to 0 over the auction duration.
    /// Example: init_boost = 0.10 means add 10% to the base fee during initial trading.
    pub init_boost: f64,
    /// Duration of the Dutch auction in seconds.
    /// After this period, the boost reaches 0 and normal pricing applies.
    pub duration: u32,
    /// Curvature parameter controlling the decay rate of the boost.
    /// Higher values create steeper initial drops and slower final decay.
    pub curvature: f64,
}

/// Serialized representation of a single linear segment in a multi-segment curve.
/// 
/// Each segment defines a linear price function over a specific supply range,
/// with seamless transitions to adjacent segments ensuring price continuity.
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct SegmentSerialized {
    /// Starting X-coordinate of this segment (serialized Decimal).
    /// Represents the supply level where this segment begins.
    pub start: [u8; 16],
    /// Ending X-coordinate of this segment (serialized Decimal).
    /// Represents the supply level where this segment ends.
    pub end: [u8; 16],
    /// Slope of this linear segment (serialized Decimal).
    /// Determines how quickly price changes with supply in this range.
    pub m: [u8; 16],
    /// Y-intercept of this segment (serialized Decimal).
    /// Base price offset for the linear equation y = mx + b.
    pub b: [u8; 16],
}

/// Serialized representation of a multi-segment bonding curve with adaptive complexity.
/// 
/// This structure enables sophisticated price curves that can evolve over time while
/// maintaining important invariants like area-under-curve preservation. The curve
/// consists of an initial shoulder region, optional middle segments, and a final
/// tail segment extending to maximum supply.
/// 
/// # Curve Evolution
/// The curve starts simple (shoulder + tail) but gains complexity when:
/// - Floor price is raised (adds middle segments)
/// - Market conditions require price curve adjustments
/// - Area preservation constraints need to be maintained
/// 
/// # Segment Organization
/// 1. Implicit shoulder: [0, shoulder_end] with slope = final_segment.m * shoulder_slope_scalar
/// 2. Middle segments: Variable-length array for intermediate price regions
/// 3. Final segment: Extends from last middle segment (or shoulder) to u64::MAX
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MultiPriceCurveSerialized {
    /// Minimum price floor for the token (serialized Decimal).
    /// Price cannot fall below this value regardless of supply.
    pub floor_height: [u8; 16],
    /// Multiplier for shoulder slope relative to neighboring segment (serialized Decimal).
    /// Creates steeper initial pricing for early adopters.
    pub shoulder_slope_scalar: [u8; 16],
    /// Variable-length array of middle curve segments.
    /// Empty for simple curves, populated when floor is raised.
    pub middle_segments: Vec<SegmentSerialized>,
    /// The main segment extending to maximum supply (u64::MAX).
    /// Defines the long-tail pricing behavior of the market.
    pub final_segment: SegmentSerialized,
}

/// Dynamic state tracking for market operations and accounting.
/// 
/// MarketState maintains all mutable values that change during market operations,
/// separate from the static configuration in MarketMeta and the price curve parameters.
/// This separation allows for efficient state updates without modifying larger structures.
/// 
/// # State Components
/// - **Token Supply**: Total minted tokens in circulation
/// - **Cash Liquidity**: Available main token (e.g., USDC) for operations
/// - **Debt**: Total borrowed amount across all positions
/// - **Collateral**: Total deposited tokens used as collateral
/// - **Revenue**: Cumulative fees collected for market group and tenant
/// 
/// # Accounting Invariants
/// The state maintains several important invariants:
/// - Token supply reflects actual minted tokens
/// - Cash liquidity equals vault balance minus outstanding debt
/// - Total debt equals sum of all individual position debts
/// - Total collateral equals sum of all position collateral deposits
/// 
/// # Revenue Distribution
/// Fees collected from market operations are tracked separately for:
/// - Market group admin (receives majority of fees)
/// - Tenant platform (receives platform fee percentage)
#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MarketState {
    /// Total supply of tokens minted by this market.
    /// Increases when users buy tokens, decreases when tokens are sold back.
    pub token_supply: u64,
    /// Total amount of main token (cash) held in the market's liquidity vault.
    /// Represents available liquidity for sells and borrows.
    pub total_cash_liquidity: u64,
    /// Total outstanding debt across all borrowers in this market.
    /// Sum of all individual borrow positions.
    pub total_debt: u64,
    /// Total token collateral deposited across all positions in this market.
    /// Sum of all individual collateral deposits.
    pub total_collateral: u64,
    /// Cumulative revenue earned by the market group (in main token units).
    /// Tracks total fees collected for the market group admin.
    pub cumulative_revenue_market: u128,
    /// Cumulative revenue earned by the tenant (in main token units).
    /// Tracks platform fees collected for the tenant.
    pub cumulative_revenue_tenant: u128,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub enum MultiMarketInitValidationError {
    ShoulderSlopeScalarNotGreaterThanOne,
    ShoulderSlopeScalarNotFinite,
    MainSlopeNotPositive,
    MainSlopeNotFinite,
    FloorNotPositive,
    FloorNotFinite,
    DutchConfigValidationError(/* Complex fields */),
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub enum MarketLinearInitValidationError {
    M2MustBeGreaterThanZero,
    M1MustBeGreaterThanM2,
    FMustBeGreaterThanZero,
    InvalidCurveParameters,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub enum FeeBoundsError {
    GreaterThanOne,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub enum SetFeeError {
    NegativeFee,
    GreaterThanOne,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub enum MarketPermission {
    CanBuy,
    CanSell,
    CanBorrow,
    CanRepay,
    CanMintOptions,
    CanExerciseOptions,
    CanRaiseFloor,
    CanDepositCollateral,
    CanWithdrawCollateral,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub enum DutchConfigValidationError {
    InitBoostNotPositive,
    CurvatureZero,
    CurvatureNegative,
    InitBoostInfinity,
    InitBoostNaN,
    CurvatureInfinity,
    CurvatureNaN,
    InitBoostTooLarge,
    CurvatureTooLarge,
    DurationZero,
    CBProductOverflow,
    InvalidParameters,
}

#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub enum FullOrPartialU64 {
    Full,
    Partial(u64),
}

pub type MicroBasisPoints = u32;

// Event structures
#[event]
pub struct BorrowEvent {
    /// Fee amount allocated to the market group admin (in main token units).
    /// Part of the total borrow fee after platform fee deduction.
    pub fee_market_group: u64,
    /// Platform fee amount allocated to the tenant (in main token units).
    /// Calculated as a percentage of the total borrow fee.
    pub fee_tenant: u64,
    /// Net amount of main tokens received by the borrower after fees.
    /// This is the actual amount transferred to the borrower's account.
    pub net_cash_out: u64,
    /// New debt balance for the personal position
    pub new_debt: u64,
    /// Owner of the personal position account
    pub personal_position_owner: Pubkey,
    /// Address of the personal position account
    pub personal_position_address: Pubkey,
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct BuyEvent {
    /// The account that purchased tokens from the market.
    pub trader: Pubkey,
    /// Amount of market tokens minted and sent to the trader.
    pub token_out: u64,
    /// Amount of main tokens paid by the trader (excluding fees).
    /// This is the amount that went into the liquidity pool.
    pub net_cash_in: u64,
    /// Fee amount allocated to the market group admin (in main token units).
    pub fee_market_group: u64,
    /// Platform fee amount allocated to the tenant (in main token units).
    pub fee_tenant: u64,
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct BuyWithExactCashInAndDepositWithDebtEvent {
    /// The owner of the personal position (who is also the trader in this case)
    pub personal_position_owner: Pubkey,
    /// The personal position account
    pub personal_position: Pubkey,
    /// The account that provided cash for the purchase
    pub trader: Pubkey,
    /// The net cash spent (after fees, including debt used in purchase - market volume)
    pub net_cash_spent: u64,
    /// The total cash in from the trader (amount deducted from trader's account)
    pub trader_cash_spend: u64,
    /// The new acquired debt
    pub newly_acquired_debt: u64,
    /// The number of tokens purchased and deposited as collateral
    pub token_out: u64,
    /// New collateral balance in the personal position after deposit
    pub new_personal_position_collateral: u64,
    /// New debt balance in the personal position after borrowing
    pub new_personal_position_debt: u64,
    /// Borrow fee allocated to the market group admin (in main token units)
    pub fee_market_group_borrow: u64,
    /// Buy fee allocated to the market group admin (in main token units)
    pub fee_market_group_buy: u64,
    /// Borrow fee allocated to the tenant platform (in main token units)
    pub fee_platform_borrow: u64,
    /// Buy fee allocated to the tenant platform (in main token units)
    pub fee_platform_buy: u64,
    /// Market state snapshot at the time of the transaction
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct DepositEvent {
    /// The account that paid for and transferred the market tokens being deposited as collateral.
    pub payer: Pubkey,
    /// The address of the personal position account receiving the deposited collateral.
    pub personal_position_address: Pubkey,
    /// Amount of market tokens deposited as collateral into the personal position.
    /// These tokens are transferred to the position's escrow account.
    pub amount: u64,
    /// The new collateral balance of the personal position after the deposit.
    /// This will be greater than the previous balance by the deposited amount.
    pub new_balance: u64,
    /// Snapshot of the market state after the deposit transaction.
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct ExerciseOptionsEvent {
    /// The account that exercised the options.
    pub owner: Pubkey,
    /// Number of option tokens exercised (and market tokens received).
    pub amount: u64,
    /// Platform fee amount allocated to the tenant (in main token units).
    pub fee_tenant: u64,
    /// Fee amount allocated to the market group admin (in main token units).
    pub fee_market_group: u64,
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct RedeemAtFloorEvent {
    /// The account that redeemed tokens at floor price.
    pub trader: Pubkey,
    /// Amount of market tokens burned for redemption.
    /// These tokens are exchanged at the floor price rate.
    pub token_in: u64,
    /// Platform fee amount allocated to the tenant (in main token units).
    pub fee_platform: u64,
    /// Fee amount allocated to the market group admin (in main token units).
    pub fee_market_group: u64,
    /// Net amount of main tokens received by the trader after fees.
    /// Calculated as: token_in * floor_price - total_fees.
    pub net_cash_out: u64,
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct RepayEvent {
    /// The account that provided main tokens to repay the debt.
    /// This may be the position owner or another authorized party.
    pub repayer: Pubkey,
    /// The owner of the personal position whose debt is being repaid.
    pub personal_position_owner: Pubkey,
    /// The address of the personal position account that had its debt reduced.
    pub personal_position_address: Pubkey,
    /// Amount of main tokens used to repay debt.
    /// This amount is transferred from the repayer to the market's liquidity pool.
    pub amount: u64,
    /// The new debt balance of the personal position after repayment.
    /// This will be less than the previous debt by the repaid amount (minus any accrued interest).
    pub new_debt: u64,
    /// Snapshot of the market state after the repayment transaction.
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct SellWithExactTokenInEvent {
    /// The account that sold tokens back to the market.
    pub trader: Pubkey,
    /// Amount of market tokens burned in the sale.
    pub token_in: u64,
    /// Amount of main tokens received by the trader after fees.
    /// This is the net amount transferred to the trader.
    pub actual_cash_out: u64,
    /// Platform fee amount allocated to the tenant (in main token units).
    pub fee_platform: u64,
    /// Fee amount allocated to the market group admin (in main token units).
    pub fee_market_group: u64,
    /// The market state snapshot at the time of the sell
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct WithdrawEvent {
    /// The owner of the personal position making the withdrawal.
    pub personal_position_owner: Pubkey,
    /// The address of the personal position account from which collateral is being withdrawn.
    pub personal_position_address: Pubkey,
    /// Amount of market tokens being withdrawn from the position's collateral.
    /// These tokens are transferred from the position's escrow to the user's destination account.
    pub amount: u64,
    /// The new collateral balance of the personal position after withdrawal.
    /// This will be less than the previous balance by the withdrawn amount.
    pub new_balance: u64,
    /// Snapshot of the market state after the withdrawal transaction.
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct WithdrawSellAndRepayEvent {
    /// The owner of the personal position (who is also the trader in this case)
    pub personal_position_owner: Pubkey,
    /// The address of the personal position
    pub personal_position_address: Pubkey,
    /// The fee to the platform (from selling)
    pub fee_to_platform: u64,
    /// The fee to the market group (from selling)
    pub fee_to_market_group: u64,
    /// Cash to user (not including fees)
    pub cash_to_user: u64,
    /// The amount of collateral sold
    pub collateral_sold: u64,
    /// The amount of debt repaid
    pub debt_repaid: u64,
    /// The new collateral balance in the personal position
    pub new_personal_position_collateral_balance: u64,
    /// The new debt balance in the personal position
    pub new_personal_position_debt_balance: u64,
    /// The market state snapshot after the trade
    pub market_state_snapshot: MarketStateSnapshot,
}

#[event]
pub struct DonateLiquidityEvent {
    /// The account that donated liquidity to the market.
    pub payer: Pubkey,
    /// The market metadata account that received the donation.
    pub market_meta: Pubkey,
    /// Total cash balance in the market after the donation.
    /// This increased liquidity may enable floor price increases.
    pub new_cash_balance: u64,
    /// Amount of main tokens donated to the market's liquidity pool.
    pub amount: u64,
}

#[event]
pub struct MarketLinearInitEvent {
    /// The market metadata account that stores configuration and references to all associated token accounts.
    /// This account holds information about the market's tokens, vaults, revenue escrows, and permissions.
    pub market_meta: Pubkey,
    /// The market state account that stores the linear price curve parameters and market state.
    /// This account contains the mathematical definition of the pricing curve (floor, slopes, shoulder) and tracks supply/collateral/debt.
    pub market_state: Pubkey,
    /// The market group that owns this market.
    /// The market inherits fee configuration from the market group and distributes revenue to the group admin.
    pub group: Pubkey,
}

#[event]
pub struct RaiseFloorFromExcessLiquidity2Event {
    /// The market metadata account where the floor was raised.
    pub market_meta: Pubkey,
    pub prev_floor: DecimalSerialized,
    /// New minimum price floor after utilizing excess liquidity (serialized Decimal).
    /// Raised proportionally based on available excess liquidity in the market.
    pub new_floor: DecimalSerialized,
    /// Area under the curve after the floor raise
    pub new_area_under_curve: u64,
    /// Area under the curve before the floor raise
    pub prev_area_under_curve: u64,
    /// cash + debt (ie, the max area under the curve)
    pub total_liquidity: u64,
}

#[event]
pub struct RaiseFloorFromExcessLiquidityEvent {
    /// The market metadata account where the floor was raised.
    pub market_meta: Pubkey,
    /// New minimum price floor after utilizing excess liquidity (serialized Decimal).
    /// Raised proportionally based on available excess liquidity in the market.
    pub new_floor: DecimalSerialized,
    /// Area under the price curve up to current supply after raising the floor.
    /// Measured in token units and represents the total value locked in the curve.
    pub new_area_under_curve: u64,
}

#[event]
pub struct RaiseFloorFromTriggerEvent {
    /// The market metadata account where the floor was raised.
    pub market_meta: Pubkey,
    /// New minimum price floor for the token (serialized Decimal).
    /// Price cannot fall below this value after the adjustment.
    pub new_floor: DecimalSerialized,
    /// New X-coordinate where the shoulder segment ends (supply units).
    /// Determines the transition point between price curve segments.
    pub new_shoulder_end: u64,
    /// Area under the price curve after the floor raise.
    /// Represents total liquidity backing up to current supply.
    pub new_area: u64,
    /// Area under the price curve before the floor raise.
    /// Used to verify the operation maintained proper backing.
    pub prev_area: u64,
}

#[event]
pub struct RaiseFloorPreserveAreaChecked2Event {
    /// The market metadata account where the floor was raised.
    pub market_meta: Pubkey,
    /// New minimum price floor after the adjustment (serialized Decimal).
    pub new_floor: DecimalSerialized,
    /// New X-coordinate where the shoulder segment ends (supply units).
    pub new_shoulder_end: u64,
    /// Resulting liquidity buffer ratio after the floor raise (serialized Decimal).
    pub new_liq_ratio: DecimalSerialized,
    /// Area under the price curve up to current supply before raising the floor.
    /// Measured in token units and represents the integral of the price curve from 0 to supply.
    pub prev_area: u64,
    /// Area under the price curve up to current supply after raising the floor.
    /// Should not shrink by more than the maximum allowed tolerance to prevent excessive value extraction.
    pub new_area: u64,
}

#[event]
pub struct RaiseFloorPreserveAreaCheckedEvent {
    /// New minimum price floor after the adjustment (serialized Decimal).
    /// Calculated as: old_floor * (1 + floor_increase_ratio).
    pub new_floor: DecimalSerialized,
    /// New X-coordinate where the shoulder segment ends (supply units).
    /// Must be greater than the previous shoulder end to maintain curve validity.
    pub new_shoulder_end: u64,
    /// Resulting liquidity buffer ratio after the floor raise (serialized Decimal).
    /// Ratio of excess liquidity to required liquidity, must meet minimum threshold.
    pub new_liq_ratio: DecimalSerialized,
}

#[event]
pub struct MarketFlagsChangeEvent {
    /// The market metadata account whose permissions were changed.
    pub market_meta: Pubkey,
    /// New permission flags controlling market operations.
    /// Determines which operations (buy, sell, borrow, etc.) are allowed.
    pub new_flags: MarketPermissions,
}

#[event]
pub struct MarketGroupAcceptNewAdminEvent {
    /// The market group account whose admin was transferred.
    pub market_group: Pubkey,
    /// The new admin public key that accepted ownership.
    /// This account now has full control over the market group.
    pub new_admin: Pubkey,
}

#[event]
pub struct MarketGroupChangeFeesEvent {
    /// The market group account whose fees were updated.
    pub market_group: Pubkey,
    /// New fee structure for all markets in this group.
    /// Contains updated buy, sell, borrow, and exercise option fee rates.
    pub new_fees: Fees,
}

#[event]
pub struct MarketGroupCollectRevEvent {
    /// The market metadata account from which revenue was collected.
    pub market_meta: Pubkey,
    /// Amount of revenue collected (in main token units).
    /// This represents accumulated fees from market operations.
    pub amount: u64,
    /// The destination token account that received the revenue.
    pub to: Pubkey,
}

#[event]
pub struct MarketGroupInitialized {
    /// The tenant account that owns this market group.
    pub tenant: Pubkey,
    /// The seed public key used to derive the market group's PDA address.
    pub market_group_seed: Pubkey,
    /// The admin public key with control over this market group.
    pub group_admin: Pubkey,
    /// Fee configuration for all markets in this group.
    /// Contains buy, sell, borrow, and exercise option fee rates.
    pub fees: Fees,
}

#[event]
pub struct MarketGroupProposeAdminEvent {
    /// The market group account for which a new admin was proposed.
    pub market_group: Pubkey,
    /// The proposed new admin public key.
    /// Must be accepted by this account to complete the transfer.
    pub new_admin: Pubkey,
}

#[event]
pub struct MintOptionsEvent {
    /// The market metadata account for which options were minted.
    pub market_meta: Pubkey,
    /// The destination token account that received the minted options.
    pub options_dst: Pubkey,
    /// Number of option tokens minted.
    /// These can later be exercised to purchase market tokens.
    pub amount: u64,
}

#[event]
pub struct PersonalPositionInitEvent {
    /// The market metadata account this position is associated with.
    pub market_meta: Pubkey,
    /// The account that paid for creating the position accounts.
    pub payer: Pubkey,
    /// The owner public key who will control this position.
    pub owner: Pubkey,
    /// The newly created personal position account address.
    pub personal_position: Pubkey,
}

#[event]
pub struct TenantAcceptNewAdminEvent {
    /// The tenant account whose admin was transferred.
    pub tenant: Pubkey,
    /// The new admin public key that accepted ownership.
    /// This account now has full control over the tenant.
    pub new_admin: Pubkey,
}

#[event]
pub struct TenantChangeFeeMbpsEvent {
    /// The tenant account whose fee was changed.
    pub tenant: Pubkey,
    /// The new fee in micro basis points.
    pub fee_micro_bps: u32,
}

#[event]
pub struct TenantCollectRevEvent {
    /// The market metadata account associated with the revenue collection.
    pub market_meta: Pubkey,
    /// Amount of platform revenue collected (in main token units).
    /// This represents accumulated platform fees from market operations.
    pub amount: u64,
    /// The destination token account that received the platform revenue.
    pub to: Pubkey,
}

#[event]
pub struct TenantInitialized {
    /// The seed public key used to derive the tenant's PDA address.
    pub tenant_seed: Pubkey,
    /// The admin public key with control over this tenant.
    pub admin: Pubkey,
    /// Platform fee rate in micro basis points (1 micro bp = 0.0001%).
    /// This fee is taken from all market operations under this tenant.
    pub fee_micro_bps: u32,
    /// Whether market groups can be created without tenant admin approval.
    /// If true, anyone can create market groups under this tenant.
    pub permissionless_group_creation: bool,
}

#[event]
pub struct TenantProposeAdminEvent {
    /// The tenant account for which a new admin was proposed.
    pub tenant: Pubkey,
    /// The proposed new admin public key.
    /// Must be accepted by this account to complete the transfer.
    pub new_admin: Pubkey,
}

#[event]
pub struct TestLogEvent {
    pub payer: Pubkey,
    pub log_account: Pubkey,
    pub data: u64,
}