strata-public-contract 0.2.1

Shared Rust types for Strata markets and Sonar quotes.
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
//! Public SDK 2.0 request and response primitives.

use serde::{Deserialize, Serialize};

use crate::{CapabilityRisk, McpExposure};

pub const PLATFORM_SCHEMA_VERSION: u16 = 2;
pub const PLATFORM_CONTRACT_VERSION: &str = "2.0";
pub const PLATFORM_ACTION_GRAPH: &str = include_str!("../fixtures/v2/platform-action-graph.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_SERVICE_STATUS_FIXTURE: &str =
    include_str!("../fixtures/v2/platform-status.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_CAPABILITIES_FIXTURE: &str =
    include_str!("../fixtures/v2/platform-capabilities.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ASSETS_FIXTURE: &str = include_str!("../fixtures/v2/assets.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_SWAP_QUOTE_FIXTURE: &str = include_str!("../fixtures/v2/swap-quote.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_MARKETS_FIXTURE: &str = include_str!("../fixtures/v2/markets.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_BOOK_FIXTURE: &str = include_str!("../fixtures/v2/book.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_BBO_FIXTURE: &str = include_str!("../fixtures/v2/bbo.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_FEES_FIXTURE: &str = include_str!("../fixtures/v2/fees.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_STATUS_FIXTURE: &str = include_str!("../fixtures/v2/status.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_CANDLES_FIXTURE: &str = include_str!("../fixtures/v2/candles.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_MARK_FIXTURE: &str = include_str!("../fixtures/v2/mark.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_EXECUTION_STATUS_FIXTURE: &str =
    include_str!("../fixtures/v2/execution-status.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_TWAPS_FIXTURE: &str = include_str!("../fixtures/v2/twaps.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_TWAP_CHALLENGE_FIXTURE: &str =
    include_str!("../fixtures/v2/twap-challenge.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_TWAP_PREPARE_FIXTURE: &str = include_str!("../fixtures/v2/twap-prepare.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_TWAP_SUBMIT_FIXTURE: &str = include_str!("../fixtures/v2/twap-submit.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_PORTFOLIO_HISTORY_FIXTURE: &str =
    include_str!("../fixtures/v2/portfolio-history.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_PORTFOLIO_FIXTURE: &str = include_str!("../fixtures/v2/portfolio.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_REWARDS_FIXTURE: &str = include_str!("../fixtures/v2/rewards.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_REFERRALS_FIXTURE: &str = include_str!("../fixtures/v2/referrals.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_REFERRAL_LINK_FIXTURE: &str = include_str!("../fixtures/v2/referral-link.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_REFERRAL_CLAIM_FIXTURE: &str =
    include_str!("../fixtures/v2/referral-claim.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_VAULT_STATUS_FIXTURE: &str = include_str!("../fixtures/v2/vault-status.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_VAULT_PAUSE_PREPARE_FIXTURE: &str =
    include_str!("../fixtures/v2/vault-pause-prepare.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_VAULT_SETUP_PREPARE_FIXTURE: &str =
    include_str!("../fixtures/v2/vault-setup-prepare.json");
pub const PLATFORM_VAULT_DELEGATE_PREPARE_FIXTURE: &str =
    include_str!("../fixtures/v2/vault-delegate-prepare.json");
pub const PLATFORM_VAULT_POLICY_PREPARE_FIXTURE: &str =
    include_str!("../fixtures/v2/vault-policy-prepare.json");
pub const PLATFORM_VAULT_DEPOSIT_PREPARE_FIXTURE: &str =
    include_str!("../fixtures/v2/vault-deposit-prepare.json");
pub const PLATFORM_VAULT_WITHDRAW_PREPARE_FIXTURE: &str =
    include_str!("../fixtures/v2/vault-withdraw-prepare.json");
pub const PLATFORM_VAULT_SUBMIT_FIXTURE: &str = include_str!("../fixtures/v2/vault-submit.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_BUGS_FIXTURE: &str = include_str!("../fixtures/v2/bugs.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_BUG_SUBMIT_FIXTURE: &str = include_str!("../fixtures/v2/bug-submit.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_TRADES_FIXTURE: &str = include_str!("../fixtures/v2/trades.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ACCOUNT_FIXTURE: &str = include_str!("../fixtures/v2/account.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_MAKER_REPUTATION_FIXTURE: &str =
    include_str!("../fixtures/v2/maker-reputation.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_MAKER_STATUS_FIXTURE: &str = include_str!("../fixtures/v2/maker-status.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_MAKER_STREAM_FIXTURE: &str = include_str!("../fixtures/v2/maker-stream.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_TWAP_STREAM_FIXTURE: &str = include_str!("../fixtures/v2/twap-stream.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_EXECUTION_STREAM_FIXTURE: &str =
    include_str!("../fixtures/v2/execution-stream.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_CHALLENGE_FIXTURE: &str =
    include_str!("../fixtures/v2/order-challenge.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_PREPARE_FIXTURE: &str = include_str!("../fixtures/v2/order-prepare.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_SUBMIT_FIXTURE: &str = include_str!("../fixtures/v2/order-submit.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_STATUS_FIXTURE: &str = include_str!("../fixtures/v2/order-status.json");

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionSource {
    ExternalAgentOwner,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SigningLocation {
    External,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAuthority {
    pub permission_source: PermissionSource,
    pub signing_location: SigningLocation,
    pub accepts_private_keys: bool,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformTransport {
    Http,
    Websocket,
    Mcp,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMarketState {
    Active,
    ReadOnly,
    QuoteOnly,
    CancelOnly,
    Paused,
    Warming,
    Degraded,
    Unavailable,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderState {
    Created,
    Accepted,
    Open,
    PartiallyFilled,
    Filled,
    CancelPending,
    Cancelled,
    Expired,
    Rejected,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformSettlementState {
    NotApplicable,
    Pending,
    Confirmed,
    Failed,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformPublicErrorCode {
    InvalidRequest,
    UnsupportedCapability,
    MarketUnavailable,
    MarketWarming,
    QuoteUnavailable,
    QuoteExpired,
    PriceBoundFailed,
    InsufficientBalance,
    PolicyRejected,
    SessionExpired,
    SequenceConflict,
    DuplicateClientId,
    OrderRejected,
    OrderNotFound,
    CancelTooLate,
    SelfTradePrevented,
    DeadManExpired,
    RateLimited,
    TemporarilyUnavailable,
    SubmissionAmbiguous,
    SettlementPending,
    SettlementFailed,
}

/// Exact asset amount. Public money never crosses the contract as a float.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ExactAmount {
    pub asset_id: String,
    pub atoms: String,
}

/// Sequence metadata shared by all recoverable state streams.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SequenceEnvelope {
    pub stream_id: String,
    pub sequence: String,
    pub previous_sequence: Option<String>,
    pub server_time_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot_id: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PageRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PageInfo {
    pub next_cursor: Option<String>,
    pub has_more: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PublicOperationError {
    pub code: PlatformPublicErrorCode,
    pub message: String,
    pub retryable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_ms: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation_id: Option<String>,
}

/// One operation currently callable through the live v2 gateway.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LivePlatformCapability {
    pub id: String,
    pub risk: CapabilityRisk,
    pub required_scope: String,
    pub transports: Vec<PlatformTransport>,
    pub mcp_exposure: McpExposure,
}

/// Operations currently available to the client.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformDiscoveryResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub authority: PlatformAuthority,
    pub capabilities: Vec<LivePlatformCapability>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformServiceState {
    Operational,
    Degraded,
}

/// Product-level readiness without leaking private implementation details.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformServiceStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub status: PlatformServiceState,
    pub available_operations: u32,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformActionKind {
    Discovery,
    Read,
    Prepare,
    ExternalSignature,
    Submit,
    Receipt,
    Stream,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformGraphRelation {
    pub from: String,
    pub to: String,
    pub kind: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformGraphModule {
    pub id: String,
    pub client_property: String,
    pub capability_ids: Vec<String>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOperationTransport {
    pub transport: PlatformTransport,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool: Option<String>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOperation {
    pub id: String,
    pub capability_id: String,
    pub kind: PlatformActionKind,
    pub summary: String,
    pub transports: Vec<PlatformOperationTransport>,
    pub available: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformWorkflowNode {
    pub id: String,
    pub kind: PlatformActionKind,
    pub capability_id: Option<String>,
    pub operation_ids: Vec<String>,
    pub available: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformWorkflowEdge {
    pub from: String,
    pub to: String,
    pub condition: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformWorkflow {
    pub id: String,
    pub entry_node: String,
    pub nodes: Vec<PlatformWorkflowNode>,
    pub edges: Vec<PlatformWorkflowEdge>,
}

/// Complete customer-safe product graph. Static package support is projected
/// against live capability discovery before this response is served.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformActionGraphResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub graph_version: String,
    pub entry_operation_id: String,
    pub authority: PlatformAuthority,
    pub entities: Vec<String>,
    pub relations: Vec<PlatformGraphRelation>,
    pub modules: Vec<PlatformGraphModule>,
    pub operations: Vec<PlatformOperation>,
    pub workflows: Vec<PlatformWorkflow>,
}

impl PlatformActionGraphResponse {
    pub fn foundation() -> Self {
        serde_json::from_str(PLATFORM_ACTION_GRAPH)
            .expect("embedded platform action graph must be valid")
    }

    /// Live discovery is the authority. Package support alone never makes a
    /// callable operation or workflow node available.
    pub fn project_availability(
        &mut self,
        live_capability_ids: &std::collections::BTreeSet<String>,
    ) {
        for operation in &mut self.operations {
            operation.available = live_capability_ids.contains(&operation.capability_id);
        }
        for workflow in &mut self.workflows {
            for node in &mut workflow.nodes {
                node.available = node
                    .capability_id
                    .as_ref()
                    .is_none_or(|capability_id| live_capability_ids.contains(capability_id));
            }
        }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformNetwork {
    Solana,
}

/// Asset identity used by ordinary SDK operations.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAsset {
    pub asset_id: String,
    pub symbol: String,
    pub name: String,
    pub decimals: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo_url: Option<String>,
    pub network: PlatformNetwork,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAssetsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub assets: Vec<PlatformAsset>,
    pub page: PageInfo,
}

/// Exact-input asset swap request. Asset identifiers come from
/// [`PlatformAssetsResponse`]; implementation-specific identifiers are not
/// part of this contract.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformSwapQuoteRequest {
    pub input_asset_id: String,
    pub output_asset_id: String,
    pub amount_in_atoms: String,
    #[serde(default)]
    pub maximum_tolerance_bps: u16,
}

/// Short-lived customer economics for an exact-input asset swap.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformSwapQuoteResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub quote_id: String,
    pub server_time_ms: u64,
    pub expires_at_ms: u64,
    pub input_asset_id: String,
    pub output_asset_id: String,
    pub amount_in_atoms: String,
    pub amount_in_consumed_atoms: String,
    pub amount_out_atoms: String,
    pub minimum_output_atoms: String,
    pub input_fee_atoms: String,
    pub output_fee_atoms: String,
    pub maximum_tolerance_bps: u16,
    pub reference_price: String,
    pub price_impact_pct: String,
    pub provider: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMarketAction {
    Quote,
    ExecuteImmediate,
    PlaceOrder,
    ScheduleTwap,
}

/// Stable market metadata for public SDK operations.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMarket {
    pub market_id: String,
    pub label: String,
    pub base_asset_id: String,
    pub quote_asset_id: String,
    pub status: PlatformMarketState,
    pub available_actions: Vec<PlatformMarketAction>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMarketsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub markets: Vec<PlatformMarket>,
    pub page: PageInfo,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBookLevel {
    /// Quote atoms per whole base unit, encoded as an unsigned decimal string.
    pub price_atoms: String,
    /// Available base quantity in base atoms, encoded as an unsigned decimal string.
    pub size_atoms: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformBookSide {
    Bid,
    Ask,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBookChange {
    pub side: PlatformBookSide,
    pub price_atoms: String,
    /// Zero removes the price level.
    pub size_atoms: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBookSnapshotResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub stream_id: String,
    pub sequence: String,
    pub server_time_ms: u64,
    pub snapshot_id: String,
    pub bids: Vec<PlatformBookLevel>,
    pub asks: Vec<PlatformBookLevel>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBestBidAskResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub stream_id: String,
    pub sequence: String,
    pub server_time_ms: u64,
    pub best_bid: Option<PlatformBookLevel>,
    pub best_ask: Option<PlatformBookLevel>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformFeeScheduleResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub passive_maker_fee_bps: u16,
    pub maximum_immediate_execution_fee_bps: u16,
    pub book_prices_include_trading_fees: bool,
    pub exact_fee_returned_by_quote: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMarketStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub status: PlatformMarketState,
    pub tick_size_atoms: String,
    pub minimum_order_size_atoms: String,
}

/// Decimal prices are strings so no SDK boundary silently rounds money.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformCandle {
    pub started_at_ms: u64,
    pub open_price: String,
    pub high_price: String,
    pub low_price: String,
    pub close_price: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformCandlesResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub resolution_seconds: u32,
    pub candles: Vec<PlatformCandle>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMarkResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub price_atoms_per_base_unit: Option<String>,
    pub quote_decimals: u8,
    pub stale: bool,
    pub age_ms: Option<u64>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformExecutionState {
    Prepared,
    Confirmed,
}

/// Recoverable immediate-execution receipt. Confirmed rows are journalled and
/// survive a market-service restart.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformExecutionStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub execution_id: String,
    pub market_id: String,
    pub status: PlatformExecutionState,
    pub signature: Option<String>,
    pub settlement: PlatformSettlementState,
    pub updated_at_ms: u64,
}

/// One watched immediate execution as the stream sees it: the same fields as
/// the recoverable HTTP receipt without the envelope.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformExecutionRow {
    pub execution_id: String,
    pub market_id: String,
    pub status: PlatformExecutionState,
    pub signature: Option<String>,
    pub settlement: PlatformSettlementState,
    pub updated_at_ms: u64,
}

/// Client frame for the execution stream: watch one or more opaque execution
/// handles issued by `execution.prepare` in this market.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformExecutionCommand {
    Watch { execution_ids: Vec<String> },
}

/// Sequenced execution stream (`execution.stream`) for one market. The client
/// opens the socket and sends a `watch` frame; the server answers with one
/// `executions_snapshot` for the watched handles, then `execution_update`
/// whenever a watched execution is prepared, confirmed on chain, or expires
/// unconfirmed, `execution_unknown` for handles this market never issued or
/// no longer remembers, and heartbeats. Later `watch` frames add handles and
/// produce update/unknown events for them.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformExecutionEvent {
    ExecutionsSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        executions: Vec<PlatformExecutionRow>,
        unknown_execution_ids: Vec<String>,
    },
    ExecutionUpdate {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        execution: PlatformExecutionRow,
    },
    ExecutionExpired {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        execution_id: String,
    },
    ExecutionUnknown {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        execution_id: String,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
    },
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformTwapState {
    Active,
    Completed,
    Cancelled,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwapFill {
    pub fill_id: String,
    pub size_atoms: String,
    pub price_atoms: String,
    pub gross_quote_atoms: String,
    pub base_fee_atoms: String,
    pub quote_fee_atoms: String,
    pub signature: Option<String>,
    pub observed_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwap {
    pub twap_id: String,
    pub side: PlatformTradeSide,
    pub status: PlatformTwapState,
    pub slices_total: u16,
    pub slices_executed: u16,
    pub interval_slots: u32,
    pub maximum_tolerance_bps: u16,
    pub limit_price_atoms: String,
    pub total_size_atoms: String,
    pub executed_size_atoms: String,
    pub gross_quote_executed_atoms: String,
    pub complete_execution_value: bool,
    pub created_at_ms: u64,
    pub completed_at_ms: Option<u64>,
    pub placed_signature: Option<String>,
    pub terminal_signature: Option<String>,
    pub fills: Vec<PlatformTwapFill>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwapsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub wallet_address: String,
    pub server_time_ms: u64,
    pub twaps: Vec<PlatformTwap>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformTwapControlAction {
    Place,
    Cancel,
}

/// Request exact authorization bytes for one Vault-owned TWAP action. The
/// external owner chooses the session signer; Strata never receives its key.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformTwapChallengeRequest {
    Place {
        owner_wallet: String,
        session_public_key: String,
        side: PlatformTradeSide,
        total_size_atoms: String,
        slices_total: u16,
        maximum_tolerance_bps: u16,
        /// Slots between slices. Slot time is a cluster parameter (400 ms
        /// today, stepping down to 200 ms under SIMD-0525), so a schedule
        /// expressed in slots runs faster in wall time as slots shorten.
        interval_slots: u32,
        limit_price_atoms: String,
    },
    Cancel {
        owner_wallet: String,
        session_public_key: String,
        twap_id: String,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwapChallengeResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub challenge_id: String,
    pub market_id: String,
    pub action: PlatformTwapControlAction,
    pub twap_id: String,
    pub authorization_payload_base64: String,
    pub server_time_ms: u64,
    pub expires_at_ms: u64,
}

/// A prepared TWAP challenge, signed: the two-step path.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwapPrepareAuthorization {
    pub challenge_id: String,
    /// Base58 Ed25519 signature over `authorization_payload_base64`.
    pub authorization_signature: String,
}

/// Prepare a TWAP-control transaction: a signed challenge (`Authorized`) or
/// the action itself (`Direct`, one signature — the transaction signature is
/// the authorization). The response is identical.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum PlatformTwapPrepareRequest {
    Authorized(PlatformTwapPrepareAuthorization),
    Direct(PlatformTwapChallengeRequest),
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwapPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub twap_control_id: String,
    pub market_id: String,
    pub action: PlatformTwapControlAction,
    pub twap_id: String,
    /// Backend-partially-signed transaction. The external session signer
    /// verifies and fills only its signature slot.
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub last_valid_block_height: u64,
    pub expires_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwapSubmitRequest {
    pub twap_control_id: String,
    pub signed_transaction_base64: String,
    pub idempotency_key: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTwapSubmitResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub twap_control_id: String,
    pub market_id: String,
    pub action: PlatformTwapControlAction,
    pub twap_id: String,
    pub signature: String,
    pub status: PlatformOrderSubmissionStatus,
}

/// Sequenced wallet-scoped TWAP progress stream (`algos.twap.stream`) for one
/// market. It starts with a `twaps_snapshot`, then sends one `twap_update`
/// carrying the complete sanitized TWAP row whenever a schedule is created,
/// executes a slice, or reaches a terminal state, plus heartbeats. Every event
/// carries the stream identity and previous sequence; a recovery snapshot
/// advances the sequence on the same identity.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
#[allow(clippy::large_enum_variant)]
pub enum PlatformTwapEvent {
    TwapsSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        twaps: Vec<PlatformTwap>,
    },
    TwapUpdate {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        twap: PlatformTwap,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
    },
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum PlatformPortfolioHistoryRange {
    #[serde(rename = "24h")]
    Day,
    #[serde(rename = "7d")]
    Week,
    #[serde(rename = "30d")]
    Month,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformPortfolioHistoryPoint {
    pub recorded_at_ms: u64,
    pub equity_usd_micros: String,
    pub available_usd_micros: String,
    pub locked_usd_micros: String,
    pub market_count: u32,
}

/// Stored account-equity history. It never fabricates data before collection
/// began and keeps all currency values in exact USD micros.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformPortfolioHistoryResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub wallet_address: String,
    pub server_time_ms: u64,
    pub range: PlatformPortfolioHistoryRange,
    pub points: Vec<PlatformPortfolioHistoryPoint>,
    pub collecting: bool,
    pub first_sample_ms: Option<u64>,
    pub last_sample_ms: Option<u64>,
}

/// One asset the owner holds on Strata, across every live market. Assets
/// with no holdings are omitted. A balance is a balance: `total` is what the
/// owner has, `available` is what is free to trade or withdraw, `locked` is
/// what resting orders reserve.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformPortfolioBalance {
    pub asset_id: String,
    /// Holdings not reserved by resting orders.
    pub available_atoms: String,
    /// Holdings reserved by resting orders.
    pub locked_atoms: String,
    /// `available_atoms + locked_atoms`.
    pub total_atoms: String,
    /// Exact USD micros for `total_atoms` when a fresh public mark exists.
    pub value_usd_micros: Option<String>,
}

/// The owner's Vault position in one live market. Only markets where the
/// Vault holds a market account are listed.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformPortfolioPosition {
    pub market_id: String,
    pub base_asset_id: String,
    pub quote_asset_id: String,
    pub base_available_atoms: String,
    pub base_locked_atoms: String,
    pub quote_available_atoms: String,
    pub quote_locked_atoms: String,
}

/// One open order, tagged with the market it rests in.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformPortfolioOrder {
    pub market_id: String,
    pub order_id: String,
    pub side: PlatformTradeSide,
    pub order_type: PlatformOrderType,
    pub state: PlatformOrderState,
    pub limit_price_atoms: String,
    pub original_size_atoms: String,
    pub remaining_size_atoms: String,
}

/// One recent fill, tagged with the market it happened in.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformPortfolioFill {
    pub market_id: String,
    pub fill_id: String,
    pub side: PlatformTradeSide,
    pub price_atoms: String,
    pub size_atoms: String,
    pub fee_quote_atoms: String,
    pub fee_is_final: bool,
    pub settlement: PlatformSettlementState,
    pub executed_at_ms: u64,
    pub confirmed_at_ms: Option<u64>,
    pub transaction_id: Option<String>,
    pub realized_pnl_quote_atoms: String,
}

/// The owner's whole account in one public read, by wallet address: balances,
/// per-market positions, open orders, and recent fills across every live
/// market, plus USD totals. No signature and no market selection is needed.
/// Amounts are exact atomic strings; USD totals are null whenever any held
/// asset lacks a fresh public mark, so a partial valuation is never presented
/// as complete.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformPortfolioResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub wallet_address: String,
    pub server_time_ms: u64,
    /// When the on-chain state behind this snapshot was observed.
    pub observed_at_ms: u64,
    /// Chain slot the snapshot was observed at.
    pub observed_slot: String,
    /// Live markets included in the snapshot.
    pub market_count: u32,
    pub balances: Vec<PlatformPortfolioBalance>,
    pub positions: Vec<PlatformPortfolioPosition>,
    /// Every open order across every live market.
    pub open_orders: Vec<PlatformPortfolioOrder>,
    /// Recent fills across every live market, newest first (bounded).
    pub recent_fills: Vec<PlatformPortfolioFill>,
    /// Markets whose orders and fills could not be read for this snapshot;
    /// balances and positions are still complete.
    pub unavailable_market_ids: Vec<String>,
    /// Sum of every balance's `value_usd_micros`; null unless the valuation is complete.
    pub equity_usd_micros: Option<String>,
    /// Exact USD value of every available balance; null unless the valuation is complete.
    pub available_usd_micros: Option<String>,
    /// `equity_usd_micros - available_usd_micros`; null unless the valuation is complete.
    pub locked_usd_micros: Option<String>,
    pub valuation_complete: bool,
    pub unpriced_asset_ids: Vec<String>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformVaultState {
    Absent,
    Active,
    Paused,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformVaultSessionState {
    Absent,
    Active,
    Expired,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformVaultWithdrawalMode {
    Unrestricted,
    Blocked,
    Restricted,
}

/// One asset-specific execution limit. A null maximum means that the session
/// is permitted to use the asset without a per-execution amount ceiling.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultSpendingLimit {
    pub asset_id: String,
    pub maximum_per_execution_atoms: Option<String>,
}

/// Sanitized state for the requested external session key. It intentionally
/// omits all construction accounts and price-source identities.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultSessionStatus {
    pub session_public_key: String,
    pub state: PlatformVaultSessionState,
    pub expires_at_ms: Option<u64>,
    pub permanent: bool,
    pub minimum_interval_seconds: u32,
    pub maximum_tolerance_bps: u16,
    pub last_execution_at_ms: Option<u64>,
    pub market_execution_ready: bool,
    pub price_protection_active: bool,
    pub spending_limits: Vec<PlatformVaultSpendingLimit>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultWithdrawalAccess {
    pub mode: PlatformVaultWithdrawalMode,
    pub allowed_wallet_addresses: Vec<String>,
}

/// Product-level Vault state for an owner and, when requested, one external
/// session key. Chain construction identities never cross this boundary.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub state: PlatformVaultState,
    pub session: Option<PlatformVaultSessionStatus>,
    pub withdrawal_access: PlatformVaultWithdrawalAccess,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultPausePrepareRequest {
    pub wallet_address: String,
    pub paused: bool,
}

/// An unsigned owner transaction. The external owner must verify its wallet
/// and requested state before signing and broadcasting it.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultPausePrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub paused: bool,
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub owner_signature_required: bool,
    /// Opaque handle for this prepared transaction. Hand it back with the
    /// owner-signed transaction to `vault.relay` and Strata submits it — no
    /// RPC or SOL needed on the owner side.
    pub preparation_id: String,
    /// `true` when Strata is the transaction fee payer and covers any rent the
    /// action creates, so the owner needs no SOL at all. `false` means the
    /// owner wallet is the fee payer (Strata still submits it on request).
    pub sponsored: bool,
    /// The prepared transaction must be submitted before this server time.
    pub submit_by_ms: u64,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformVaultSetupMode {
    Create,
    ReplaceSession,
}

/// Session policy applied when onboarding does not state one: at most one
/// execution per second per session, and a 1% maximum tolerance.
pub const PLATFORM_SESSION_DEFAULT_MINIMUM_INTERVAL_SECONDS: u32 = 1;
pub const PLATFORM_SESSION_DEFAULT_MAXIMUM_TOLERANCE_BPS: u16 = 100;
/// A session carries at most this many spending limits.
pub const PLATFORM_SESSION_MAX_SPENDING_LIMITS: usize = 4;

/// One-signature onboarding: only the wallet and the external session key are
/// required. One session then trades every market. Everything else is an
/// optional policy on top; absent values take the product defaults.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultSetupPrepareRequest {
    pub wallet_address: String,
    pub session_public_key: String,
    /// Optional. Names the market whose price protection the session pins
    /// when the product has one; the session trades every market either way.
    #[serde(default)]
    pub market_id: Option<String>,
    /// Null or absent requests the permanent-session expiry supported by the
    /// product.
    #[serde(default)]
    pub expires_at_ms: Option<u64>,
    /// Absent takes `PLATFORM_SESSION_DEFAULT_MINIMUM_INTERVAL_SECONDS`.
    #[serde(default)]
    pub minimum_interval_seconds: Option<u32>,
    /// Absent takes `PLATFORM_SESSION_DEFAULT_MAXIMUM_TOLERANCE_BPS`.
    #[serde(default)]
    pub maximum_tolerance_bps: Option<u16>,
    /// Optional per-asset ceilings, at most `PLATFORM_SESSION_MAX_SPENDING_LIMITS`.
    /// Assets without a limit are unlimited.
    #[serde(default)]
    pub spending_limits: Vec<PlatformVaultSpendingLimit>,
}

/// Owner-bound onboarding or session-replacement transaction. Product inputs
/// are echoed exactly so an external verifier can reject changed intent.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultSetupPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub session_public_key: String,
    /// The market named in the request, if any.
    pub market_id: Option<String>,
    pub mode: PlatformVaultSetupMode,
    pub expires_at_ms: Option<u64>,
    pub permanent: bool,
    /// The applied policy, defaults resolved.
    pub minimum_interval_seconds: u32,
    pub maximum_tolerance_bps: u16,
    pub spending_limits: Vec<PlatformVaultSpendingLimit>,
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub owner_signature_required: bool,
    /// Opaque handle for this prepared transaction. Hand it back with the
    /// owner-signed transaction to `vault.relay` and Strata submits it — no
    /// RPC or SOL needed on the owner side.
    pub preparation_id: String,
    /// `true` when Strata is the transaction fee payer and covers any rent the
    /// action creates, so the owner needs no SOL at all. `false` means the
    /// owner wallet is the fee payer (Strata still submits it on request).
    pub sponsored: bool,
    /// The prepared transaction must be submitted before this server time.
    pub submit_by_ms: u64,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformVaultDelegateAction {
    Revoke,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultDelegatePrepareRequest {
    pub wallet_address: String,
    pub session_public_key: String,
    pub action: PlatformVaultDelegateAction,
}

/// Unsigned session-lifecycle control. The owner verifies both identities and
/// the destructive action before signing and broadcasting it externally.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultDelegatePrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub session_public_key: String,
    pub action: PlatformVaultDelegateAction,
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub owner_signature_required: bool,
    /// Opaque handle for this prepared transaction. Hand it back with the
    /// owner-signed transaction to `vault.relay` and Strata submits it — no
    /// RPC or SOL needed on the owner side.
    pub preparation_id: String,
    /// `true` when Strata is the transaction fee payer and covers any rent the
    /// action creates, so the owner needs no SOL at all. `false` means the
    /// owner wallet is the fee payer (Strata still submits it on request).
    pub sponsored: bool,
    /// The prepared transaction must be submitted before this server time.
    pub submit_by_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultPolicyPrepareRequest {
    pub wallet_address: String,
    pub withdrawal_access: PlatformVaultWithdrawalAccess,
}

/// An owner-bound withdrawal-access change. Unrestricted access is a status
/// state rather than a preparable action in this contract.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultPolicyPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub withdrawal_access: PlatformVaultWithdrawalAccess,
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub owner_signature_required: bool,
    /// Opaque handle for this prepared transaction. Hand it back with the
    /// owner-signed transaction to `vault.relay` and Strata submits it — no
    /// RPC or SOL needed on the owner side.
    pub preparation_id: String,
    /// `true` when Strata is the transaction fee payer and covers any rent the
    /// action creates, so the owner needs no SOL at all. `false` means the
    /// owner wallet is the fee payer (Strata still submits it on request).
    pub sponsored: bool,
    /// The prepared transaction must be submitted before this server time.
    pub submit_by_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultDepositPrepareRequest {
    pub wallet_address: String,
    pub market_id: String,
    pub asset_id: String,
    pub amount_atoms: String,
    /// Optional external session key. When it is not yet registered for this
    /// wallet, the same deposit transaction registers it with the default
    /// session policy — a first deposit is the whole onboarding, one owner
    /// signature. An already-registered key changes nothing.
    #[serde(default)]
    pub session_public_key: Option<String>,
}

/// Exact owner-funded deposit transaction. Asset construction and custody
/// identities remain internal; the public intent is echoed for verification.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultDepositPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub market_id: String,
    pub asset_id: String,
    pub amount_atoms: String,
    /// SOL Strata already spent on this owner's sponsored actions, recovered
    /// in the deposit asset inside this same transaction (a second transfer
    /// from the owner's account to Strata). "0" when nothing is owed. It is
    /// only ever charged when the owner had no SOL and Strata paid instead,
    /// and never exceeds 1% of the deposit.
    pub network_cost_atoms: String,
    /// The session key named in the request, if any.
    pub session_public_key: Option<String>,
    /// `true` when this transaction also registers `session_public_key` with
    /// the default session policy (the deposit doubles as onboarding);
    /// `false` when the key was already registered or none was named.
    pub registers_session: bool,
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub owner_signature_required: bool,
    /// Opaque handle for this prepared transaction. Hand it back with the
    /// owner-signed transaction to `vault.relay` and Strata submits it — no
    /// RPC or SOL needed on the owner side.
    pub preparation_id: String,
    /// `true` when Strata is the transaction fee payer and covers any rent the
    /// action creates, so the owner needs no SOL at all. `false` means the
    /// owner wallet is the fee payer (Strata still submits it on request).
    pub sponsored: bool,
    /// The prepared transaction must be submitted before this server time.
    pub submit_by_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultWithdrawPrepareRequest {
    pub wallet_address: String,
    pub market_id: String,
    pub asset_id: String,
    pub destination_wallet_address: String,
    pub amount_atoms: String,
}

/// Exact owner-authorized withdrawal transaction. The destination is a wallet
/// identity; account construction and private balance routing remain internal.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultWithdrawPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub market_id: String,
    pub asset_id: String,
    pub destination_wallet_address: String,
    pub amount_atoms: String,
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub owner_signature_required: bool,
    /// Opaque handle for this prepared transaction. Hand it back with the
    /// owner-signed transaction to `vault.relay` and Strata submits it — no
    /// RPC or SOL needed on the owner side.
    pub preparation_id: String,
    /// `true` when Strata is the transaction fee payer and covers any rent the
    /// action creates, so the owner needs no SOL at all. `false` means the
    /// owner wallet is the fee payer (Strata still submits it on request).
    pub sponsored: bool,
    /// The prepared transaction must be submitted before this server time.
    pub submit_by_ms: u64,
}

/// Which prepared Vault action a submission carries.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformVaultAction {
    Setup,
    Deposit,
    Withdraw,
    Delegate,
    Policy,
    Pause,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformVaultSubmissionStatus {
    /// Accepted by the cluster; confirmation pending.
    Submitted,
    Confirmed,
    Failed,
}

/// Submit an owner-signed prepared Vault transaction. Strata verifies it is
/// exactly the prepared transaction, adds its own fee-payer signature when
/// the preparation was sponsored, and broadcasts it. Idempotent per
/// `idempotency_key`.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultSubmitRequest {
    pub preparation_id: String,
    pub signed_transaction_base64: String,
    pub idempotency_key: String,
}

/// Durable outcome of a Vault submission, also returned by the status read.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformVaultSubmitResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub preparation_id: String,
    pub action: PlatformVaultAction,
    pub wallet_address: String,
    pub sponsored: bool,
    pub signature: String,
    pub status: PlatformVaultSubmissionStatus,
    /// Present only when `status` is `failed`.
    pub failure_code: Option<String>,
    pub updated_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformRewardStanding {
    pub rank: u32,
    pub wallet_address: String,
    pub points: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOwnerRewards {
    pub wallet_address: String,
    pub rank: Option<u32>,
    pub points: String,
    pub trading_points: String,
    pub making_points: String,
    pub bug_points: String,
    pub referral_points: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformRewardsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub season: String,
    pub total_wallets: u32,
    pub owner: Option<PlatformOwnerRewards>,
    pub standings: Vec<PlatformRewardStanding>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformReferralsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub enabled: bool,
    pub cash_rewards_enabled: bool,
    pub referral_code: Option<String>,
    pub referred_wallets: u32,
    pub referral_points: String,
    pub referred_by: Option<String>,
    pub referral_locked: bool,
    pub cash_accrued_atoms: String,
    pub cash_paid_atoms: String,
    pub cash_claimable_atoms: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformReferralLinkRequest {
    pub wallet_address: String,
    pub referral_code: String,
    pub authorization_signature: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformReferralLinkResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub referral_code: String,
    pub status: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformReferralClaimRequest {
    pub wallet_address: String,
    pub payout_wallet_address: Option<String>,
    pub authorization_signature: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformReferralClaimResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub payout_wallet_address: String,
    pub claimable_atoms: String,
    pub status: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformBugStatus {
    Pending,
    Confirmed,
    Rejected,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBugReport {
    pub bug_id: String,
    pub status: PlatformBugStatus,
    pub severity: u8,
    pub points: String,
    pub created_at_ms: u64,
    pub triaged_at_ms: Option<u64>,
    pub completed_at_ms: Option<u64>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBugsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub wallet_address: String,
    pub points: String,
    pub confirmed_reports: u32,
    pub reports: Vec<PlatformBugReport>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBugSubmitRequest {
    pub owner_wallet: String,
    pub message: String,
    /// Hex Ed25519 signature over `strata-bug-report:v1:` followed by the
    /// trimmed report message. Signing always happens outside Strata.
    pub authorization_signature: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBugSubmitResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub bug_id: String,
    pub status: PlatformBugStatus,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformTradeSide {
    Buy,
    Sell,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTrade {
    pub trade_id: String,
    pub side: PlatformTradeSide,
    pub price_atoms: String,
    pub size_atoms: String,
    pub executed_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTradesResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub trades: Vec<PlatformTrade>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderType {
    GoodUntilCancelled,
    ImmediateOrCancel,
    FillOrKill,
    PostOnly,
}

/// Externally authorized resting-order operation. The public contract exposes
/// product intent only; private construction details never cross the SDK
/// boundary.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderAction {
    Place,
    Cancel,
    CancelAll,
    /// Atomically cancel one existing order and place its explicitly bound
    /// successor in the same transaction.
    Replace,
    /// Atomically execute a bounded heterogeneous set of place, cancel, and
    /// replace operations in one transaction.
    Batch,
}

/// One operation inside an atomic order-control batch. Owner and session
/// identity live on the enclosing challenge so no item can widen authority.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderBatchOperation {
    Place {
        /// Vault market account sequence for this order. Omit it and Strata
        /// resolves the next sequence from the Vault's confirmed market
        /// account when the challenge is issued (consecutive places in one
        /// batch receive consecutive sequences); supply it to pin a sequence
        /// tracked locally. A batch must either supply every sequence or none.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        account_sequence: Option<String>,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
    Cancel {
        order_id: String,
    },
    Replace {
        order_id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        account_sequence: Option<String>,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
}

/// Request canonical bytes for one externally signed order-control operation.
/// Variant-specific fields are sealed so an authorization cannot be widened
/// between challenge and transaction preparation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderChallengeRequest {
    Place {
        owner_wallet: String,
        session_public_key: String,
        /// Vault market account sequence. Omit it and Strata resolves the next
        /// sequence from the Vault's confirmed market account when the
        /// challenge is issued; supply it to pin a sequence tracked locally.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        account_sequence: Option<String>,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
    Cancel {
        owner_wallet: String,
        session_public_key: String,
        order_id: String,
    },
    CancelAll {
        owner_wallet: String,
        session_public_key: String,
    },
    Replace {
        owner_wallet: String,
        session_public_key: String,
        order_id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        account_sequence: Option<String>,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
    Batch {
        owner_wallet: String,
        session_public_key: String,
        operations: Vec<PlatformOrderBatchOperation>,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderChallengeResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub challenge_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    /// Exact opaque order set bound by the authorization. Replace returns the
    /// old then new ID. Batch flattens item IDs in request order, with replace
    /// contributing old then new. A batch contains at most six operations.
    pub order_ids: Vec<String>,
    pub authorization_payload_base64: String,
    pub server_time_ms: u64,
    pub expires_at_ms: u64,
}

/// A prepared challenge, signed: the two-step path.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderPrepareAuthorization {
    pub challenge_id: String,
    /// Base58 Ed25519 signature over `authorization_payload_base64`. Required
    /// over HTTP. Over the session-authenticated order command channel it may
    /// be omitted: the socket already proved the session and the challenge is
    /// bound to it, so the session signs only the transaction (one signature).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authorization_signature: Option<String>,
}

/// Prepare an order-control transaction. Either hand back a signed challenge
/// (`Authorized`, two signatures per action) or send the operation itself
/// (`Direct`, one signature per action): Strata builds the transaction from
/// the operation immediately and the session's signature over that
/// transaction is the whole authorization. The response is identical.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum PlatformOrderPrepareRequest {
    Authorized(PlatformOrderPrepareAuthorization),
    Direct(PlatformOrderChallengeRequest),
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub order_control_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    pub order_ids: Vec<String>,
    /// Backend-partially-signed Solana v0 transaction. The external session
    /// signer verifies and fills only its signature slot.
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub last_valid_block_height: u64,
    pub expires_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderSubmitRequest {
    pub order_control_id: String,
    pub signed_transaction_base64: String,
    pub idempotency_key: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderSubmissionStatus {
    Submitted,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderSubmitResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub order_control_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    pub order_ids: Vec<String>,
    pub signature: String,
    pub status: PlatformOrderSubmissionStatus,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderStatusRequest {
    pub order_control_id: String,
    pub idempotency_key: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderControlStatus {
    Submitting,
    Submitted,
    Failed,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub order_control_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    pub order_ids: Vec<String>,
    pub signature: String,
    pub status: PlatformOrderControlStatus,
    pub failure_code: Option<String>,
    pub updated_at_ms: u64,
}

/// Collision policy for an incoming order that would cross the owner's own
/// resting liquidity. Every mode still preserves Strata's matcher and on-chain
/// self-fill prohibition; this only controls which order is cancelled first.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformSelfTradePrevention {
    CancelTaker,
    CancelMaker,
    CancelBoth,
    SkipOwnLiquidity,
}

/// One command on the persistent order-control connection. Challenge results
/// may contain an effective request that differs from the requested one only
/// by the explicitly selected self-trade prevention transformation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderCommand {
    /// Authenticated non-trading round trip used for latency certification.
    Probe {
        nonce: String,
    },
    Challenge {
        request: PlatformOrderChallengeRequest,
        self_trade_prevention: PlatformSelfTradePrevention,
    },
    Prepare {
        request: PlatformOrderPrepareRequest,
    },
    Submit {
        request: PlatformOrderSubmitRequest,
    },
    Status {
        request: PlatformOrderStatusRequest,
    },
    DeadManArm {
        timeout_ms: u64,
        request: PlatformOrderSubmitRequest,
    },
    DeadManStatus,
    DeadManHeartbeat,
    DeadManDisarm,
}

/// Frames sent by an external agent. Authentication proves possession of the
/// declared session key; individual order authorizations and transactions keep
/// their existing exact external-signing boundaries. Authentication is a
/// singleton frame. After authentication, the transport accepts either one
/// command or a bounded array of commands; every command retains its own
/// request ID and contiguous sequence.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderCommandClientFrame {
    Authenticate {
        owner_wallet: String,
        session_public_key: String,
        /// Base58 Ed25519 signature over the stream authentication payload.
        signature: String,
        /// Optional negotiated result framing. Omitted clients retain the
        /// complete-event array format.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        batch_format: Option<PlatformOrderCommandBatchFormat>,
    },
    Command {
        request_id: String,
        sequence: String,
        command: PlatformOrderCommand,
    },
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderCommandBatchFormat {
    CompactV1,
}

/// One result inside a compact event batch. Shared stream identity, time and
/// sequence metadata live on the enclosing frame; request correlation and
/// command-specific results remain independent.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderCommandBatchEvent {
    ProbeResult {
        request_id: String,
        nonce: String,
    },
    ChallengeResult {
        request_id: String,
        self_trade_prevention: PlatformSelfTradePrevention,
        prevented_order_ids: Vec<String>,
        effective_request: PlatformOrderChallengeRequest,
        response: PlatformOrderChallengeResponse,
    },
    PrepareResult {
        request_id: String,
        response: PlatformOrderPrepareResponse,
    },
    SubmitResult {
        request_id: String,
        response: PlatformOrderSubmitResponse,
    },
    StatusResult {
        request_id: String,
        response: PlatformOrderStatusResponse,
    },
    DeadManResult {
        request_id: String,
        state: PlatformDeadManState,
    },
    CommandError {
        request_id: String,
        error: PublicOperationError,
    },
    Heartbeat,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderCommandServerFrame {
    EventBatch {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        first_sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        events: Vec<PlatformOrderCommandBatchEvent>,
    },
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformDeadManStatus {
    Armed,
    Triggering,
    Triggered,
    Disarmed,
    Expired,
    Failed,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformDeadManState {
    pub status: PlatformDeadManStatus,
    pub timeout_ms: u64,
    pub heartbeat_deadline_ms: u64,
    pub order_control_id: Option<String>,
    pub signature: Option<String>,
    pub failure_code: Option<String>,
    pub updated_at_ms: u64,
}

/// One sequenced event emitted by the persistent order-control connection.
/// After authentication, the transport carries bounded arrays of these events
/// so concurrent results share frame overhead without weakening per-event
/// sequence or request correlation. Terminal chain status may arrive later
/// without blocking command submission.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderCommandEvent {
    AuthChallenge {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        challenge: String,
        server_time_ms: u64,
        expires_at_ms: u64,
    },
    Ready {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
    },
    ProbeResult {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        request_id: String,
        nonce: String,
        server_time_ms: u64,
    },
    ChallengeResult {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        request_id: String,
        self_trade_prevention: PlatformSelfTradePrevention,
        prevented_order_ids: Vec<String>,
        effective_request: PlatformOrderChallengeRequest,
        response: PlatformOrderChallengeResponse,
        server_time_ms: u64,
    },
    PrepareResult {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        request_id: String,
        response: PlatformOrderPrepareResponse,
        server_time_ms: u64,
    },
    SubmitResult {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        request_id: String,
        response: PlatformOrderSubmitResponse,
        server_time_ms: u64,
    },
    StatusResult {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        request_id: String,
        response: PlatformOrderStatusResponse,
        server_time_ms: u64,
    },
    DeadManResult {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        request_id: String,
        state: PlatformDeadManState,
        server_time_ms: u64,
    },
    CommandError {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        request_id: String,
        error: PublicOperationError,
        server_time_ms: u64,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAccountOrder {
    pub order_id: String,
    pub side: PlatformTradeSide,
    pub order_type: PlatformOrderType,
    pub state: PlatformOrderState,
    pub limit_price_atoms: String,
    pub original_size_atoms: String,
    pub remaining_size_atoms: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAccountFill {
    pub fill_id: String,
    pub side: PlatformTradeSide,
    pub price_atoms: String,
    pub size_atoms: String,
    pub fee_quote_atoms: String,
    pub fee_is_final: bool,
    pub settlement: PlatformSettlementState,
    pub executed_at_ms: u64,
    pub confirmed_at_ms: Option<u64>,
    pub transaction_id: Option<String>,
    pub realized_pnl_quote_atoms: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAccountSnapshotResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub wallet_address: String,
    pub server_time_ms: u64,
    pub orders: Vec<PlatformAccountOrder>,
    pub fills: Vec<PlatformAccountFill>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMakerReputationTier {
    Probation,
    Bronze,
    Silver,
    Gold,
    Platinum,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerTierProgress {
    pub next_tier: Option<PlatformMakerReputationTier>,
    pub reputation_score_required: Option<u16>,
    pub reputation_score_remaining: u16,
    pub quote_requests_required: Option<String>,
    pub quote_requests_remaining: String,
    pub stake_atoms_required: Option<String>,
    pub stake_atoms_remaining: String,
    pub tenure_slots_required: Option<String>,
    pub tenure_slots_remaining: String,
}

/// Authenticated, privacy-preserving reliability and participation record for the
/// requesting maker. All potentially large counters and atomic quantities are
/// decimal strings so JavaScript agents never lose integer precision.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerReputationResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub maker_id: String,
    pub wallet_address: String,
    pub active: bool,
    pub tier: PlatformMakerReputationTier,
    pub reputation_score: u16,
    pub total_quote_requests: String,
    pub successful_fills: String,
    pub missed_quote_requests: String,
    pub fill_rate_bps: u16,
    pub consecutive_misses: u16,
    pub lifetime_filled_quote_atoms: String,
    pub distinct_counterparties: u16,
    pub recent_average_latency_ms: u16,
    pub configured_minimum_spread_bps: u16,
    pub weighted_average_spread_bps: u16,
    pub stake_atoms: String,
    pub epoch_start_stake_atoms: String,
    pub epoch_slashed_atoms: String,
    pub epoch_slashed_bps: u16,
    pub lifetime_auto_slashed_atoms: String,
    pub registered_slot: String,
    pub last_active_slot: String,
    pub last_settled_slot: String,
    pub revoked_at_slot: Option<String>,
    pub tenure_slots: String,
    pub signed_quote_stream_eligible: bool,
    pub minimum_quote_interval_ms: Option<u16>,
    pub tier_progress: PlatformMakerTierProgress,
    pub server_time_ms: u64,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMakerSide {
    Buy,
    Sell,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOracleHealth {
    Fresh,
    Stale,
    Unknown,
}

/// The maker's resting firm orders in this market, summarised by side.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerFirmOrderSummary {
    pub resting_orders: u32,
    pub bid_orders: u32,
    pub ask_orders: u32,
    pub bid_size_atoms: String,
    pub ask_size_atoms: String,
}

/// One of the maker's own live signed quotes in the streaming lane.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerSignedQuote {
    pub side: PlatformMakerSide,
    pub price_atoms: String,
    pub size_atoms: String,
    pub nonce: String,
    pub issued_at_ms: u64,
    pub expires_at_ms: u64,
}

/// The maker's own intent product in this market.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerIntentStatus {
    pub active: bool,
    pub side: PlatformMakerSide,
    pub minimum_price_atoms: String,
    pub maximum_price_atoms: String,
    pub maximum_fill_size_atoms: String,
    /// Fill budget still available after in-flight reservations.
    pub remaining_fill_size_atoms: String,
    pub minimum_spread_bps: u16,
    pub stake_atoms: String,
}

/// The maker's signed-quote lane: eligibility and its own live quotes.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerSignedQuoteLane {
    pub eligible: bool,
    pub live_quotes: Vec<PlatformMakerSignedQuote>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerStrandLevel {
    /// Null when the configured offset overflows the price range.
    pub price_atoms: Option<String>,
    pub size_atoms: String,
    pub remaining_size_atoms: String,
}

/// One of the maker's own Strands in this market.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerStrandStatus {
    pub enabled: bool,
    pub async_only: bool,
    /// True once the chain would reject fills because `valid_until_slot` passed.
    pub expired: bool,
    pub mid_price_atoms: String,
    pub tick_size_atoms: String,
    /// Null means the Strand never expires.
    pub valid_until_slot: Option<String>,
    pub bids: Vec<PlatformMakerStrandLevel>,
    pub asks: Vec<PlatformMakerStrandLevel>,
    pub maximum_exposure_atoms: String,
    pub remaining_exposure_atoms: String,
}

/// One of the maker's own Currents in this market.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerCurrentStatus {
    pub enabled: bool,
    pub async_only: bool,
    pub expired: bool,
    pub half_spread_bps: u16,
    pub band_step_bps: u16,
    pub maximum_confidence_bps: u16,
    pub maximum_oracle_age_seconds: u32,
    pub sync_spread_bps: u16,
    /// Null means the Current never expires.
    pub valid_until_slot: Option<String>,
    pub bid_depth_atoms: Vec<String>,
    pub ask_depth_atoms: Vec<String>,
    pub maximum_exposure_atoms: String,
    pub remaining_exposure_atoms: String,
    /// Freshness class of the market oracle the Current settles against.
    pub oracle_health: PlatformOracleHealth,
}

/// One durable dead-man guard the owner armed for a session in this market.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerDeadManGuard {
    pub session_public_key: String,
    pub status: PlatformDeadManStatus,
    pub timeout_ms: u64,
    pub heartbeat_deadline_ms: u64,
    pub updated_at_ms: u64,
}

/// Authenticated, owner-scoped view of the maker's Strata products in one
/// market: firm orders, intent, Strands, Currents, the signed-quote lane, live
/// exposure, health, and kill state. Nothing about other makers, takers, or
/// liquidity sources crosses this boundary.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub maker_id: String,
    pub wallet_address: String,
    pub server_time_ms: u64,
    pub current_slot: String,
    pub firm_orders: PlatformMakerFirmOrderSummary,
    pub intent: Option<PlatformMakerIntentStatus>,
    pub signed_quotes: PlatformMakerSignedQuoteLane,
    pub strands: Vec<PlatformMakerStrandStatus>,
    pub currents: Vec<PlatformMakerCurrentStatus>,
    pub dead_man_guards: Vec<PlatformMakerDeadManGuard>,
    /// Count of maker products currently able to fill: an active intent, each
    /// enabled unexpired Strand or Current, and resting firm orders (as one).
    pub active_products: u16,
}

/// One maker-owned Strand mutation. Amounts that may exceed JavaScript's safe
/// integer range remain canonical unsigned decimal strings on the wire.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformMakerStrandPrepareRequest {
    Upsert {
        maker_wallet: String,
        enabled: bool,
        async_only: bool,
        sync_spread_ticks: u16,
        mid_price_atoms: String,
        max_exposure_base_lots: String,
        bid_offsets_ticks: Vec<u16>,
        ask_offsets_ticks: Vec<u16>,
        bid_sizes_base_lots: Vec<String>,
        ask_sizes_base_lots: Vec<String>,
        valid_until_slot: String,
    },
    Recenter {
        maker_wallet: String,
        new_mid_price_atoms: String,
        valid_until_slot: String,
    },
    SetEnabled {
        maker_wallet: String,
        enabled: bool,
    },
    Cancel {
        maker_wallet: String,
    },
}

/// One maker-owned Current mutation. Current is parameterized around the
/// market's configured on-chain reference and therefore has no recenter action.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformMakerCurrentPrepareRequest {
    Upsert {
        maker_wallet: String,
        enabled: bool,
        async_only: bool,
        half_spread_bps: u16,
        band_step_bps: u16,
        max_conf_bps: u16,
        max_oracle_dev_bps: u16,
        max_oracle_age_secs: u32,
        sync_spread_bps: u16,
        max_exposure_base_atoms: String,
        bid_depth_base_atoms: Vec<String>,
        ask_depth_base_atoms: Vec<String>,
        valid_until_slot: String,
    },
    Cancel {
        maker_wallet: String,
    },
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMakerControlProduct {
    Strand,
    Current,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMakerControlAction {
    StrandUpsert,
    StrandRecenter,
    StrandSetEnabled,
    StrandCancel,
    CurrentUpsert,
    CurrentCancel,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerControlPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub maker_control_id: String,
    pub market_id: String,
    pub maker_wallet: String,
    pub product: PlatformMakerControlProduct,
    pub action: PlatformMakerControlAction,
    /// Unsigned legacy Solana transaction. The maker verifies the exact
    /// instruction and fills its only signature slot externally.
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub last_valid_block_height: u64,
    pub expires_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerControlSubmitRequest {
    pub maker_control_id: String,
    pub signed_transaction_base64: String,
    pub idempotency_key: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMakerControlSubmissionStatus {
    Submitted,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerControlSubmitResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub maker_control_id: String,
    pub market_id: String,
    pub maker_wallet: String,
    pub product: PlatformMakerControlProduct,
    pub action: PlatformMakerControlAction,
    pub signature: String,
    pub status: PlatformMakerControlSubmissionStatus,
}

/// Which Strata maker product produced a maker-side fill.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMakerProduct {
    FirmOrder,
    Intent,
    Strand,
    Current,
}

/// One maker-side fill: the same sanitized settlement view as an account fill
/// plus the maker product that produced it. No counterparty or venue.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMakerFill {
    pub fill_id: String,
    pub product: PlatformMakerProduct,
    pub side: PlatformTradeSide,
    pub price_atoms: String,
    pub size_atoms: String,
    pub fee_quote_atoms: String,
    pub fee_is_final: bool,
    pub settlement: PlatformSettlementState,
    pub executed_at_ms: u64,
    pub confirmed_at_ms: Option<u64>,
    pub transaction_id: Option<String>,
    pub realized_pnl_quote_atoms: String,
}

/// Authenticated, sequenced owner-only maker stream (`mm.fills.stream`).
/// After the signed challenge the server sends one `maker_snapshot`, then
/// sequenced `maker_fill`, `maker_status` (exposure/product change), and
/// `heartbeat` events; a recovery snapshot advances the sequence on the same
/// stream identity.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformMakerEvent {
    AuthChallenge {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        challenge: String,
        server_time_ms: u64,
        expires_at_ms: u64,
    },
    MakerSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        status: PlatformMakerStatusResponse,
        fills: Vec<PlatformMakerFill>,
    },
    MakerFill {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        fill: PlatformMakerFill,
    },
    MakerStatus {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        status: PlatformMakerStatusResponse,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformAccountEvent {
    AuthChallenge {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        challenge: String,
        server_time_ms: u64,
        expires_at_ms: u64,
    },
    AccountSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        orders: Vec<PlatformAccountOrder>,
        fills: Vec<PlatformAccountFill>,
    },
    OrdersSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        orders: Vec<PlatformAccountOrder>,
    },
    Fill {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        fill: PlatformAccountFill,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformMarketDataEvent {
    BookSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        snapshot_id: String,
        bids: Vec<PlatformBookLevel>,
        asks: Vec<PlatformBookLevel>,
    },
    BookDelta {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        changes: Vec<PlatformBookChange>,
    },
    BestBidAsk {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        best_bid: Option<PlatformBookLevel>,
        best_ask: Option<PlatformBookLevel>,
    },
    Trade {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        server_time_ms: u64,
        trade: PlatformTrade,
    },
    MarketStatus {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        server_time_ms: u64,
        status: PlatformMarketState,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        server_time_ms: u64,
    },
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn public_platform_fixtures_decode_strictly() {
        let discovery: PlatformDiscoveryResponse =
            serde_json::from_str(PLATFORM_CAPABILITIES_FIXTURE).unwrap();
        let service_status: PlatformServiceStatusResponse =
            serde_json::from_str(PLATFORM_SERVICE_STATUS_FIXTURE).unwrap();
        let graph = PlatformActionGraphResponse::foundation();
        let assets: PlatformAssetsResponse = serde_json::from_str(PLATFORM_ASSETS_FIXTURE).unwrap();
        let swap_quote: PlatformSwapQuoteResponse =
            serde_json::from_str(PLATFORM_SWAP_QUOTE_FIXTURE).unwrap();
        let markets: PlatformMarketsResponse =
            serde_json::from_str(PLATFORM_MARKETS_FIXTURE).unwrap();
        let book: PlatformBookSnapshotResponse =
            serde_json::from_str(PLATFORM_BOOK_FIXTURE).unwrap();
        let bbo: PlatformBestBidAskResponse = serde_json::from_str(PLATFORM_BBO_FIXTURE).unwrap();
        let fees: PlatformFeeScheduleResponse =
            serde_json::from_str(PLATFORM_FEES_FIXTURE).unwrap();
        let status: PlatformMarketStatusResponse =
            serde_json::from_str(PLATFORM_STATUS_FIXTURE).unwrap();
        let candles: PlatformCandlesResponse =
            serde_json::from_str(PLATFORM_CANDLES_FIXTURE).unwrap();
        let mark: PlatformMarkResponse = serde_json::from_str(PLATFORM_MARK_FIXTURE).unwrap();
        let execution_status: PlatformExecutionStatusResponse =
            serde_json::from_str(PLATFORM_EXECUTION_STATUS_FIXTURE).unwrap();
        let twaps: PlatformTwapsResponse = serde_json::from_str(PLATFORM_TWAPS_FIXTURE).unwrap();
        let twap_challenge: PlatformTwapChallengeResponse =
            serde_json::from_str(PLATFORM_TWAP_CHALLENGE_FIXTURE).unwrap();
        let twap_prepare: PlatformTwapPrepareResponse =
            serde_json::from_str(PLATFORM_TWAP_PREPARE_FIXTURE).unwrap();
        let twap_submit: PlatformTwapSubmitResponse =
            serde_json::from_str(PLATFORM_TWAP_SUBMIT_FIXTURE).unwrap();
        let portfolio_history: PlatformPortfolioHistoryResponse =
            serde_json::from_str(PLATFORM_PORTFOLIO_HISTORY_FIXTURE).unwrap();
        let portfolio: PlatformPortfolioResponse =
            serde_json::from_str(PLATFORM_PORTFOLIO_FIXTURE).unwrap();
        let rewards: PlatformRewardsResponse =
            serde_json::from_str(PLATFORM_REWARDS_FIXTURE).unwrap();
        let referrals: PlatformReferralsResponse =
            serde_json::from_str(PLATFORM_REFERRALS_FIXTURE).unwrap();
        let referral_link: PlatformReferralLinkResponse =
            serde_json::from_str(PLATFORM_REFERRAL_LINK_FIXTURE).unwrap();
        let referral_claim: PlatformReferralClaimResponse =
            serde_json::from_str(PLATFORM_REFERRAL_CLAIM_FIXTURE).unwrap();
        let vault_status: PlatformVaultStatusResponse =
            serde_json::from_str(PLATFORM_VAULT_STATUS_FIXTURE).unwrap();
        let vault_pause: PlatformVaultPausePrepareResponse =
            serde_json::from_str(PLATFORM_VAULT_PAUSE_PREPARE_FIXTURE).unwrap();
        let vault_setup: PlatformVaultSetupPrepareResponse =
            serde_json::from_str(PLATFORM_VAULT_SETUP_PREPARE_FIXTURE).unwrap();
        let vault_delegate: PlatformVaultDelegatePrepareResponse =
            serde_json::from_str(PLATFORM_VAULT_DELEGATE_PREPARE_FIXTURE).unwrap();
        let vault_policy: PlatformVaultPolicyPrepareResponse =
            serde_json::from_str(PLATFORM_VAULT_POLICY_PREPARE_FIXTURE).unwrap();
        let vault_deposit: PlatformVaultDepositPrepareResponse =
            serde_json::from_str(PLATFORM_VAULT_DEPOSIT_PREPARE_FIXTURE).unwrap();
        let vault_withdraw: PlatformVaultWithdrawPrepareResponse =
            serde_json::from_str(PLATFORM_VAULT_WITHDRAW_PREPARE_FIXTURE).unwrap();
        let vault_submit: PlatformVaultSubmitResponse =
            serde_json::from_str(PLATFORM_VAULT_SUBMIT_FIXTURE).unwrap();
        let bugs: PlatformBugsResponse = serde_json::from_str(PLATFORM_BUGS_FIXTURE).unwrap();
        let bug_submit: PlatformBugSubmitResponse =
            serde_json::from_str(PLATFORM_BUG_SUBMIT_FIXTURE).unwrap();
        let trades: PlatformTradesResponse = serde_json::from_str(PLATFORM_TRADES_FIXTURE).unwrap();
        let account: PlatformAccountSnapshotResponse =
            serde_json::from_str(PLATFORM_ACCOUNT_FIXTURE).unwrap();
        let maker_reputation: PlatformMakerReputationResponse =
            serde_json::from_str(PLATFORM_MAKER_REPUTATION_FIXTURE).unwrap();
        let maker_status: PlatformMakerStatusResponse =
            serde_json::from_str(PLATFORM_MAKER_STATUS_FIXTURE).unwrap();
        let maker_stream: PlatformMakerEvent =
            serde_json::from_str(PLATFORM_MAKER_STREAM_FIXTURE).unwrap();
        let twap_stream: PlatformTwapEvent =
            serde_json::from_str(PLATFORM_TWAP_STREAM_FIXTURE).unwrap();
        let execution_stream: PlatformExecutionEvent =
            serde_json::from_str(PLATFORM_EXECUTION_STREAM_FIXTURE).unwrap();
        let order_challenge: PlatformOrderChallengeResponse =
            serde_json::from_str(PLATFORM_ORDER_CHALLENGE_FIXTURE).unwrap();
        let order_prepare: PlatformOrderPrepareResponse =
            serde_json::from_str(PLATFORM_ORDER_PREPARE_FIXTURE).unwrap();
        let order_submit: PlatformOrderSubmitResponse =
            serde_json::from_str(PLATFORM_ORDER_SUBMIT_FIXTURE).unwrap();
        let order_status: PlatformOrderStatusResponse =
            serde_json::from_str(PLATFORM_ORDER_STATUS_FIXTURE).unwrap();

        assert_eq!(discovery.schema_version, PLATFORM_SCHEMA_VERSION);
        assert_eq!(service_status.status, PlatformServiceState::Operational);
        assert_eq!(service_status.available_operations, 59);
        assert_eq!(graph.entry_operation_id, "platform.capabilities.read");
        assert_eq!(graph.operations.len(), 69);
        assert_eq!(maker_reputation.tier, PlatformMakerReputationTier::Gold);
        assert_eq!(maker_status.active_products, 3);
        match &maker_stream {
            PlatformMakerEvent::MakerSnapshot { status, fills, .. } => {
                assert_eq!(status.active_products, maker_status.active_products);
                assert_eq!(fills.len(), 1);
                assert_eq!(fills[0].product, PlatformMakerProduct::Strand);
            }
            other => panic!("maker stream fixture must be a snapshot, got {other:?}"),
        }
        match &twap_stream {
            PlatformTwapEvent::TwapsSnapshot {
                twaps: streamed, ..
            } => {
                assert_eq!(streamed, &twaps.twaps);
            }
            other => panic!("twap stream fixture must be a snapshot, got {other:?}"),
        }
        match &execution_stream {
            PlatformExecutionEvent::ExecutionsSnapshot {
                executions,
                unknown_execution_ids,
                ..
            } => {
                assert_eq!(executions.len(), 2);
                assert_eq!(executions[0].execution_id, execution_status.execution_id);
                assert_eq!(unknown_execution_ids.len(), 1);
            }
            other => panic!("execution stream fixture must be a snapshot, got {other:?}"),
        }
        assert_eq!(maker_status.strands.len(), 1);
        assert_eq!(maker_status.currents.len(), 1);
        assert!(maker_status
            .intent
            .as_ref()
            .is_some_and(|intent| intent.active));
        assert_eq!(portfolio.balances.len(), 2);
        assert_eq!(portfolio.positions.len(), 1);
        assert!(portfolio.valuation_complete);
        assert_eq!(portfolio.equity_usd_micros.as_deref(), Some("439989500"));
        assert!(graph
            .operations
            .iter()
            .any(|operation| operation.id == "twap.place.submit"));
        assert!(graph
            .operations
            .iter()
            .any(|operation| operation.id == "twap.cancel.submit"));
        assert_eq!(discovery.capabilities.len(), 5);
        assert!(!discovery.authority.accepts_private_keys);
        assert_eq!(assets.assets.len(), 2);
        assert_eq!(swap_quote.input_asset_id, assets.assets[0].asset_id);
        assert_eq!(swap_quote.output_asset_id, assets.assets[1].asset_id);
        assert_eq!(markets.markets.len(), 1);
        assert_eq!(markets.markets[0].base_asset_id, assets.assets[0].asset_id);
        assert_eq!(markets.markets[0].quote_asset_id, assets.assets[1].asset_id);
        assert_eq!(book.sequence, "42");
        assert_eq!(bbo.best_bid.unwrap().price_atoms, "149990000");
        assert_eq!(fees.maximum_immediate_execution_fee_bps, 10);
        assert_eq!(status.status, PlatformMarketState::Active);
        assert_eq!(candles.candles.len(), 2);
        assert_eq!(mark.price_atoms_per_base_unit.as_deref(), Some("149995000"));
        assert_eq!(execution_status.status, PlatformExecutionState::Confirmed);
        assert_eq!(
            execution_status.settlement,
            PlatformSettlementState::Confirmed
        );
        assert_eq!(twaps.twaps[0].fills.len(), 1);
        assert_eq!(twaps.twaps[0].slices_executed, 2);
        assert_eq!(twap_challenge.action, PlatformTwapControlAction::Place);
        assert_eq!(twap_prepare.twap_id, twap_challenge.twap_id);
        assert_eq!(twap_submit.twap_control_id, twap_prepare.twap_control_id);
        assert_eq!(portfolio_history.points.len(), 2);
        assert_eq!(rewards.standings.len(), 2);
        assert!(referrals.enabled);
        assert_eq!(referral_link.status, "pending_first_fill");
        assert_eq!(referral_claim.status, "requested");
        assert_eq!(vault_status.state, PlatformVaultState::Active);
        assert_eq!(
            vault_status.session.as_ref().unwrap().state,
            PlatformVaultSessionState::Active
        );
        assert!(vault_pause.paused);
        assert!(vault_pause.owner_signature_required);
        assert_eq!(vault_setup.mode, PlatformVaultSetupMode::Create);
        assert!(vault_setup.permanent);
        assert_eq!(vault_delegate.action, PlatformVaultDelegateAction::Revoke);
        assert!(vault_delegate.owner_signature_required);
        assert_eq!(
            vault_policy.withdrawal_access.mode,
            PlatformVaultWithdrawalMode::Restricted
        );
        assert!(vault_policy.owner_signature_required);
        assert_eq!(vault_deposit.amount_atoms, "10000000");
        assert!(vault_deposit.owner_signature_required);
        assert_eq!(vault_withdraw.amount_atoms, "5000000");
        assert!(vault_withdraw.owner_signature_required);
        assert!(vault_withdraw.sponsored);
        assert!(vault_withdraw.preparation_id.starts_with("vp_"));
        assert_eq!(vault_submit.action, PlatformVaultAction::Deposit);
        assert_eq!(
            vault_submit.status,
            PlatformVaultSubmissionStatus::Submitted
        );
        assert!(vault_submit.sponsored);
        assert_eq!(vault_submit.failure_code, None);
        assert_eq!(bugs.reports[0].status, PlatformBugStatus::Confirmed);
        assert_eq!(bug_submit.status, PlatformBugStatus::Pending);
        assert_eq!(trades.trades.len(), 1);
        assert_eq!(account.orders.len(), 1);
        assert_eq!(account.fills.len(), 1);
        assert_eq!(order_challenge.action, PlatformOrderAction::Place);
        assert_eq!(order_prepare.order_ids, order_challenge.order_ids);
        assert_eq!(order_submit.order_ids, order_challenge.order_ids);
        assert_eq!(order_status.order_control_id, order_submit.order_control_id);
        assert_eq!(order_status.status, PlatformOrderControlStatus::Submitting);
    }

    #[test]
    fn public_platform_response_rejects_unreviewed_fields() {
        let mut value: serde_json::Value =
            serde_json::from_str(PLATFORM_CAPABILITIES_FIXTURE).unwrap();
        value
            .as_object_mut()
            .unwrap()
            .insert("unexpected_field".to_owned(), serde_json::Value::Bool(true));
        assert!(serde_json::from_value::<PlatformDiscoveryResponse>(value).is_err());

        let mut account_event: serde_json::Value =
            serde_json::from_str(PLATFORM_ACCOUNT_FIXTURE).unwrap();
        let event = account_event.as_object_mut().unwrap();
        event.insert("type".to_owned(), serde_json::json!("account_snapshot"));
        event.insert(
            "stream_id".to_owned(),
            serde_json::json!("account_stream_66666666666666666666666666666666"),
        );
        event.insert("sequence".to_owned(), serde_json::json!("1"));
        event.insert("unexpected_field".to_owned(), serde_json::json!(true));
        assert!(serde_json::from_value::<PlatformAccountEvent>(account_event).is_err());
    }

    #[test]
    fn platform_graph_availability_is_projected_from_live_capabilities() {
        let mut graph = PlatformActionGraphResponse::foundation();
        let live = std::collections::BTreeSet::from([
            "platform.discover".to_owned(),
            "graphs.read".to_owned(),
            "orders.replace".to_owned(),
        ]);

        graph.project_availability(&live);

        for operation in &graph.operations {
            assert_eq!(
                operation.available,
                live.contains(&operation.capability_id),
                "operation {} did not follow capability {}",
                operation.id,
                operation.capability_id,
            );
        }
        assert!(graph
            .workflows
            .iter()
            .flat_map(|workflow| &workflow.nodes)
            .filter(|node| node.kind != PlatformActionKind::ExternalSignature)
            .all(|node| {
                node.available
                    == node
                        .capability_id
                        .as_ref()
                        .is_some_and(|capability_id| live.contains(capability_id))
            }));
        assert!(graph
            .workflows
            .iter()
            .flat_map(|workflow| &workflow.nodes)
            .filter(|node| node.kind == PlatformActionKind::ExternalSignature)
            .all(|node| node.available));
    }

    #[test]
    fn atomic_order_batch_request_is_strict_and_typed() {
        let request: PlatformOrderChallengeRequest = serde_json::from_value(serde_json::json!({
            "action": "batch",
            "owner_wallet": "11111111111111111111111111111111",
            "session_public_key": "22222222222222222222222222222222",
            "operations": [
                {
                    "action": "cancel",
                    "order_id": "order_11111111111111111111111111111111"
                },
                {
                    "action": "replace",
                    "order_id": "order_22222222222222222222222222222222",
                    "account_sequence": "8",
                    "client_order_id": "replacement-8",
                    "side": "sell",
                    "order_type": "post_only",
                    "limit_price_atoms": "151000000",
                    "size_atoms": "2000000"
                }
            ]
        }))
        .unwrap();
        let PlatformOrderChallengeRequest::Batch { operations, .. } = request else {
            panic!("expected batch request");
        };
        assert_eq!(operations.len(), 2);
        assert!(matches!(
            &operations[1],
            PlatformOrderBatchOperation::Replace { account_sequence: Some(sequence), .. }
                if sequence == "8"
        ));

        // The account sequence is optional: Strata resolves it from the Vault's
        // confirmed market account when omitted, and omitted stays omitted on
        // the wire so older servers reject rather than misread it.
        let place: PlatformOrderChallengeRequest = serde_json::from_value(serde_json::json!({
            "action": "place",
            "owner_wallet": "11111111111111111111111111111111",
            "session_public_key": "22222222222222222222222222222222",
            "client_order_id": "first-order",
            "side": "buy",
            "order_type": "post_only",
            "limit_price_atoms": "150000000",
            "size_atoms": "1000000"
        }))
        .unwrap();
        assert!(matches!(
            place,
            PlatformOrderChallengeRequest::Place {
                account_sequence: None,
                ..
            }
        ));
        assert!(!serde_json::to_string(&place)
            .unwrap()
            .contains("account_sequence"));

        assert!(
            serde_json::from_value::<PlatformOrderChallengeRequest>(serde_json::json!({
                "action": "batch",
                "owner_wallet": "11111111111111111111111111111111",
                "session_public_key": "22222222222222222222222222222222",
                "operations": [{
                    "action": "cancel",
                    "order_id": "order_11111111111111111111111111111111",
                    "implementation": "hidden"
                }]
            }))
            .is_err()
        );
    }

    #[test]
    fn persistent_order_commands_are_strict_and_explicit_about_self_trade_policy() {
        let frame: PlatformOrderCommandClientFrame = serde_json::from_value(serde_json::json!({
            "type": "command",
            "request_id": "agent-1",
            "sequence": "1",
            "command": {
                "type": "challenge",
                "self_trade_prevention": "cancel_maker",
                "request": {
                    "action": "cancel_all",
                    "owner_wallet": "11111111111111111111111111111111",
                    "session_public_key": "22222222222222222222222222222222"
                }
            }
        }))
        .unwrap();
        assert!(matches!(
            frame,
            PlatformOrderCommandClientFrame::Command {
                command: PlatformOrderCommand::Challenge {
                    self_trade_prevention: PlatformSelfTradePrevention::CancelMaker,
                    ..
                },
                ..
            }
        ));
        assert!(
            serde_json::from_value::<PlatformOrderCommandClientFrame>(serde_json::json!({
                "type": "command",
                "request_id": "agent-1",
                "sequence": "1",
                "command": {
                    "type": "challenge",
                    "request": {
                        "action": "cancel_all",
                        "owner_wallet": "11111111111111111111111111111111",
                        "session_public_key": "22222222222222222222222222222222"
                    }
                }
            }))
            .is_err()
        );
    }

    #[test]
    fn prepare_requests_accept_a_signed_challenge_or_the_operation_itself() {
        let signed: PlatformOrderPrepareRequest = serde_json::from_value(serde_json::json!({
            "challenge_id": "oc_0123456789abcdef0123456789abcdef",
            "authorization_signature": "1111",
        }))
        .unwrap();
        assert!(matches!(signed, PlatformOrderPrepareRequest::Authorized(_)));
        let direct: PlatformOrderPrepareRequest = serde_json::from_value(serde_json::json!({
            "action": "cancel_all",
            "owner_wallet": "5Ji61Fbeb22Yntgv1hhHeSSLgdEdZchHeM1Tv1MjGhSL",
            "session_public_key": "9Uu7cLBgfMk233BAjMvTS8XJy6KbZK7oQ7NXuCTi3Fg2",
        }))
        .unwrap();
        assert!(matches!(
            direct,
            PlatformOrderPrepareRequest::Direct(PlatformOrderChallengeRequest::CancelAll { .. })
        ));
        // Neither shape tolerates a stray field.
        assert!(
            serde_json::from_value::<PlatformOrderPrepareRequest>(serde_json::json!({
                "challenge_id": "oc_0123456789abcdef0123456789abcdef",
                "authorization_signature": "1111",
                "extra": true,
            }))
            .is_err()
        );
        let twap: PlatformTwapPrepareRequest = serde_json::from_value(serde_json::json!({
            "action": "cancel",
            "owner_wallet": "5Ji61Fbeb22Yntgv1hhHeSSLgdEdZchHeM1Tv1MjGhSL",
            "session_public_key": "9Uu7cLBgfMk233BAjMvTS8XJy6KbZK7oQ7NXuCTi3Fg2",
            "twap_id": "twap_0123456789abcdef0123456789abcdef",
        }))
        .unwrap();
        assert!(matches!(twap, PlatformTwapPrepareRequest::Direct(_)));
        let execution: crate::ExecutionPrepareRequest = serde_json::from_value(serde_json::json!({
            "quote_id": "quote_0123456789abcdef0123456789abcdef",
            "owner_wallet": "5Ji61Fbeb22Yntgv1hhHeSSLgdEdZchHeM1Tv1MjGhSL",
            "session_public_key": "9Uu7cLBgfMk233BAjMvTS8XJy6KbZK7oQ7NXuCTi3Fg2",
        }))
        .unwrap();
        assert!(matches!(
            execution,
            crate::ExecutionPrepareRequest::Direct(_)
        ));
    }

    #[test]
    fn maker_control_requests_are_tagged_exact_and_amount_safe() {
        let strand: PlatformMakerStrandPrepareRequest = serde_json::from_value(serde_json::json!({
            "action": "recenter",
            "maker_wallet": "5Ji61Fbeb22Yntgv1hhHeSSLgdEdZchHeM1Tv1MjGhSL",
            "new_mid_price_atoms": "123000000",
            "valid_until_slot": "0"
        }))
        .unwrap();
        assert!(matches!(
            strand,
            PlatformMakerStrandPrepareRequest::Recenter { .. }
        ));

        let current: PlatformMakerCurrentPrepareRequest =
            serde_json::from_value(serde_json::json!({
                "action": "cancel",
                "maker_wallet": "5Ji61Fbeb22Yntgv1hhHeSSLgdEdZchHeM1Tv1MjGhSL"
            }))
            .unwrap();
        assert!(matches!(
            current,
            PlatformMakerCurrentPrepareRequest::Cancel { .. }
        ));
        assert!(
            serde_json::from_value::<PlatformMakerCurrentPrepareRequest>(serde_json::json!({
                "action": "cancel",
                "maker_wallet": "5Ji61Fbeb22Yntgv1hhHeSSLgdEdZchHeM1Tv1MjGhSL",
                "oracle_price": 123.45
            }))
            .is_err()
        );
    }
}