madeonsol 0.26.1

Official Rust SDK for the MadeOnSol Solana API — KOL wallet tracking, Pump.fun deployer intelligence, and DEX trade firehose. Free tier: 200 req/day at https://madeonsol.com/pricing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
//! Request and response types for every endpoint in the MadeOnSol API.
//!
//! Field names mirror the JSON wire format exactly so you can paste API examples
//! straight from the docs at <https://madeonsol.com/api-docs>.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ─── Shared enums ────────────────────────────────────────────────────────────

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

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum LeaderboardPeriod {
    #[serde(rename = "today")]
    Today,
    #[serde(rename = "7d")]
    D7,
    #[serde(rename = "30d")]
    D30,
    #[serde(rename = "90d")]
    D90,
    #[serde(rename = "180d")]
    D180,
}

impl LeaderboardPeriod {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Today => "today",
            Self::D7 => "7d",
            Self::D30 => "30d",
            Self::D90 => "90d",
            Self::D180 => "180d",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum CoordinationPeriod {
    #[serde(rename = "1h")]
    H1,
    #[serde(rename = "6h")]
    H6,
    #[serde(rename = "24h")]
    H24,
    #[serde(rename = "7d")]
    D7,
}

impl CoordinationPeriod {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::H1 => "1h",
            Self::H6 => "6h",
            Self::H24 => "24h",
            Self::D7 => "7d",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum KolStrategy {
    Scalper,
    DayTrader,
    SwingTrader,
    Hodler,
    Mixed,
}

impl KolStrategy {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Scalper => "scalper",
            Self::DayTrader => "day_trader",
            Self::SwingTrader => "swing_trader",
            Self::Hodler => "hodler",
            Self::Mixed => "mixed",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum KolLeaderboardSort {
    Pnl,
    Winrate,
    Volume,
    AvgRoi,
    ProfitFactor,
    EarlyEntryPct,
    Consistency,
}

impl KolLeaderboardSort {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Pnl => "pnl",
            Self::Winrate => "winrate",
            Self::Volume => "volume",
            Self::AvgRoi => "avg_roi",
            Self::ProfitFactor => "profit_factor",
            Self::EarlyEntryPct => "early_entry_pct",
            Self::Consistency => "consistency",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DeployerTier {
    Elite,
    Good,
    Moderate,
    Rising,
    Cold,
    #[serde(rename = "unranked")]
    Unranked,
}

impl DeployerTier {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Elite => "elite",
            Self::Good => "good",
            Self::Moderate => "moderate",
            Self::Rising => "rising",
            Self::Cold => "cold",
            Self::Unranked => "unranked",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DeployerSortField {
    BondingRate,
    RecentBondRate,
    TotalBonded,
    LastDeployAt,
}

impl DeployerSortField {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::BondingRate => "bonding_rate",
            Self::RecentBondRate => "recent_bond_rate",
            Self::TotalBonded => "total_bonded",
            Self::LastDeployAt => "last_deploy_at",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum AlertPeriod {
    #[serde(rename = "7d")]
    D7,
    #[serde(rename = "30d")]
    D30,
    #[serde(rename = "all")]
    All,
}

impl AlertPeriod {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::D7 => "7d",
            Self::D30 => "30d",
            Self::All => "all",
        }
    }
}

pub type BestTokensPeriod = AlertPeriod;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum WalletTrackerSummaryPeriod {
    #[serde(rename = "24h")]
    H24,
    #[serde(rename = "7d")]
    D7,
    #[serde(rename = "30d")]
    D30,
}

impl WalletTrackerSummaryPeriod {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::H24 => "24h",
            Self::D7 => "7d",
            Self::D30 => "30d",
        }
    }
}

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

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

impl WalletTrackerAction {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Buy => "buy",
            Self::Sell => "sell",
            Self::TransferIn => "transfer_in",
            Self::TransferOut => "transfer_out",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CoordinationDeliveryMode {
    Websocket,
    Webhook,
    Both,
}

impl CoordinationDeliveryMode {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Websocket => "websocket",
            Self::Webhook => "webhook",
            Self::Both => "both",
        }
    }
}

// ─── KOL ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolFeedParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Cursor — return trades strictly older than this ISO 8601 timestamp.
    /// Pass `next_before` from the previous response for polling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<KolAction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_sol: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_age_max_min: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exclude_sells: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kol_winrate: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strategy: Option<KolStrategy>,
    /// v0.7 — Lower bound on `market_cap_usd_at_trade`. Trades with unknown MC drop out.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc_usd: Option<f64>,
    /// v0.7 — Upper bound on `market_cap_usd_at_trade`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc_usd: Option<f64>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolLeaderboardParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<LeaderboardPeriod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<KolLeaderboardSort>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strategy: Option<KolStrategy>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_winrate: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolWalletParams {
    /// Comma-separated extras: "pnl_by_token", "recent_winners", "recent_losers".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolCoordinationParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<CoordinationPeriod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kols: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_avg_winrate: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unique_strategies: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_majors: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_minutes: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_score: Option<u32>,
    /// v0.7 — Lower bound on entry MC (MC at first KOL buy).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc_usd: Option<f64>,
    /// v0.7 — Upper bound on entry MC.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc_usd: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolTradeDeployer {
    pub wallet: String,
    pub tier: String,
    #[serde(default)]
    pub bonding_rate: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolTrade {
    pub tx_signature: String,
    pub wallet_address: String,
    #[serde(default)]
    pub kol_name: Option<String>,
    #[serde(default)]
    pub kol_twitter: Option<String>,
    pub action: KolAction,
    pub token_mint: String,
    #[serde(default)]
    pub token_name: Option<String>,
    #[serde(default)]
    pub token_symbol: Option<String>,
    #[serde(default)]
    pub token_image_url: Option<String>,
    pub sol_amount: f64,
    pub token_amount: f64,
    /// Token market cap in USD at the moment of trade (real-time, sourced
    /// from our in-memory price tracker — not Dexscreener spot, which lags).
    #[serde(default)]
    pub market_cap_usd_at_trade: Option<f64>,
    /// Token price in USD at the moment of trade.
    #[serde(default)]
    pub price_usd_at_trade: Option<f64>,
    pub traded_at: String,
    #[serde(default)]
    pub kol_strategy_tag: Option<String>,
    #[serde(default)]
    pub kol_auto_strategy_tag: Option<String>,
    #[serde(default)]
    pub kol_winrate_7d: Option<f64>,
    #[serde(default)]
    pub kol_winrate_30d: Option<f64>,
    #[serde(default)]
    pub kol_early_entry_pct_30d: Option<f64>,
    #[serde(default)]
    pub kol_is_heating_up: Option<bool>,
    #[serde(default)]
    pub kol_percentile_pnl_7d: Option<f64>,
    #[serde(default)]
    pub kol_percentile_winrate_7d: Option<f64>,
    #[serde(default)]
    pub token_age_minutes: Option<f64>,
    #[serde(default)]
    pub deployer: Option<KolTradeDeployer>,
    #[serde(default)]
    pub deployer_tier: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolFeedResponse {
    pub trades: Vec<KolTrade>,
    pub count: u32,
    #[serde(default)]
    pub data_age_seconds: Option<u64>,
    /// Cursor for the next page — pass as `before` to fetch older trades.
    #[serde(default)]
    pub next_before: Option<String>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolLeaderboardEntry {
    #[serde(default)]
    pub name: Option<String>,
    pub wallet: String,
    #[serde(default)]
    pub strategy_tag: Option<String>,
    #[serde(default)]
    pub auto_strategy_tag: Option<String>,
    pub pnl: f64,
    pub buy_count: u64,
    pub sell_count: u64,
    pub volume: f64,
    #[serde(default)]
    pub win_rate: Option<f64>,
    #[serde(default)]
    pub avg_roi: Option<f64>,
    #[serde(default)]
    pub profit_factor: Option<f64>,
    #[serde(default)]
    pub early_entry_pct_30d: Option<f64>,
    #[serde(default)]
    pub consistency_7d: Option<f64>,
    #[serde(default)]
    pub is_heating_up: Option<bool>,
    #[serde(default)]
    pub is_cold: Option<bool>,
    #[serde(default)]
    pub percentile_pnl_7d: Option<f64>,
    #[serde(default)]
    pub percentile_winrate_7d: Option<f64>,
    #[serde(default)]
    pub percentile_pnl_30d: Option<f64>,
    #[serde(default)]
    pub percentile_winrate_30d: Option<f64>,
    /// Median position hold time in minutes over the trailing 30 days.
    #[serde(default)]
    pub median_hold_minutes_30d: Option<f64>,
    /// Percentile rank for early-entry rate over the trailing 30 days (0–100).
    #[serde(default)]
    pub percentile_early_entry_30d: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolLeaderboardResponse {
    pub leaderboard: Vec<KolLeaderboardEntry>,
    pub period: String,
    #[serde(default)]
    pub sort: Option<String>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPnlByToken {
    pub mint: String,
    pub token_name: Option<String>,
    pub token_symbol: Option<String>,
    pub realized_pnl_usd: f64,
    pub buy_count: u32,
    pub sell_count: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolWalletProfile {
    pub wallet: String,
    pub kol_name: Option<String>,
    pub kol_twitter: Option<String>,
    pub total_pnl_usd: f64,
    pub win_rate: f64,
    pub trade_count: u32,
    #[serde(default)]
    pub pnl_by_token: Option<Vec<KolPnlByToken>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinationKol {
    pub name: String,
    pub wallet: String,
    #[serde(default)]
    pub buy_sol: Option<f64>,
    #[serde(default)]
    pub sell_sol: Option<f64>,
    #[serde(default)]
    pub exited: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinatedToken {
    pub token_mint: String,
    pub token_name: Option<String>,
    pub token_symbol: Option<String>,
    pub kol_count: u32,
    pub total_buys: u64,
    pub total_sells: u64,
    pub net_sol_flow: f64,
    pub signal: String,
    pub avg_winrate_7d: Option<f64>,
    pub entry_rank_avg: Option<f64>,
    pub unique_strategies: u32,
    pub strategies: Vec<String>,
    pub first_buy_at: String,
    pub last_buy_at: String,
    pub time_to_consensus_sec: i64,
    #[serde(default)]
    pub peak_window_start: Option<String>,
    #[serde(default)]
    pub peak_window_end: Option<String>,
    #[serde(default)]
    pub peak_kols: Option<u32>,
    #[serde(default)]
    pub peak_buys: Option<u64>,
    #[serde(default)]
    pub exited_count: Option<u32>,
    #[serde(default)]
    pub holders_count: Option<u32>,
    #[serde(default)]
    pub coordination_score: Option<u32>,
    /// v0.6 (2026-05-06) — market cap (USD) stamped on the cluster's chronologically-first KOL buy.
    #[serde(default)]
    pub market_cap_usd_at_first_buy: Option<f64>,
    /// v0.6 — current market cap (USD), from `token_prices`.
    #[serde(default)]
    pub market_cap_usd: Option<f64>,
    /// v0.6 — current last-trade price (USD).
    #[serde(default)]
    pub last_price_usd: Option<f64>,
    #[serde(default)]
    pub kols: Option<Vec<CoordinationKol>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolCoordinationResponse {
    pub coordination: Vec<CoordinatedToken>,
    #[serde(default)]
    pub score_version: Option<String>,
    #[serde(default)]
    pub window_minutes: Option<u32>,
    #[serde(default)]
    pub period: Option<String>,
    #[serde(default)]
    pub min_kols: Option<u32>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolTokenActivity {
    pub mint: String,
    pub token_name: Option<String>,
    pub token_symbol: Option<String>,
    pub kol_buyers: Vec<String>,
    pub kol_sellers: Vec<String>,
    pub buy_count: u32,
    pub sell_count: u32,
    pub total_sol_volume: f64,
    pub recent_trades: Vec<KolTrade>,
}

// ─── KOL pairs / timing / hot-tokens / pnl / trending ───────────────────────

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolPairsParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_shared: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPairMember {
    pub name: String,
    #[serde(default)]
    pub wallet: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPair {
    pub kol_a: KolPairMember,
    pub kol_b: KolPairMember,
    pub shared_token_count: u32,
    #[serde(default)]
    pub agreement_rate: Option<f64>,
    #[serde(default)]
    pub shared_tokens: Option<Vec<String>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPairsResponse {
    pub pairs: Vec<KolPair>,
    pub period: String,
    pub min_shared: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolTimingParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolTimingProfile {
    pub tokens_traded: u32,
    pub positions_closed: u32,
    pub avg_hold_minutes: Option<f64>,
    #[serde(default)]
    pub median_hold_minutes: Option<f64>,
    #[serde(default)]
    pub pct_closed_1h: Option<f64>,
    #[serde(default)]
    pub pct_closed_6h: Option<f64>,
    #[serde(default)]
    pub pct_closed_24h: Option<f64>,
    #[serde(default)]
    pub avg_buy_size_sol: Option<f64>,
    #[serde(default)]
    pub avg_sell_size_sol: Option<f64>,
    #[serde(default)]
    pub most_active_hours: Option<Vec<u32>>,
    #[serde(default)]
    pub hour_distribution: Option<HashMap<String, f64>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolTimingResponse {
    pub kol: KolPairMember,
    pub timing: KolTimingProfile,
    pub period: String,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolHotTokensParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kols: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_avg_winrate: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unique_strategies: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct HotToken {
    pub token_mint: String,
    pub token_symbol: String,
    pub token_name: String,
    pub kols_total: u32,
    pub kols_recent: u32,
    pub acceleration: f64,
    pub total_buy_sol: f64,
    pub total_sell_sol: f64,
    pub net_flow: f64,
    pub first_kol_buy_age_minutes: Option<f64>,
    #[serde(default)]
    pub kols: Option<Vec<KolPairMember>>,
    #[serde(default)]
    pub token_image_url: Option<String>,
    #[serde(default)]
    pub first_kol_buy_at: Option<String>,
    #[serde(default)]
    pub last_kol_buy_at: Option<String>,
    #[serde(default)]
    pub time_to_consensus_sec: Option<i64>,
    #[serde(default)]
    pub avg_winrate_7d: Option<f64>,
    #[serde(default)]
    pub entry_rank_avg: Option<f64>,
    #[serde(default)]
    pub unique_strategies: Option<u32>,
    #[serde(default)]
    pub strategies: Option<Vec<String>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolHotTokensResponse {
    pub hot_tokens: Vec<HotToken>,
    pub period: String,
    pub min_kols: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolPnlParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPnlSummary {
    pub realized_pnl_sol: f64,
    pub total_volume_sol: f64,
    pub tokens_traded: u32,
    pub closed_positions: u32,
    pub open_positions: u32,
    pub win_count: u32,
    pub loss_count: u32,
    pub win_rate: Option<f64>,
    pub profit_factor: Option<f64>,
    pub best_trade_pnl_sol: f64,
    pub worst_trade_pnl_sol: f64,
    pub avg_roi_pct: Option<f64>,
    pub avg_hold_minutes: f64,
    pub median_hold_minutes: f64,
    pub max_drawdown_sol: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPnlCurvePoint {
    pub date: String,
    pub day_pnl: f64,
    pub cumulative_pnl: f64,
    pub trades: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolClosedPosition {
    pub token_mint: String,
    pub token_symbol: String,
    pub token_name: String,
    pub buy_count: u32,
    pub sell_count: u32,
    pub bought_sol: f64,
    pub sold_sol: f64,
    pub pnl_sol: f64,
    pub roi_pct: f64,
    pub hold_minutes: f64,
    pub result: String,
    pub first_trade: String,
    pub last_trade: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolOpenPosition {
    pub token_mint: String,
    pub token_symbol: String,
    pub token_name: String,
    pub buy_count: u32,
    pub bought_sol: f64,
    pub first_buy_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPnlIdentity {
    pub name: String,
    #[serde(default)]
    pub wallet: Option<String>,
    #[serde(default)]
    pub twitter_url: Option<String>,
    #[serde(default)]
    pub strategy_tag: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolPnlResponse {
    pub kol: KolPnlIdentity,
    pub summary: KolPnlSummary,
    #[serde(default)]
    pub pnl_curve: Option<Vec<KolPnlCurvePoint>>,
    #[serde(default)]
    pub closed_positions: Option<Vec<KolClosedPosition>>,
    #[serde(default)]
    pub open_positions: Option<Vec<KolOpenPosition>>,
    pub period: String,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolTrendingParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kols: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TrendingToken {
    pub token_mint: String,
    pub token_symbol: String,
    pub token_name: String,
    pub buy_volume_sol: f64,
    pub sell_volume_sol: f64,
    pub net_flow_sol: f64,
    pub buy_count: u32,
    pub sell_count: u32,
    pub kol_count: u32,
    pub latest_buy_age_minutes: Option<f64>,
    #[serde(default)]
    pub token_image_url: Option<String>,
    #[serde(default)]
    pub first_buy_at: Option<String>,
    #[serde(default)]
    pub latest_buy_at: Option<String>,
    #[serde(default)]
    pub kols: Option<Vec<KolPairMember>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolTrendingResponse {
    pub trending: Vec<TrendingToken>,
    pub period: String,
    pub min_kols: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── KOL entry-order / compare / alerts ─────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolEntryOrderParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolEntryOrderEntry {
    pub rank: u32,
    pub kol_name: Option<String>,
    pub kol_twitter: Option<String>,
    pub wallet: String,
    pub strategy_tag: Option<String>,
    pub auto_strategy_tag: Option<String>,
    pub winrate_7d: Option<f64>,
    pub winrate_30d: Option<f64>,
    pub early_entry_pct_30d: Option<f64>,
    #[serde(default)]
    pub percentile_pnl_7d: Option<f64>,
    #[serde(default)]
    pub percentile_winrate_7d: Option<f64>,
    pub first_buy_at: String,
    pub seconds_after_first: f64,
    pub sol_amount: f64,
    pub token_amount: f64,
    #[serde(default)]
    pub tx_signature: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolEntryOrderResponse {
    pub token_mint: String,
    pub token_name: Option<String>,
    pub token_symbol: Option<String>,
    pub total_kol_buyers: u32,
    pub first_buy_at: String,
    pub last_buy_at: String,
    pub span_sec: i64,
    pub entries: Vec<KolEntryOrderEntry>,
}

#[derive(Debug, Clone)]
pub struct KolCompareParams {
    /// 2–5 Solana wallet addresses. Tier limit: BASIC=2, PRO=4, ULTRA=5.
    pub wallets: Vec<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolCompareProfile {
    pub wallet: String,
    pub found: bool,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub twitter_url: Option<String>,
    #[serde(default)]
    pub strategy_tag: Option<String>,
    #[serde(default)]
    pub auto_strategy_tag: Option<String>,
    #[serde(default)]
    pub winrate_7d: Option<f64>,
    #[serde(default)]
    pub winrate_30d: Option<f64>,
    #[serde(default)]
    pub avg_roi_7d: Option<f64>,
    #[serde(default)]
    pub avg_roi_30d: Option<f64>,
    #[serde(default)]
    pub profit_factor_7d: Option<f64>,
    #[serde(default)]
    pub profit_factor_30d: Option<f64>,
    #[serde(default)]
    pub pnl_7d: Option<f64>,
    #[serde(default)]
    pub pnl_30d: Option<f64>,
    #[serde(default)]
    pub early_entry_pct_30d: Option<f64>,
    #[serde(default)]
    pub consistency_7d: Option<f64>,
    #[serde(default)]
    pub median_hold_minutes_30d: Option<f64>,
    #[serde(default)]
    pub closed_positions_7d: Option<u32>,
    #[serde(default)]
    pub closed_positions_30d: Option<u32>,
    #[serde(default)]
    pub is_heating_up: Option<bool>,
    #[serde(default)]
    pub is_cold: Option<bool>,
    #[serde(default)]
    pub percentile_pnl_7d: Option<f64>,
    #[serde(default)]
    pub percentile_winrate_7d: Option<f64>,
    #[serde(default)]
    pub percentile_pnl_30d: Option<f64>,
    #[serde(default)]
    pub percentile_winrate_30d: Option<f64>,
    #[serde(default)]
    pub percentile_early_entry_30d: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolCompareOverlapToken {
    pub token_mint: String,
    pub token_symbol: Option<String>,
    pub token_name: Option<String>,
    pub wallets: Vec<String>,
    pub buy_count: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolCompareResponse {
    pub profiles: Vec<KolCompareProfile>,
    #[serde(default)]
    pub overlap: Option<Vec<KolCompareOverlapToken>>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct KolAlertsParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub types: Option<Vec<String>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolAlert {
    #[serde(rename = "type")]
    pub alert_type: String,
    pub severity: String,
    pub detected_at: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolAlertsResponse {
    pub alerts: Vec<KolAlert>,
    pub count: u32,
    pub window: String,
    pub types: Vec<String>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Scout leaderboard (v1.9) ───────────────────────────────────────────────

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScoutLeaderboardSort {
    Swarm3PlusPct,
    NFirstTouches30d,
    Swarm5PlusPct,
    ScoutScore,
}

impl ScoutLeaderboardSort {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Swarm3PlusPct => "swarm_3plus_pct",
            Self::NFirstTouches30d => "n_first_touches_30d",
            Self::Swarm5PlusPct => "swarm_5plus_pct",
            Self::ScoutScore => "scout_score",
        }
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct ScoutLeaderboardParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scout_tier: Option<ScoutTier>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<ScoutLeaderboardSort>,
}

// ─── Coordination history (v1.9) ────────────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize)]
pub struct CoordinationHistoryParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_score: Option<u32>,
}

// ─── KOL consensus (v1.9) ──────────────────────────────────────────────────

#[derive(Debug, Clone, Deserialize)]
pub struct KolConsensusResponse {
    pub total_kol_buyers: u32,
    pub total_kol_sellers: u32,
    #[serde(default)]
    pub kol_exit_rate: Option<f64>,
    pub net_flow_sol: f64,
    pub total_buy_sol: f64,
    pub total_sell_sol: f64,
    #[serde(default)]
    pub first_kol_buy_at: Option<String>,
    #[serde(default)]
    pub last_kol_buy_at: Option<String>,
    #[serde(default)]
    pub first_touch_wallet: Option<String>,
    #[serde(default)]
    pub first_touch_at: Option<String>,
    #[serde(default)]
    pub median_entry_mc_usd: Option<f64>,
    /// ULTRA only — individual buyer wallet addresses.
    #[serde(default)]
    pub buyers: Option<Vec<String>>,
    /// ULTRA only — wallets that have fully exited.
    #[serde(default)]
    pub exited: Option<Vec<String>>,
}

// ─── Peak history (v1.9) ───────────────────────────────────────────────────

#[derive(Debug, Clone, Deserialize)]
pub struct PeakHistoryResponse {
    #[serde(default)]
    pub peak_mc_usd: Option<f64>,
    #[serde(default)]
    pub peak_mc_updated_at: Option<String>,
    #[serde(default)]
    pub current_mc_usd: Option<f64>,
    #[serde(default)]
    pub current_price_usd: Option<f64>,
    #[serde(default)]
    pub decline_from_peak_pct: Option<f64>,
    #[serde(default)]
    pub mc_at_bond: Option<f64>,
    #[serde(default)]
    pub mc_1h_after_bond: Option<f64>,
    #[serde(default)]
    pub mc_6h_after_bond: Option<f64>,
    #[serde(default)]
    pub mc_24h_after_bond: Option<f64>,
    #[serde(default)]
    pub mc_7d_after_bond: Option<f64>,
    #[serde(default)]
    pub still_alive_1h: Option<bool>,
    #[serde(default)]
    pub time_to_bond_minutes: Option<f64>,
    #[serde(default)]
    pub deployed_at: Option<String>,
    #[serde(default)]
    pub bonded_at: Option<String>,
}

// ─── Coordination alerts (v1.1) ─────────────────────────────────────────────

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinationAlertRule {
    pub id: String,
    pub name: Option<String>,
    pub min_kols: u32,
    pub window_minutes: u32,
    pub min_score: u32,
    pub include_majors: bool,
    pub cooldown_min: u32,
    pub score_jump_break: u32,
    pub delivery_mode: CoordinationDeliveryMode,
    pub webhook_url: Option<String>,
    /// v0.7 — entry-MC band on the rule (None = open-ended).
    #[serde(default)]
    pub min_mc_usd: Option<f64>,
    #[serde(default)]
    pub max_mc_usd: Option<f64>,
    pub is_active: bool,
    pub created_at: String,
    #[serde(default)]
    pub updated_at: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct CoordinationAlertCreateParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kols: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_minutes: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_score: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_majors: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cooldown_min: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score_jump_break: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_mode: Option<CoordinationDeliveryMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// v0.7 — entry-MC band the rule will require for triggers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc_usd: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc_usd: Option<f64>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct CoordinationAlertUpdateParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kols: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_minutes: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_score: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_majors: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cooldown_min: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score_jump_break: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_mode: Option<CoordinationDeliveryMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    /// v0.7 — pass `Some(0.0)` etc. to update the band; `None` leaves unchanged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc_usd: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc_usd: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinationAlertListResponse {
    pub rules: Vec<CoordinationAlertRule>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinationAlertCreateResponse {
    pub rule: CoordinationAlertRule,
    /// One-time HMAC secret. Save it — will not be shown again.
    pub webhook_secret: Option<String>,
    #[serde(default)]
    pub note: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinationAlertGetResponse {
    pub rule: CoordinationAlertRule,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinationAlertUpdateResponse {
    pub rule: CoordinationAlertRule,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CoordinationAlertDeleteResponse {
    pub deleted: bool,
}

// ─── First-touch signal ────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
pub enum ScoutTier {
    #[serde(rename = "S")] S,
    #[serde(rename = "A")] A,
    #[serde(rename = "B")] B,
    #[serde(rename = "C")] C,
}

impl ScoutTier {
    pub fn as_str(&self) -> &'static str {
        match self {
            ScoutTier::S => "S",
            ScoutTier::A => "A",
            ScoutTier::B => "B",
            ScoutTier::C => "C",
        }
    }
}

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

#[derive(Debug, Clone, Default, Serialize)]
pub struct FirstTouchesParams {
    /// ISO datetime — events strictly newer than this. Polling cursor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    /// ISO datetime — events strictly older than this. Pagination cursor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// 1–100. Default: 50 (BASIC capped at 20).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Single KOL wallet (32–44 base58 chars).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kol: Option<String>,
    /// 0–100.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kol_winrate_7d: Option<f64>,
    /// Restrict to scouts of this tier or better. Requires `n_first_touches_30d >= 30`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_scout_tier: Option<ScoutTier>,
    /// Lower the minimum sample size for scout scoring (default 30).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_n_touches: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strategy: Option<KolStrategy>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_age_max_min: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_first_buy_sol: Option<f64>,
    /// Suffix-filter the token mint (e.g. "pump", "bonk").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mint_suffix: Option<String>,
    /// Shortcut filter sets — `scout` = min_scout_tier=B + min_n_touches=30 + token_age_max_min=60.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preset: Option<FirstTouchPreset>,
    /// Comma-separated includes — currently `followers_4h`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include: Option<String>,
    /// v0.7 — Lower bound on `market_cap_usd_at_first_buy`. Touches with unknown MC drop out.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc_usd: Option<f64>,
    /// v0.7 — Upper bound on `market_cap_usd_at_first_buy`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc_usd: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchKol {
    /// Wallet address — only present on Ultra tier.
    #[serde(default)]
    pub wallet: Option<String>,
    pub name: Option<String>,
    pub twitter_url: Option<String>,
    pub winrate_7d: Option<f64>,
    pub strategy: Option<String>,
    pub scout_tier: Option<ScoutTier>,
    /// Same as swarm_3plus_pct on the scout leaderboard.
    pub scout_score: Option<f64>,
    pub n_first_touches_30d: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchEvent {
    pub token_mint: String,
    pub token_symbol: Option<String>,
    pub token_name: Option<String>,
    pub token_image_url: Option<String>,
    pub first_buy_at: String,
    pub sol_amount: Option<f64>,
    pub token_amount: Option<f64>,
    pub tx_signature: Option<String>,
    pub token_age_minutes: Option<u32>,
    pub first_kol: FirstTouchKol,
    #[serde(default)]
    pub followers_4h: Option<u32>,
    /// v0.6 (2026-05-06) — market cap (USD) stamped on the exact tx that fired
    /// the first KOL buy, joined via `tx_signature`.
    #[serde(default)]
    pub market_cap_usd_at_first_buy: Option<f64>,
    /// v0.6 — token price (USD) at the same moment.
    #[serde(default)]
    pub price_usd_at_first_buy: Option<f64>,
    /// v0.6 — current market cap (USD), from `token_prices`.
    #[serde(default)]
    pub market_cap_usd: Option<f64>,
    /// v0.6 — current last-trade price (USD).
    #[serde(default)]
    pub last_price_usd: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchesResponse {
    pub events: Vec<FirstTouchEvent>,
    pub count: u32,
    pub next_before: Option<String>,
    pub data_age_seconds: Option<u32>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FirstTouchSubscriptionFilters {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mint_suffix: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_first_buy_sol: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_scout_tier: Option<ScoutTier>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_n_touches: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchSubscription {
    pub id: String,
    pub name: Option<String>,
    pub filters: FirstTouchSubscriptionFilters,
    pub delivery_mode: CoordinationDeliveryMode,
    pub webhook_url: Option<String>,
    /// v0.7 — first-touch MC band on the subscription (None = open-ended).
    #[serde(default)]
    pub min_mc_usd: Option<f64>,
    #[serde(default)]
    pub max_mc_usd: Option<f64>,
    pub is_active: bool,
    pub created_at: String,
    #[serde(default)]
    pub updated_at: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct FirstTouchSubscriptionCreateParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<FirstTouchSubscriptionFilters>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_mode: Option<CoordinationDeliveryMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// v0.7 — first-touch MC band on the subscription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc_usd: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc_usd: Option<f64>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct FirstTouchSubscriptionUpdateParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<FirstTouchSubscriptionFilters>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_mode: Option<CoordinationDeliveryMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// v0.7 — pass `Some(0.0)` etc. to update the band; `None` leaves unchanged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc_usd: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc_usd: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchSubscriptionListResponse {
    pub subscriptions: Vec<FirstTouchSubscription>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchSubscriptionCreateResponse {
    pub subscription: FirstTouchSubscription,
    /// One-time HMAC secret. Save it — will not be shown again.
    pub webhook_secret: Option<String>,
    #[serde(default)]
    pub note: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchSubscriptionGetResponse {
    pub subscription: FirstTouchSubscription,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchSubscriptionUpdateResponse {
    pub subscription: FirstTouchSubscription,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FirstTouchSubscriptionDeleteResponse {
    pub ok: bool,
}

// ─── Deployer Hunter ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize)]
pub struct DeployerLeaderboardParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<DeployerTier>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<DeployerSortField>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct DeployerTokensParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct DeployerAlertsParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    /// Cursor — return alerts strictly older than this ISO 8601 timestamp.
    /// Pass `next_before` from previous response. Preferred over `offset` at scale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
    /// PRO/ULTRA only. BASIC subscribers receive HTTP 403.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<DeployerTier>,
    /// Filter by alert_type (e.g. "new_deploy", "bonded").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alert_type: Option<String>,
    /// Filter by alert priority ("high" | "medium" | "low").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<String>,
    /// Only alerts where at least N KOLs bought the token.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_kol_buys: Option<u32>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct DeployerAlertStatsParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<AlertPeriod>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct BestTokensParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<BestTokensPeriod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct RecentBondsParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// ISO 8601 datetime — only bonds strictly newer than this timestamp.
    /// Pass `next_since` from the previous response for incremental polling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    /// Filter by deployer reputation tier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<DeployerTier>,
    /// Only bonds that reached at least this peak market cap (USD).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub peak_mc_min: Option<u64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerTierCounts {
    pub elite: u32,
    pub good: u32,
    pub rising: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerStats {
    pub tracked_count: u32,
    pub signals_today: u32,
    pub bonds_detected: u32,
    pub bond_rate: f64,
    pub tiers: DeployerTierCounts,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Shared: DeployerSummary (used by RecentBond, DeployerAlert) ─────────────

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerSummary {
    pub wallet_address: String,
    pub tier: DeployerTier,
    #[serde(default)]
    pub bonding_rate: Option<f64>,
    #[serde(default)]
    pub total_bonded: Option<u32>,
    #[serde(default)]
    pub recent_outcomes: Option<String>,
    #[serde(default)]
    pub recent_bond_rate: Option<f64>,
    #[serde(default)]
    pub total_tokens_deployed: Option<u32>,
    /// Peak market cap (USD) of this deployer's best token to date. Populated on alert rows.
    #[serde(default)]
    pub best_token_peak_mc: Option<f64>,
    /// Fraction of the deployer's labeled tokens that ran (peak >=60min after deploy) vs dumped.
    #[serde(default)]
    pub runner_rate: Option<f64>,
    /// Confidence denominator; gate on >=3.
    #[serde(default)]
    pub labeled_tokens: Option<i64>,
    #[serde(default)]
    pub avg_time_to_bond_minutes: Option<i64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerLeaderboardEntry {
    pub id: String,
    pub wallet_address: String,
    pub tier: DeployerTier,
    pub bonding_rate: f64,
    pub recent_bond_rate: f64,
    pub total_tokens_deployed: u32,
    pub total_bonded: u32,
    #[serde(default)]
    pub last_deploy_at: Option<String>,
    #[serde(default)]
    pub recent_outcomes: Option<String>,
    #[serde(default)]
    pub avg_time_to_bond_minutes: Option<f64>,
    /// Fraction of the deployer's labeled tokens that ran (peak >=60min after deploy) vs dumped.
    #[serde(default)]
    pub runner_rate: Option<f64>,
    /// Confidence denominator; gate on >=3.
    #[serde(default)]
    pub labeled_tokens: Option<i64>,
    #[serde(default)]
    pub best_token_peak_mc: Option<f64>,
    #[serde(default)]
    pub avg_peak_mc: Option<f64>,
    #[serde(default)]
    pub last_bond_at: Option<String>,
    #[serde(default)]
    pub is_tracked: Option<bool>,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub first_seen_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerLeaderboardResponse {
    pub deployers: Vec<DeployerLeaderboardEntry>,
    pub total: u32,
    pub limit: u32,
    pub offset: u32,
    pub has_more: bool,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerToken {
    pub mint: String,
    pub name: Option<String>,
    pub symbol: Option<String>,
    pub bonded: bool,
    pub deployed_at: String,
    pub bonded_at: Option<String>,
    pub peak_market_cap_usd: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerProfile {
    pub wallet: String,
    pub tier: DeployerTier,
    pub bonding_rate: f64,
    pub recent_bond_rate: f64,
    pub total_deployed: u32,
    pub total_bonded: u32,
    pub last_deploy_at: Option<String>,
    pub first_seen: Option<String>,
    /// Fraction of the deployer's labeled tokens that ran (peak >=60min after deploy) vs dumped.
    #[serde(default)]
    pub runner_rate: Option<f64>,
    /// Confidence denominator; gate on >=3.
    #[serde(default)]
    pub labeled_tokens: Option<i64>,
    #[serde(default)]
    pub avg_time_to_bond_minutes: Option<i64>,
    #[serde(default)]
    pub tokens: Option<Vec<DeployerToken>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerTokensResponse {
    pub tokens: Vec<DeployerToken>,
    pub count: u32,
    pub total: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KolBuysSummary {
    pub count: u32,
    pub total_sol: f64,
    pub kols: Vec<serde_json::Value>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerAlert {
    pub id: String,
    pub token_mint: String,
    #[serde(default)]
    pub token_name: Option<String>,
    #[serde(default)]
    pub token_symbol: Option<String>,
    pub alert_type: String,
    pub title: String,
    pub message: String,
    pub priority: String,
    pub created_at: String,
    #[serde(default)]
    pub market_cap_at_alert: Option<f64>,
    /// Deployer wallet's SOL balance at alert time, in SOL. `None` when unknown.
    #[serde(default)]
    pub deployer_sol_balance: Option<f64>,
    pub deployers: DeployerSummary,
    #[serde(default)]
    pub kol_buys: Option<KolBuysSummary>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerAlertsResponse {
    pub alerts: Vec<DeployerAlert>,
    pub limit: u32,
    pub offset: u32,
    /// Cursor for the next page — pass as `before` to fetch older alerts.
    #[serde(default)]
    pub next_before: Option<String>,
    #[serde(default)]
    pub data_age_seconds: Option<u64>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BondRateStats {
    pub total_deploys: u32,
    pub total_bonded: u32,
    pub rate: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MultiplierStats {
    pub total_with_mc: u32,
    pub pct_2x: f64,
    pub pct_5x: f64,
    pub pct_10x: f64,
    pub pct_50x: f64,
    pub avg_multiplier: f64,
    pub best_multiplier: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TierStats {
    pub deploys: u32,
    pub bonded: u32,
    pub bond_rate: f64,
    #[serde(default)]
    pub avg_multiplier: Option<f64>,
    pub total_with_mc: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerAlertStats {
    pub bond_rate: BondRateStats,
    pub multiplier: MultiplierStats,
    pub tiers: HashMap<String, TierStats>,
    pub period: String,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BestToken {
    pub id: String,
    pub token_mint: String,
    #[serde(default)]
    pub token_name: Option<String>,
    #[serde(default)]
    pub token_symbol: Option<String>,
    #[serde(default)]
    pub token_image_url: Option<String>,
    pub bonded_at: String,
    #[serde(default)]
    pub peak_market_cap: Option<f64>,
    #[serde(default)]
    pub mc_at_bond: Option<f64>,
    #[serde(default)]
    pub market_cap_at_alert: Option<f64>,
    #[serde(default)]
    pub mc_multiplier: Option<f64>,
    pub deployer_wallet: String,
    pub deployer_tier: DeployerTier,
    #[serde(default)]
    pub alerted_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BestTokensResponse {
    pub tokens: Vec<BestToken>,
    pub period: String,
    pub limit: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecentBond {
    pub id: String,
    pub token_mint: String,
    #[serde(default)]
    pub token_name: Option<String>,
    #[serde(default)]
    pub token_symbol: Option<String>,
    #[serde(default)]
    pub token_image_url: Option<String>,
    pub deployed_at: String,
    pub bonded_at: String,
    #[serde(default)]
    pub time_to_bond_minutes: Option<f64>,
    #[serde(default)]
    pub peak_market_cap: Option<f64>,
    #[serde(default)]
    pub mc_at_bond: Option<f64>,
    pub deployers: DeployerSummary,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RecentBondsResponse {
    pub tokens: Vec<RecentBond>,
    pub limit: u32,
    /// Cursor for incremental polling — pass as `since` on the next call to
    /// fetch only newer bonds.
    #[serde(default)]
    pub next_since: Option<String>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerStreak {
    #[serde(rename = "type")]
    pub streak_type: String,
    pub count: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerRollingRate {
    pub window_end: u32,
    pub bond_rate: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerStretch {
    pub start_index: u32,
    pub end_index: u32,
    pub bond_rate: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerTrajectoryData {
    pub current_streak: DeployerStreak,
    pub longest_bond_streak: u32,
    pub longest_fail_streak: u32,
    pub rolling_bond_rates: Vec<DeployerRollingRate>,
    pub trend: String,
    pub avg_days_between_deploys: Option<f64>,
    pub avg_recovery_tokens: Option<f64>,
    pub best_stretch: Option<DeployerStretch>,
    pub worst_stretch: Option<DeployerStretch>,
    pub total_tokens_analyzed: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerTrajectoryDeployer {
    pub wallet_address: String,
    pub total_tokens_deployed: u32,
    pub total_bonded: u32,
    pub bonding_rate: f64,
    pub recent_bond_rate: f64,
    pub tier: String,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct DeployerTrajectoryParams {
    /// Pass `"daily_snapshots"` for up to 90 daily tier/bonding snapshots.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerDailySnapshot {
    pub snapshot_date: String,
    pub tier: String,
    pub total_tokens_deployed: u32,
    pub total_bonded: u32,
    pub bonding_rate: f64,
    pub recent_bond_rate: f64,
    #[serde(default)]
    pub avg_peak_mc: Option<f64>,
    #[serde(default)]
    pub best_token_peak_mc: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct DeployerTrajectoryResponse {
    pub deployer: DeployerTrajectoryDeployer,
    pub trajectory: DeployerTrajectoryData,
    /// Present when `include=daily_snapshots` is requested.
    #[serde(default)]
    pub daily_snapshots: Option<Vec<DeployerDailySnapshot>>,
}

// ─── Deployer history (/deployer-hunter/{wallet}/history) ────────────────────

/// Query params for [`Deployer::history`](crate::api::deployer::Deployer::history).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct DeployerHistoryParams {
    /// Number of daily snapshots to return (1..=365). Defaults server-side when unset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// A single daily performance snapshot for a deployer wallet.
#[derive(Debug, Clone, Deserialize)]
pub struct DeployerSnapshot {
    /// Snapshot date (ISO 8601).
    pub date: String,
    pub tier: String,
    pub is_tracked: bool,
    pub total_deployed: i64,
    pub total_bonded: i64,
    /// Lifetime bonding rate. `None` when unavailable.
    #[serde(default)]
    pub bonding_rate: Option<f64>,
    /// Recent (rolling) bond rate. `None` when unavailable.
    #[serde(default)]
    pub recent_bond_rate: Option<f64>,
    /// Average peak market cap across deploys. `None` when unavailable.
    #[serde(default)]
    pub avg_peak_mc: Option<f64>,
    /// Peak market cap of the best token. `None` when unavailable.
    #[serde(default)]
    pub best_token_peak_mc: Option<f64>,
}

/// Daily performance snapshots for a deployer wallet.
#[derive(Debug, Clone, Deserialize)]
pub struct DeployerHistoryResponse {
    pub is_deployer: bool,
    pub wallet: String,
    pub snapshots: Vec<DeployerSnapshot>,
}

// ─── Alpha Wallet Intelligence ──────────────────────────────────────────────

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AlphaSort {
    WinRate,
    Pnl,
    Roi,
}

impl AlphaSort {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::WinRate => "win_rate",
            Self::Pnl => "pnl",
            Self::Roi => "roi",
        }
    }
}

pub type AlphaPeriod = AlertPeriod;

#[derive(Debug, Clone, Default, Serialize)]
pub struct AlphaLeaderboardParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<AlphaPeriod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<AlphaSort>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exclude_bots: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaWalletEntry {
    pub rank: u32,
    pub wallet: String,
    pub tokens_traded: u32,
    pub wins: u32,
    pub losses: u32,
    pub win_rate: Option<f64>,
    pub net_pnl_sol: f64,
    #[serde(default)]
    pub total_sol_bought: Option<f64>,
    #[serde(default)]
    pub total_sol_sold: Option<f64>,
    #[serde(default)]
    pub roi: Option<f64>,
    #[serde(default)]
    pub avg_rank: Option<f64>,
    #[serde(default)]
    pub best_rank: Option<f64>,
    #[serde(default)]
    pub total_buys: Option<u32>,
    #[serde(default)]
    pub total_sells: Option<u32>,
    #[serde(default)]
    pub last_seen: Option<String>,
    #[serde(default)]
    pub bundle_rate: Option<f64>,
    #[serde(default)]
    pub buy_size_stddev: Option<f64>,
    #[serde(default)]
    pub active_hours: Option<f64>,
    #[serde(default)]
    pub bot_confidence: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaLeaderboardResponse {
    pub leaderboard: Vec<AlphaWalletEntry>,
    pub total: u32,
    pub period: String,
    pub sort: String,
    pub min_tokens: u32,
    pub exclude_bots: bool,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaWalletPosition {
    pub token_mint: String,
    pub token_symbol: Option<String>,
    pub token_name: Option<String>,
    pub first_buy_at: Option<String>,
    pub last_trade_at: Option<String>,
    pub buy_count: u32,
    pub sell_count: u32,
    pub total_bought_sol: f64,
    pub total_sold_sol: f64,
    pub realized_pnl_sol: f64,
    pub roi_pct: Option<f64>,
    pub result: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaWalletBotSignal {
    pub signal: String,
    pub detail: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaWalletSummary {
    pub tokens_traded: u32,
    pub wins: u32,
    pub losses: u32,
    pub win_rate: Option<f64>,
    pub net_pnl_sol: f64,
    pub total_vol_sol: f64,
    pub roi: Option<f64>,
    pub avg_rank: Option<f64>,
    pub best_rank: Option<f64>,
    pub bundle_rate: f64,
    pub buy_size_stddev: f64,
    pub active_hours: Option<f64>,
    pub bot_confidence: String,
    pub night_only_activity: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaWalletResponse {
    pub wallet: String,
    pub summary: AlphaWalletSummary,
    pub positions: Vec<AlphaWalletPosition>,
    pub bot_signals: Vec<AlphaWalletBotSignal>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaLinkedWallet {
    pub wallet_address: String,
    pub shared_tokens: u32,
    pub similarity_score: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaLinkedResponse {
    pub wallet: String,
    pub linked_wallets: Vec<AlphaLinkedWallet>,
    pub total: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaCapTableBuyer {
    pub rank: u32,
    pub wallet: String,
    pub first_buy_sol: f64,
    pub first_buy_at: Option<String>,
    pub is_bundle: bool,
    pub is_kol: bool,
    pub kol_name: Option<String>,
    pub bot_confidence: Option<String>,
    pub historical_win_rate: Option<f64>,
    pub historical_pnl_sol: Option<f64>,
    pub historical_tokens: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaCapTableSummary {
    pub known_alpha_wallets: u32,
    pub known_kols: u32,
    pub bundle_buyers: u32,
    pub buyer_quality_score: u32,
    pub confidence: String,
    pub signal: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaCapTableResponse {
    pub mint: String,
    pub buyers: Vec<AlphaCapTableBuyer>,
    pub summary: AlphaCapTableSummary,
    /// v0.23.4 — trade-coverage disclosure (`None` on older cached responses).
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaBuyerQualityBreakdown {
    pub alpha_wallet_count: u32,
    pub kol_count: u32,
    pub bundle_buyer_count: u32,
    pub avg_historical_win_rate: Option<f64>,
    pub bot_dominated: bool,
    /// First-20 buyers on the rolling dump-cluster list (wallets whose 5+
    /// recent first-20 appearances are exclusively on tokens that peaked
    /// <15 min after deploy; trailing 42d, refreshed daily). Out-of-sample:
    /// 3+ such wallets predicted a sub-15-min peak 94% of the time vs 61%
    /// base. Informational — does not move the score.
    #[serde(default)]
    pub dump_cluster_count: u32,
    /// First-20 buyers with 5+ recent first-20 appearances of any kind.
    /// Alone it predicts nothing; a heavily recycled cohort with
    /// `dump_cluster_count` 0 historically leans runner.
    #[serde(default)]
    pub recycled_early_buyer_count: u32,
}

/// Payload of a `token:graduation` stream event — every pump.fun graduation
/// (bonding curve complete → PumpSwap migration), tracked deployer or not.
/// Delivered on the `token:graduations` WebSocket channel (PRO+).
#[derive(Debug, Clone, Deserialize)]
pub struct GraduationEvent {
    pub token_mint: String,
    pub token_name: Option<String>,
    pub token_symbol: Option<String>,
    pub time_to_bond_minutes: Option<f64>,
    pub deployer_wallet: Option<String>,
    /// `"unranked"` when the deployer is unknown to deployer-hunter.
    pub deployer_tier: String,
    pub market_cap_usd: Option<f64>,
    pub bonded_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaBuyerQualityResponse {
    pub mint: String,
    pub score: u32,
    pub confidence: String,
    pub signal: String,
    pub cached_at: String,
    #[serde(default)]
    pub breakdown: Option<AlphaBuyerQualityBreakdown>,
    #[serde(default)]
    pub note: Option<String>,
    /// v0.23.4 — trade-coverage disclosure (`None` on older cached responses).
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AlphaBuyerQualityBatchResponse {
    pub tokens: Vec<AlphaBuyerQualityResponse>,
    pub count: u32,
    /// Number of mints served from the shared 5-min LRU cache without a DB query.
    pub cache_hits: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Token intelligence (/token/{mint}) ─────────────────────────────────────

#[derive(Debug, Clone, Deserialize)]
pub struct TokenKolTopBuyer {
    pub name: String,
    pub sol_amount: f64,
    /// ULTRA only — individual KOL wallet address.
    #[serde(default)]
    pub wallet: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokenKolActivity {
    pub buying_kols: u32,
    pub selling_kols: u32,
    pub net_flow_sol: f64,
    /// "accumulating" | "distributing" | "neutral".
    pub signal: String,
    pub top_buyers: Vec<TokenKolTopBuyer>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokenDeployerInfo {
    pub wallet: String,
    pub tier: DeployerTier,
    #[serde(default)]
    pub bonding_rate: Option<f64>,
    #[serde(default)]
    pub total_deployed: Option<u32>,
    #[serde(default)]
    pub total_bonded: Option<u32>,
    #[serde(default)]
    pub recent_bond_rate: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokenResponseBody {
    pub mint: String,
    #[serde(default)]
    pub price_usd: Option<f64>,
    #[serde(default)]
    pub price_sol: Option<f64>,
    #[serde(default)]
    pub market_cap: Option<f64>,
    #[serde(default)]
    pub volume_24h_usd: Option<f64>,
    #[serde(default)]
    pub volume_24h_sol: Option<f64>,
    #[serde(default)]
    pub trades_24h: Option<u32>,
    #[serde(default)]
    pub last_trade_at: Option<String>,
    /// When the mint first appeared in our indexer.
    #[serde(default)]
    pub first_seen_at: Option<String>,
    #[serde(default)]
    pub age_seconds: Option<u64>,
    #[serde(default)]
    pub is_blacklisted: Option<bool>,
    /// "stablecoin" | "wrapped_sol" | "lst" | "rug" | custom category when blacklisted.
    #[serde(default)]
    pub blacklist_category: Option<String>,
    #[serde(default)]
    pub deployer: Option<TokenDeployerInfo>,
    pub kol_activity: TokenKolActivity,
    /// Liquidity-to-MC ratio (`liquidity_usd / market_cap`). Useful for spotting
    /// thin-liquidity tokens where price impact is high.
    #[serde(default)]
    pub liquidity_to_mc_ratio: Option<f64>,
    /// Total SOL spent by the first-20 buyers of this token.
    #[serde(default)]
    pub launch_cohort_sol: Option<f64>,
    /// Count of first-20 buyers of this token (0–20).
    #[serde(default)]
    pub launch_cohort_size: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokenResponse {
    pub token: TokenResponseBody,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokenBatchResponse {
    pub tokens: Vec<TokenResponseBody>,
    pub count: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Token risk score (/tokens/{mint}/risk) ─────────────────────────────────

/// Overall risk band for a token's rug-risk/safety score.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RiskBand {
    Safe,
    Caution,
    Danger,
}

impl RiskBand {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Safe => "safe",
            Self::Caution => "caution",
            Self::Danger => "danger",
        }
    }
}

/// Per-factor status within a token risk breakdown.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RiskFactorStatus {
    Ok,
    Warn,
    Danger,
}

impl RiskFactorStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Warn => "warn",
            Self::Danger => "danger",
        }
    }
}

/// A single contributing factor to a token's risk score.
#[derive(Debug, Clone, Deserialize)]
pub struct RiskFactor {
    /// Stable machine-readable key (e.g. "mint_authority", "liquidity").
    pub key: String,
    /// Human-readable label.
    pub label: String,
    pub status: RiskFactorStatus,
    /// Points this factor contributed to the total risk score.
    pub points: i64,
    /// Explanatory detail for the factor.
    pub detail: String,
}

/// Raw signals the risk score was computed from. Each nullable field is `None`
/// when the underlying data was unavailable at scoring time.
#[derive(Debug, Clone, Deserialize)]
pub struct RiskInputs {
    #[serde(default)]
    pub mint_authority_revoked: Option<bool>,
    #[serde(default)]
    pub freeze_authority_revoked: Option<bool>,
    #[serde(default)]
    pub liquidity_usd: Option<f64>,
    #[serde(default)]
    pub liquidity_to_mc_ratio: Option<f64>,
    pub transfer_fee_bps: i64,
    pub is_token_2022: bool,
    pub burn_detected: bool,
    #[serde(default)]
    pub launch_cohort_sol: Option<f64>,
    pub launch_cohort_size: i64,
    #[serde(default)]
    pub deployer_bonding_rate: Option<f64>,
    #[serde(default)]
    pub deployer_total_deployed: Option<i64>,
    #[serde(default)]
    pub kol_signal: Option<String>,
    pub is_blacklisted: bool,
    /// v0.22 — slot-window launch-snipe rollup ([`SniperFootprint`]). `None`
    /// when no rollup exists for the mint; inside it, `data_available = false`
    /// means "not observable", NOT "0 snipes".
    #[serde(default)]
    pub sniper_footprint: Option<SniperFootprint>,
}

/// v0.23 — Deployer (dev) wallet activity block on a token's risk response.
/// Combines the create-tx dev-buy snapshot, the trade-derived dev-sell rollup
/// (~2 min lag), and a live on-chain holdings check answering "is the dev
/// wallet empty NOW". Every field is `None` when the underlying data is
/// unavailable — never a guess.
#[derive(Debug, Clone, Deserialize)]
pub struct RiskDev {
    /// Deployer wallet address (base58).
    #[serde(default)]
    pub wallet: Option<String>,
    /// Launchpad the token deployed on (e.g. `"pumpfun"`).
    #[serde(default)]
    pub launchpad: Option<String>,
    /// Deploy timestamp (ISO 8601).
    #[serde(default)]
    pub deployed_at: Option<String>,
    /// SOL the dev spent in the create-tx buy. `None` on rows pre-dating the
    /// snapshot or on launchpads without it.
    #[serde(default)]
    pub buy_sol: Option<f64>,
    /// Tokens the dev bought in the create tx (UI units).
    #[serde(default)]
    pub buy_tokens: Option<f64>,
    /// Create-tx dev buy as a percent of total supply.
    #[serde(default)]
    pub buy_supply_pct: Option<f64>,
    /// Tokens the dev bought AFTER the create tx (catches the
    /// same-second-separate-tx dev buy the snapshot reads as 0).
    #[serde(default)]
    pub bought_tokens_after: Option<f64>,
    /// Tokens the dev has sold (trade rollup, ~2 min lag).
    #[serde(default)]
    pub sold_tokens: Option<f64>,
    /// SOL the dev received selling (trade rollup, ~2 min lag).
    #[serde(default)]
    pub sold_sol: Option<f64>,
    /// First dev sell timestamp (ISO 8601).
    #[serde(default)]
    pub first_sell_at: Option<String>,
    /// Most recent dev sell timestamp (ISO 8601).
    #[serde(default)]
    pub last_sell_at: Option<String>,
    /// Live on-chain dev holdings of this mint (UI units). `None` = RPC
    /// unavailable right now.
    #[serde(default)]
    pub holdings_tokens: Option<f64>,
    /// `holdings_tokens` as percent of supply — pump.fun only (fixed 1B
    /// denominator); `None` for other launchpads rather than a wrong number.
    #[serde(default)]
    pub holdings_supply_pct: Option<f64>,
    /// `Some(true)` when the dev wallet holds <1 token on-chain right now.
    /// `None` = couldn't check.
    #[serde(default)]
    pub wallet_empty: Option<bool>,
    /// `Some(true)` when on-chain holdings are well below the trade-derived
    /// expectation — tokens likely moved out without a sell. Only computed
    /// when trade coverage exists AND the sell-rollup cursor is fresh;
    /// otherwise `None` (unknown), never a guess.
    #[serde(default)]
    pub transferred_out: Option<bool>,
}

/// Transparent 0–100 token rug-risk/safety score (PRO/ULTRA). Higher = riskier.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenRisk {
    pub mint: String,
    /// 0–100, higher = riskier.
    pub risk_score: u32,
    pub band: RiskBand,
    /// Per-factor breakdown that sums into `risk_score`.
    pub factors: Vec<RiskFactor>,
    /// Raw inputs the score was derived from.
    pub inputs: RiskInputs,
    pub score_version: String,
    /// v0.23 — deployer wallet activity ([`RiskDev`]): dev buy/sell rollup +
    /// live on-chain holdings. `None` when the mint has no tracked deploy row.
    #[serde(default)]
    pub dev: Option<RiskDev>,
    /// v0.23.4 — trade-coverage disclosure (single-mint `/risk` only). Its
    /// `note` names the split: trade-derived sub-fields are launchpad-pipeline
    /// scoped, on-chain sub-fields are unaffected by trade coverage.
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
    pub as_of: String,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct MintBatchRequest {
    /// 1–50 base58 Solana token mint addresses.
    pub mints: Vec<String>,
}

// ─── Batch token risk (/tokens/batch/risk) ──────────────────────────────────

/// One entry in a [`Token::batch_risk`](crate::api::token::Token::batch_risk)
/// response — either a scored result or an error entry for an untracked mint.
///
/// A scored result populates the risk fields (`risk_score`, `band`, `factors`,
/// `inputs`, `score_version`, `as_of`) exactly like [`TokenRisk`], with `error`
/// set to `None`. An untracked mint comes back as `{ mint, error:
/// Some("not_tracked") }` with the risk fields left `None`/empty — it does
/// **not** fail the batch. Use [`is_error`](Self::is_error), or match on
/// `error`, to tell the two apart.
#[derive(Debug, Clone, Deserialize)]
pub struct BatchRiskResult {
    pub mint: String,
    /// 0–100, higher = riskier. `None` on an error entry.
    #[serde(default)]
    pub risk_score: Option<u32>,
    #[serde(default)]
    pub band: Option<RiskBand>,
    /// Per-factor breakdown that sums into `risk_score`. Empty on an error entry.
    #[serde(default)]
    pub factors: Vec<RiskFactor>,
    /// Raw inputs the score was derived from. `None` on an error entry.
    #[serde(default)]
    pub inputs: Option<RiskInputs>,
    #[serde(default)]
    pub score_version: Option<String>,
    /// ISO-8601 scoring timestamp. `None` on an error entry.
    #[serde(default)]
    pub as_of: Option<String>,
    /// `Some("not_tracked")` when the mint isn't tracked; `None` for a scored result.
    #[serde(default)]
    pub error: Option<String>,
}

impl BatchRiskResult {
    /// `true` when this entry is an error (untracked mint) rather than a score.
    pub fn is_error(&self) -> bool {
        self.error.is_some()
    }
}

/// Response of [`Token::batch_risk`](crate::api::token::Token::batch_risk).
#[derive(Debug, Clone, Deserialize)]
pub struct BatchRiskResponse {
    /// One entry per unique input mint, in de-duplicated input order.
    pub tokens: Vec<BatchRiskResult>,
    /// Number of unique mints returned.
    pub count: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Token bundle intelligence (/tokens/{mint}/bundle) ──────────────────────

/// How a token's early cohort of wallets bought in — the strongest coordination
/// signal detected. `AtomicTx` means multiple wallets bought within a single
/// transaction (a classic bundle); `SameSlot` means they landed in the same
/// slot without sharing a tx; `None` means no coordinated cohort was detected.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BundleKind {
    AtomicTx,
    SameSlot,
    None,
}

impl BundleKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::AtomicTx => "atomic_tx",
            Self::SameSlot => "same_slot",
            Self::None => "none",
        }
    }
}

/// Aggregate summary of the bundled cohort for a token.
#[derive(Debug, Clone, Deserialize)]
pub struct BundleSummary {
    /// Number of wallets in the detected bundle cohort.
    pub wallet_count: u32,
    /// The kind of coordination detected across the cohort.
    pub bundle_kind: BundleKind,
    /// Fraction of supply (0–1) the cohort still holds. `None` when unknown.
    #[serde(default)]
    pub held_ratio: Option<f64>,
    /// Percent of total supply the cohort still holds. `None` when unknown.
    #[serde(default)]
    pub held_pct_of_supply: Option<f64>,
    /// `true` when the entire cohort has fully exited.
    pub fully_exited: bool,
    /// Total buy volume attributed to the cohort.
    pub buy_volume: f64,
    /// Tokens still held by the cohort.
    pub tokens_held: f64,
}

/// A single wallet within a token's bundled cohort. Identity fields
/// (`is_kol`, `kol_name`, `win_rate`, `bot_confidence`) are populated on ULTRA;
/// on lower tiers they may be `None`.
#[derive(Debug, Clone, Deserialize)]
pub struct BundleWallet {
    /// 1-based rank within the cohort (by holdings / buy volume).
    pub rank: u32,
    pub wallet: String,
    /// Fraction of supply (0–1) this wallet still holds. `None` when unknown.
    #[serde(default)]
    pub held_ratio: Option<f64>,
    /// `true` when this wallet has sold any of its position.
    pub has_sold: bool,
    /// `true` when this wallet bought in the same atomic transaction as the cohort.
    pub atomic: bool,
    /// `true` when this wallet is a tracked KOL.
    pub is_kol: bool,
    /// KOL display name. `None` on lower tiers or when not a KOL.
    #[serde(default)]
    pub kol_name: Option<String>,
    /// KOL win rate. `None` on lower tiers or when unavailable.
    #[serde(default)]
    pub win_rate: Option<f64>,
    /// Bot-confidence classification. `None` on lower tiers or when unavailable.
    #[serde(default)]
    pub bot_confidence: Option<String>,
    /// Tokens still held by this wallet.
    pub tokens_held: f64,
}

/// Bundle intelligence for a token (PRO/ULTRA): detects wallets that bought in
/// the same atomic transaction or same slot, how much of supply they still
/// hold, and whether they've fully exited. **ULTRA** populates the per-wallet
/// identity fields; lower tiers may return an empty `wallets` array.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenBundle {
    pub mint: String,
    /// Aggregate summary of the bundled cohort.
    pub bundle: BundleSummary,
    /// Per-wallet breakdown of the cohort. Empty on lower tiers.
    #[serde(default)]
    pub wallets: Vec<BundleWallet>,
    /// v0.23.4 — trade-coverage disclosure (`None` on older cached responses).
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Token pools (/tokens/{mint}/pools) ─────────────────────────────────────

/// A single liquidity pool for a token across a DEX.
#[derive(Debug, Clone, Deserialize)]
pub struct Pool {
    pub pool_address: String,
    pub dex: String,
    pub quote_mint: String,
    /// Pool liquidity in USD. `None` when unknown.
    #[serde(default)]
    pub liquidity_usd: Option<f64>,
    /// Last observed price in SOL. `None` when unknown.
    #[serde(default)]
    pub last_price_sol: Option<f64>,
    /// Timestamp of the last swap (ISO 8601). `None` when unknown.
    #[serde(default)]
    pub last_swap_at: Option<String>,
    /// AMM identifier for the pool. `None` when unavailable.
    #[serde(default)]
    pub amm_id: Option<String>,
    /// `true` when the pool is currently active.
    pub is_active: bool,
}

/// Aggregate summary across all of a token's pools.
#[derive(Debug, Clone, Deserialize)]
pub struct PoolsSummary {
    pub pool_count: i64,
    pub active_pool_count: i64,
    pub dex_count: i64,
    pub dexes: Vec<String>,
    /// Total liquidity across all pools in USD. `None` when unknown.
    #[serde(default)]
    pub total_liquidity_usd: Option<f64>,
    /// Address of the primary (deepest) pool. `None` when unknown.
    #[serde(default)]
    pub primary_pool: Option<String>,
    /// DEX of the primary pool. `None` when unknown.
    #[serde(default)]
    pub primary_dex: Option<String>,
    /// Share of total liquidity held by the top pool (percent). `None` when unknown.
    #[serde(default)]
    pub top_pool_share_pct: Option<f64>,
}

/// All liquidity pools for a token plus an aggregate summary.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenPoolsResponse {
    pub mint: String,
    pub pools: Vec<Pool>,
    pub summary: PoolsSummary,
}

// ─── Token holders (/tokens/{mint}/holders) ─────────────────────────────────

/// Wallet-intelligence label on a live holder. Labels come from MadeOnSol's
/// swap-ledger data — an empty `labels` vec means "unknown to us", NOT
/// "verified clean". `Other` catches labels added after this crate shipped.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HolderLabel {
    Deployer,
    Kol,
    EarlyBuyer,
    Buyer,
    Bundle,
    Bot,
    DumpCluster,
    #[serde(other)]
    Other,
}

/// Why an owner was excluded from the circulating denominator and listed in
/// `excluded`: `Pool` = vault authority of a known pool (`dex` + `pool_address`
/// set); `BondingCurve` = pump.fun / LaunchLab curve; `Burn` = incinerator /
/// system program; `ProgramAccount` = an off-curve owner we could not attribute
/// to a known pool (vault, escrow, staking, unknown pool).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HolderExcludedReason {
    Pool,
    BondingCurve,
    Burn,
    ProgramAccount,
    #[serde(other)]
    Other,
}

/// How the holder set was read. `GetProgramAccountsCensus` = full mint-scoped
/// census (exact `holder_count`, ranks 1–100 retained).
/// `GetTokenLargestAccounts` = the top-20 fallback used only when the provider
/// refuses the census for a mega-cap mint (`holder_count: None`,
/// `source.census_fallback_reason` set).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum HoldersMethod {
    #[serde(rename = "getProgramAccounts_census")]
    GetProgramAccountsCensus,
    #[serde(rename = "getTokenLargestAccounts")]
    GetTokenLargestAccounts,
    #[serde(other)]
    Other,
}

/// One disclosed holder — token accounts merged per owner wallet.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenHolder {
    /// 1-based rank by balance among non-excluded owners.
    pub rank: i64,
    /// Owner wallet (owner of the token account(s)).
    pub owner: String,
    /// Every non-zero token account of this owner for the mint.
    #[serde(default)]
    pub token_accounts: Vec<String>,
    /// Raw u64 balance as a decimal STRING — never a float. Parse with
    /// `amount_raw.parse::<u64>()` / `u128`.
    pub amount_raw: String,
    /// UI amount (`amount_raw / 10^decimals`); `None` when decimals are unknown.
    #[serde(default)]
    pub amount: Option<f64>,
    /// Share of TOTAL supply, 0–100.
    #[serde(default)]
    pub pct_of_supply: Option<f64>,
    /// Share of circulating supply (total minus pools/curves/burns), 0–100.
    #[serde(default)]
    pub pct_of_circulating: Option<f64>,
    /// MadeOnSol labels. Empty = unknown to us, not verified clean.
    #[serde(default)]
    pub labels: Vec<HolderLabel>,
    #[serde(default)]
    pub kol_name: Option<String>,
    /// This owner's rank in the token's early-buyer cohort, if any.
    #[serde(default)]
    pub early_buyer_rank: Option<i64>,
    /// Alpha-wallet classifier enum (`"none"`/`"low"`/`"medium"`/`"high"`), not a number.
    #[serde(default)]
    pub bot_confidence: Option<String>,
    #[serde(default)]
    pub historical_win_rate: Option<f64>,
}

/// An owner excluded from the circulating denominator (pool / bonding curve /
/// burn / unattributed program account), NAMED where possible.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenHoldersExcluded {
    pub owner: String,
    #[serde(default)]
    pub token_accounts: Vec<String>,
    /// Raw u64 balance as a decimal STRING — never a float.
    pub amount_raw: String,
    /// Share of TOTAL supply, 0–100.
    #[serde(default)]
    pub pct_of_supply: Option<f64>,
    pub reason: HolderExcludedReason,
    /// pumpfun | pumpswap | raydium | launchlab | meteora | orca | jupiter — when named.
    #[serde(default)]
    pub dex: Option<String>,
    #[serde(default)]
    pub pool_address: Option<String>,
}

/// Concentration over the FULL owner set — tier only governs how many ranks
/// are disclosed in `holders`; these numbers are identical on
/// PRO/ULTRA/BUSINESS. All `*_share` / `*_pct` values are 0–100 (or `None`
/// when the denominator is unknown).
#[derive(Debug, Clone, Deserialize)]
pub struct TokenHoldersConcentration {
    /// Exact distinct non-zero owners minus excluded pools/curves/burns, at
    /// `slot` (census). `None` ONLY when the provider refused the census (see
    /// `source.census_fallback_reason`) — never estimated from trades.
    #[serde(default)]
    pub holder_count: Option<i64>,
    /// `"census"` when `holder_count` is exact; `None` on the top-20 fallback.
    #[serde(default)]
    pub holder_count_source: Option<String>,
    #[serde(default)]
    pub token_accounts_nonzero: Option<i64>,
    /// Total supply, raw u64 as a string.
    #[serde(default)]
    pub supply_raw: Option<String>,
    /// Supply minus excluded owners, raw u64 as a string.
    #[serde(default)]
    pub circulating_raw: Option<String>,
    #[serde(default)]
    pub decimals: Option<i64>,
    /// Shares of CIRCULATING supply held by ranks 1 / 1–10 / 1–20.
    #[serde(default)]
    pub top1_share: Option<f64>,
    #[serde(default)]
    pub top10_share: Option<f64>,
    #[serde(default)]
    pub top20_share: Option<f64>,
    /// Census only — `None` on the top-20 fallback.
    #[serde(default)]
    pub top50_share: Option<f64>,
    /// Census only — `None` on the top-20 fallback.
    #[serde(default)]
    pub top100_share: Option<f64>,
    /// Share of TOTAL supply in excluded owners (= pool_pct + burned_pct + program_pct).
    #[serde(default)]
    pub pool_and_program_pct: Option<f64>,
    /// Share of total supply in NAMED pools + bonding curves.
    #[serde(default)]
    pub pool_pct: Option<f64>,
    /// Share of total supply at burn addresses.
    #[serde(default)]
    pub burned_pct: Option<f64>,
    /// Share of total supply held by off-curve owners we could not attribute.
    #[serde(default)]
    pub program_pct: Option<f64>,
    /// Shares of circulating supply held by labelled cohorts.
    #[serde(default)]
    pub deployer_pct: Option<f64>,
    #[serde(default)]
    pub kol_pct: Option<f64>,
    #[serde(default)]
    pub early_buyer_pct: Option<f64>,
    #[serde(default)]
    pub bundle_pct: Option<f64>,
    #[serde(default)]
    pub bot_pct: Option<f64>,
    #[serde(default)]
    pub dump_cluster_pct: Option<f64>,
    #[serde(default)]
    pub distinct_owners_in_top20: i64,
    /// How many ranked owners the scan retained (≤100 census, ≤20 fallback).
    #[serde(default)]
    pub ranked_owners_available: i64,
}

/// Tracked deployer of the mint, when known.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenHoldersDeployer {
    pub wallet: String,
    pub tier: String,
    #[serde(default)]
    pub bonding_rate: Option<f64>,
}

/// How the holder set was produced.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenHoldersSource {
    pub method: HoldersMethod,
    /// SPL Token or Token-2022 program id the mint lives under (pump.fun = Token-2022).
    #[serde(default)]
    pub token_program: Option<String>,
    /// Ranks retained by the scan: 100 (census) or 20 (fallback).
    #[serde(default)]
    pub rpc_cap: i64,
    #[serde(default)]
    pub commitment: String,
    #[serde(default)]
    pub scan_ms: i64,
    /// Set when the census was refused and the top-20 fallback was served.
    #[serde(default)]
    pub census_fallback_reason: Option<String>,
    #[serde(default)]
    pub note: String,
}

/// `GET /tokens/{mint}/holders` — live holder census + concentration for a
/// Solana mint, read from the ledger at `confirmed` (who holds NOW, as
/// opposed to `alpha.cap_table`, which is who bought first).
#[derive(Debug, Clone, Deserialize)]
pub struct TokenHoldersResponse {
    pub mint: String,
    /// Ledger slot the holder set was read at.
    pub slot: i64,
    pub as_of: String,
    /// Disclosed ranks: PRO 1–10, ULTRA 1–50, BUSINESS 1–100 (≤20 on the fallback).
    #[serde(default)]
    pub holders: Vec<TokenHolder>,
    pub count: i64,
    /// Rank cap for your tier: 10 PRO, 50 ULTRA, 100 BUSINESS.
    pub disclosed: i64,
    /// Pools / bonding curves / burns / unattributed program accounts —
    /// excluded from the circulating denominator, named where possible.
    #[serde(default)]
    pub excluded: Vec<TokenHoldersExcluded>,
    pub concentration: TokenHoldersConcentration,
    #[serde(default)]
    pub deployer: Option<TokenHoldersDeployer>,
    pub source: TokenHoldersSource,
}

// ─── Token locks & vesting (/tokens/{mint}/locks, /tokens/locks, /tokens/unlocks) — v0.26 ───

/// Locker program a lock / vesting contract lives in. `Other` catches
/// programs added after this crate shipped.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LockProgram {
    Streamflow,
    JupiterLock,
    BonfidaVesting,
    #[serde(other)]
    Other,
}

impl LockProgram {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Streamflow => "streamflow",
            Self::JupiterLock => "jupiter_lock",
            Self::BonfidaVesting => "bonfida_vesting",
            Self::Other => "other",
        }
    }
}

/// `Lock` = the whole amount unlocks at one date; `Vesting` = cliff and/or
/// periodic release (Streamflow's own lock-vs-vesting rule is mirrored).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LockKind {
    Lock,
    Vesting,
    #[serde(other)]
    Other,
}

/// Contract status, derived at request time from the schedule and the
/// on-chain withdrawn / cancelled / closed state.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LockStatus {
    Active,
    Completed,
    Cancelled,
    Closed,
    #[serde(other)]
    Other,
}

/// Kind of unlock event: `Cliff` (cliff amount released), `Period` (one
/// periodic release, period ≥ 1h), `Final` (last release / end of schedule),
/// `Tranche` (Bonfida schedule tranche).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum UnlockEventKind {
    Cliff,
    Period,
    Final,
    Tranche,
    #[serde(other)]
    Other,
}

/// Window for [`Token::unlocks`](crate::api::token::Token::unlocks)
/// (`within=`). Defaults to `7d` server-side when unset.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum UnlockWindow {
    #[serde(rename = "1h")]
    H1,
    #[serde(rename = "6h")]
    H6,
    #[serde(rename = "24h")]
    H24,
    #[serde(rename = "3d")]
    D3,
    #[default]
    #[serde(rename = "7d")]
    D7,
    #[serde(rename = "14d")]
    D14,
    #[serde(rename = "30d")]
    D30,
    #[serde(rename = "90d")]
    D90,
}

impl UnlockWindow {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::H1 => "1h",
            Self::H6 => "6h",
            Self::H24 => "24h",
            Self::D3 => "3d",
            Self::D7 => "7d",
            Self::D14 => "14d",
            Self::D30 => "30d",
            Self::D90 => "90d",
        }
    }
}

/// Sort order for [`Token::unlocks`](crate::api::token::Token::unlocks).
/// Defaults to [`UnlocksSort::Soonest`] server-side when unset.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum UnlocksSort {
    #[default]
    Soonest,
    LargestUsd,
    LargestPct,
}

impl UnlocksSort {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Soonest => "soonest",
            Self::LargestUsd => "largest_usd",
            Self::LargestPct => "largest_pct",
        }
    }
}

/// Mint facts + price attached to lock responses. `decimals` / `supply` come
/// from the SPL Mint account (most locked tokens are outside the pump/DEX
/// universe), `price_usd` / `market_cap_usd` from MadeOnSol price data — all
/// `None` when unknown. `facts_resolved` (per-mint response only) is `false`
/// while decimals/supply are still unresolved, in which case every ui / usd /
/// pct field on the rows is `None`.
#[derive(Debug, Clone, Deserialize)]
pub struct LockTokenInfo {
    #[serde(default)]
    pub symbol: Option<String>,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub decimals: Option<i64>,
    #[serde(default)]
    pub price_usd: Option<f64>,
    /// UI-scaled total supply (per-mint response only).
    #[serde(default)]
    pub supply: Option<f64>,
    #[serde(default)]
    pub market_cap_usd: Option<f64>,
    /// Per-mint response only; absent (`false`) on feed / unlock rows.
    #[serde(default)]
    pub facts_resolved: bool,
}

/// The next unlock event of a contract (or, in
/// [`TokenLocksSummary::next_unlock`], the nearest one across all contracts —
/// then `lock_account` names it).
#[derive(Debug, Clone, Deserialize)]
pub struct LockNextUnlock {
    /// ISO 8601.
    pub at: String,
    pub kind: UnlockEventKind,
    /// Base units as a decimal STRING — never a float.
    pub amount_raw: String,
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub amount_usd: Option<f64>,
    /// Only on the summary-level `next_unlock`.
    #[serde(default)]
    pub lock_account: Option<String>,
}

/// One on-chain lock / vesting contract with a live-derived view. Every
/// `*_raw` field is base units as a decimal STRING; the ui (`amount`,
/// `locked`, …), `*_usd` and `*_pct_of_supply` companions are `None` when
/// decimals or price are unknown.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenLock {
    /// The contract account (Streamflow stream / Jupiter `VestingEscrow` /
    /// Bonfida vesting account).
    pub lock_account: String,
    pub program: LockProgram,
    pub kind: LockKind,
    /// Derived at request time.
    pub status: LockStatus,
    pub mint: String,
    /// Creator / locker (Bonfida has none on-chain).
    #[serde(default)]
    pub sender: Option<String>,
    #[serde(default)]
    pub recipient: Option<String>,
    #[serde(default)]
    pub name: Option<String>,
    /// Deposited amount, base units.
    pub amount_raw: String,
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub amount_usd: Option<f64>,
    #[serde(default)]
    pub amount_pct_of_supply: Option<f64>,
    /// Still locked right now (amount − unlocked-so-far); `"0"` unless active.
    pub locked_raw: String,
    #[serde(default)]
    pub locked: Option<f64>,
    #[serde(default)]
    pub locked_usd: Option<f64>,
    #[serde(default)]
    pub locked_pct_of_supply: Option<f64>,
    pub unlocked_raw: String,
    #[serde(default)]
    pub unlocked: Option<f64>,
    /// Claimed so far.
    pub withdrawn_raw: String,
    #[serde(default)]
    pub withdrawn: Option<f64>,
    /// Unlocked but not yet withdrawn.
    pub claimable_raw: String,
    #[serde(default)]
    pub claimable: Option<f64>,
    #[serde(default)]
    pub start_at: Option<String>,
    #[serde(default)]
    pub cliff_at: Option<String>,
    /// Fully unlocked at; `None` = perpetual / no schedule.
    #[serde(default)]
    pub end_at: Option<String>,
    #[serde(default)]
    pub period_seconds: Option<i64>,
    /// `true` when period < 1h (per-second stream).
    #[serde(default)]
    pub continuous: bool,
    #[serde(default)]
    pub amount_per_period_raw: Option<String>,
    #[serde(default)]
    pub amount_per_period: Option<f64>,
    #[serde(default)]
    pub cliff_amount_raw: Option<String>,
    #[serde(default)]
    pub cliff_amount: Option<f64>,
    #[serde(default)]
    pub perpetual: bool,
    #[serde(default)]
    pub next_unlock: Option<LockNextUnlock>,
    /// The locker can cancel — funds are locked against the recipient, not
    /// the locker. A cancelable lock is a weaker promise.
    #[serde(default)]
    pub cancelable_by_sender: Option<bool>,
    #[serde(default)]
    pub cancelable_by_recipient: Option<bool>,
    #[serde(default)]
    pub transferable: Option<bool>,
    #[serde(default)]
    pub can_topup: Option<bool>,
    #[serde(default)]
    pub cancelled_at: Option<String>,
    #[serde(default)]
    pub created_at: Option<String>,
    /// Backfilled row with no on-chain creation time (Jupiter Lock).
    #[serde(default)]
    pub created_at_estimated: bool,
    #[serde(default)]
    pub tx_signature: Option<String>,
    /// Per-row token block — present on [`TokenLocksFeedResponse`] rows only
    /// (the per-mint response carries one [`TokenLocksResponse::token`]).
    #[serde(default)]
    pub token: Option<LockTokenInfo>,
}

/// Roll-up over every contract on the mint (the `status` / `program` filters
/// narrow the `locks` list, never the summary).
#[derive(Debug, Clone, Deserialize)]
pub struct TokenLocksSummary {
    /// Exact count of contracts on the mint.
    pub lock_count: i64,
    /// `false` when the mint holds more than 5000 contracts — totals then
    /// cover the newest 5000 (`rows_considered`).
    #[serde(default = "default_true")]
    pub complete: bool,
    #[serde(default)]
    pub rows_considered: i64,
    #[serde(default)]
    pub active_count: i64,
    #[serde(default)]
    pub by_program: HashMap<String, i64>,
    #[serde(default)]
    pub by_kind: HashMap<String, i64>,
    #[serde(default)]
    pub distinct_lockers: i64,
    /// Base units as a decimal STRING.
    pub locked_raw: String,
    #[serde(default)]
    pub locked: Option<f64>,
    #[serde(default)]
    pub locked_usd: Option<f64>,
    #[serde(default)]
    pub locked_pct_of_supply: Option<f64>,
    pub deposited_raw: String,
    #[serde(default)]
    pub deposited: Option<f64>,
    #[serde(default)]
    pub deposited_usd: Option<f64>,
    /// Forward unlock schedule — total releasing in the next 7 days.
    pub unlocking_7d_raw: String,
    #[serde(default)]
    pub unlocking_7d: Option<f64>,
    #[serde(default)]
    pub unlocking_7d_usd: Option<f64>,
    #[serde(default)]
    pub unlocking_7d_pct_of_supply: Option<f64>,
    /// Forward unlock schedule — total releasing in the next 30 days.
    pub unlocking_30d_raw: String,
    #[serde(default)]
    pub unlocking_30d: Option<f64>,
    #[serde(default)]
    pub unlocking_30d_usd: Option<f64>,
    #[serde(default)]
    pub unlocking_30d_pct_of_supply: Option<f64>,
    /// Nearest next unlock across all active contracts (`lock_account` set).
    #[serde(default)]
    pub next_unlock: Option<LockNextUnlock>,
    /// Active contracts the sender can still cancel.
    #[serde(default)]
    pub active_cancelable_by_sender: i64,
}

fn default_true() -> bool {
    true
}

/// `GET /tokens/{mint}/locks` — every lock / vesting contract on a mint
/// (Streamflow, Jupiter Lock, Bonfida vesting) + summary. **LP locks are not
/// included.**
#[derive(Debug, Clone, Deserialize)]
pub struct TokenLocksResponse {
    pub mint: String,
    pub token: LockTokenInfo,
    pub summary: TokenLocksSummary,
    #[serde(default)]
    pub locks: Vec<TokenLock>,
    #[serde(default)]
    pub meta: Option<serde_json::Value>,
}

/// Query params for [`Token::locks`](crate::api::token::Token::locks).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct TokenLocksParams {
    /// Filter the list (the summary always covers all rows).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<LockStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub program: Option<LockProgram>,
    /// 1–500; default 200.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Query params for [`Token::locks_feed`](crate::api::token::Token::locks_feed).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct TokenLocksFeedParams {
    /// ISO 8601 — only contracts created after this instant (use
    /// `pagination.next_since` to poll forward).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    /// ISO 8601 — page back: only contracts created before this instant
    /// (use `pagination.next_before`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mint: Option<String>,
    /// Creator / locker wallet.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recipient: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub program: Option<LockProgram>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<LockKind>,
    /// Post-filter (×4 over-fetch).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<LockStatus>,
    /// Deposited amount ≥ USD (needs a known price). Post-filter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_usd: Option<f64>,
    /// Deposited amount ≥ this % of supply, 0–100. Post-filter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_pct_of_supply: Option<f64>,
    /// Include backfilled Jupiter Lock rows that have no on-chain creation
    /// time (`created_at_estimated`); excluded by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_estimated: Option<bool>,
    /// 1–100; default 50.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Time-cursor pagination shared by the lock feed and the fee-claim feed:
/// pass `next_since` back as `since` to poll forward, `next_before` as
/// `before` to page back.
#[derive(Debug, Clone, Deserialize)]
pub struct TimeCursorPagination {
    pub limit: u32,
    pub count: u32,
    pub has_more: bool,
    #[serde(default)]
    pub next_since: Option<String>,
    #[serde(default)]
    pub next_before: Option<String>,
}

/// WebSocket pointer attached to feed responses that are also pushed live —
/// `channel` is what to put in the subscribe frame (`token:locks`,
/// `token:fee_claims`), `url` the stream endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct StreamPointer {
    pub channel: String,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub token_endpoint: Option<String>,
    #[serde(default)]
    pub subscribe: Option<serde_json::Value>,
    #[serde(default)]
    pub note: Option<String>,
}

/// `GET /tokens/locks` — cross-token feed of NEW lock / vesting contracts,
/// newest first. Same rows as [`TokenLocksResponse::locks`] plus a per-row
/// [`TokenLock::token`] block. Pushed live as `token:lock` on the
/// `token:locks` channel ([`TokenLockEvent`]).
#[derive(Debug, Clone, Deserialize)]
pub struct TokenLocksFeedResponse {
    #[serde(default)]
    pub locks: Vec<TokenLock>,
    pub pagination: TimeCursorPagination,
    #[serde(default)]
    pub stream: Option<StreamPointer>,
    #[serde(default)]
    pub meta: Option<serde_json::Value>,
}

/// Query params for [`Token::unlocks`](crate::api::token::Token::unlocks).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct TokenUnlocksParams {
    /// Window; default `7d`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub within: Option<UnlockWindow>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub program: Option<LockProgram>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<LockKind>,
    /// Next-event amount ≥ USD (needs a known price).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_usd: Option<f64>,
    /// Next-event amount ≥ this % of supply, 0–100.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_pct_of_supply: Option<f64>,
    /// Default `soonest`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<UnlocksSort>,
    /// 1–200; default 50.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// The `[from, to]` window an unlock query covered.
#[derive(Debug, Clone, Deserialize)]
pub struct UnlockWindowInfo {
    /// Echo of `within` (`"7d"` …).
    pub within: String,
    pub from: String,
    pub to: String,
}

/// The contract an unlock event belongs to — a subset of a [`TokenLock`] row.
#[derive(Debug, Clone, Deserialize)]
pub struct UnlockLockRef {
    pub lock_account: String,
    pub program: LockProgram,
    pub kind: LockKind,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub sender: Option<String>,
    #[serde(default)]
    pub recipient: Option<String>,
    /// Deposited amount, base units as a decimal STRING.
    pub amount_raw: String,
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub amount_usd: Option<f64>,
    /// Still locked right now, base units.
    pub locked_raw: String,
    #[serde(default)]
    pub locked: Option<f64>,
    #[serde(default)]
    pub locked_usd: Option<f64>,
    #[serde(default)]
    pub cliff_at: Option<String>,
    #[serde(default)]
    pub end_at: Option<String>,
    #[serde(default)]
    pub period_seconds: Option<i64>,
    #[serde(default)]
    pub continuous: bool,
    #[serde(default)]
    pub cancelable_by_sender: Option<bool>,
}

/// One upcoming unlock event: an active contract's NEXT release inside the
/// window (`amount_*`) plus that contract's total release over the whole
/// window (`window_amount_*`). Base units are decimal STRINGS; ui / usd /
/// pct are `None` when decimals or price are unknown.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenUnlock {
    /// ISO 8601.
    pub unlock_at: String,
    /// Seconds from the request instant until `unlock_at`.
    pub in_seconds: i64,
    pub event: UnlockEventKind,
    pub amount_raw: String,
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub amount_usd: Option<f64>,
    #[serde(default)]
    pub amount_pct_of_supply: Option<f64>,
    pub window_amount_raw: String,
    #[serde(default)]
    pub window_amount: Option<f64>,
    #[serde(default)]
    pub window_amount_usd: Option<f64>,
    #[serde(default)]
    pub window_amount_pct_of_supply: Option<f64>,
    pub mint: String,
    pub token: LockTokenInfo,
    pub lock: UnlockLockRef,
}

/// Pagination block of [`TokenUnlocksResponse`]. `total_in_window` counts
/// every matching event in the window, not just the returned page.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenUnlocksPagination {
    pub limit: u32,
    pub count: u32,
    pub total_in_window: i64,
    pub has_more: bool,
}

/// `GET /tokens/unlocks` — upcoming unlock events across all active
/// contracts inside a window. Continuous per-second streams (Streamflow
/// payroll) contribute only their cliff / final events.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenUnlocksResponse {
    pub window: UnlockWindowInfo,
    #[serde(default)]
    pub unlocks: Vec<TokenUnlock>,
    pub pagination: TokenUnlocksPagination,
    #[serde(default)]
    pub meta: Option<serde_json::Value>,
}

/// Payload of a `token:lock` stream event — one frame per NEW Streamflow /
/// Jupiter Lock / Bonfida lock or vesting contract, emitted the moment the
/// account is first seen (~seconds after the create tx). Delivered on the
/// `token:locks` WebSocket channel (PRO+). Updates (claims / cancels /
/// closes) are NOT pushed — poll
/// [`Token::locks`](crate::api::token::Token::locks) for the live state.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenLockEvent {
    pub lock_account: String,
    pub program: LockProgram,
    pub mint: String,
    pub kind: LockKind,
    #[serde(default)]
    pub sender: Option<String>,
    #[serde(default)]
    pub recipient: Option<String>,
    /// Base units as a decimal STRING.
    pub amount_raw: String,
    /// May be `None` on the very first sighting of a mint.
    #[serde(default)]
    pub decimals: Option<i64>,
    #[serde(default)]
    pub start_at: Option<String>,
    #[serde(default)]
    pub cliff_at: Option<String>,
    #[serde(default)]
    pub end_at: Option<String>,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub tx_signature: Option<String>,
    #[serde(default)]
    pub slot: Option<i64>,
    #[serde(default)]
    pub created_at: Option<String>,
}

// ─── pump.fun creator-fee sharing (/tokens/{mint}/fee-shares, /tokens/fee-claims) — v0.26 ───

/// Where the `SharingConfig` in a [`TokenFeeSharesResponse`] came from:
/// `Stream` = our table (only NON-default splits are stored), `Chain` = a live
/// PDA read (so `is_default: true` — 100% to the creator — is a real answer).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FeeConfigSource {
    Stream,
    Chain,
    #[serde(other)]
    Other,
}

/// pump.fun fee-event type. `CreatorClaim` (the plain creator vault claim —
/// per creator, carries no mint) is excluded from the feed unless requested
/// via [`TokenFeeClaimsParams::event_type`].
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FeeEventType {
    SharesCreated,
    SharesUpdated,
    SharesReset,
    Distribution,
    SocialPdaCreated,
    SocialClaim,
    CreatorTransferred,
    CreatorClaim,
    #[serde(other)]
    Other,
}

impl FeeEventType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::SharesCreated => "shares_created",
            Self::SharesUpdated => "shares_updated",
            Self::SharesReset => "shares_reset",
            Self::Distribution => "distribution",
            Self::SocialPdaCreated => "social_pda_created",
            Self::SocialClaim => "social_claim",
            Self::CreatorTransferred => "creator_transferred",
            Self::CreatorClaim => "creator_claim",
            Self::Other => "other",
        }
    }
}

/// Platform identity behind a `SocialFeePda` shareholder — fees earmarked
/// for e.g. an X account. `platform` 2 = X (`platform_label: "x"`); other
/// ids read `platform_<n>` until observed. `user_id` is the platform-native
/// numeric id, NOT the handle.
#[derive(Debug, Clone, Deserialize)]
pub struct FeeShareSocial {
    pub platform: i64,
    #[serde(default)]
    pub platform_label: Option<String>,
    pub user_id: String,
    /// Lifetime claimed by this identity, quote base units as a decimal STRING.
    #[serde(default)]
    pub lifetime_claimed_raw: Option<String>,
    #[serde(default)]
    pub lifetime_claimed: Option<f64>,
    #[serde(default)]
    pub lifetime_claimed_usd: Option<f64>,
    #[serde(default)]
    pub last_claimed_at: Option<String>,
}

/// One fee-share recipient — a current shareholder
/// ([`FeeSharingConfig::shareholders`]), a distribution recipient
/// ([`FeeDistributions::recipients`]) or a past recipient no longer in the
/// split ([`FeeDistributions::past_recipients`]; `share_bps` then `None`).
#[derive(Debug, Clone, Deserialize)]
pub struct FeeShareholder {
    pub address: String,
    #[serde(default)]
    pub share_bps: Option<i64>,
    #[serde(default)]
    pub share_pct: Option<f64>,
    /// The config admin (normally the coin creator).
    #[serde(default)]
    pub is_admin: bool,
    /// Address is a pump_fees `SocialFeePda` — fees earmarked for a platform
    /// identity ([`FeeShareholder::social`]).
    #[serde(default)]
    pub is_social_pda: bool,
    #[serde(default)]
    pub social: Option<FeeShareSocial>,
    /// Received via distributions since 2026-08-17, quote base units as a
    /// decimal STRING.
    #[serde(default)]
    pub received_raw: Option<String>,
    #[serde(default)]
    pub received: Option<f64>,
    #[serde(default)]
    pub received_usd: Option<f64>,
    #[serde(default)]
    pub payout_count: i64,
    #[serde(default)]
    pub last_payout_at: Option<String>,
}

/// The on-chain pump.fun `SharingConfig` of a coin (pump_fees PDA
/// `["sharing-config", mint]`).
#[derive(Debug, Clone, Deserialize)]
pub struct FeeSharingConfig {
    /// The SharingConfig PDA.
    pub sharing_config: String,
    #[serde(default)]
    pub admin: Option<String>,
    #[serde(default)]
    pub admin_revoked: Option<bool>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub version: Option<i64>,
    /// `Some(true)` = 100% to the admin — no redirect.
    #[serde(default)]
    pub is_default: Option<bool>,
    /// Share (bps) going to non-admin addresses.
    #[serde(default)]
    pub redirected_bps: i64,
    #[serde(default)]
    pub redirected_pct: f64,
    /// Share (bps) going to `SocialFeePda` addresses.
    #[serde(default)]
    pub social_bps: i64,
    #[serde(default)]
    pub social_pct: f64,
    #[serde(default)]
    pub shareholders: Vec<FeeShareholder>,
    pub source: FeeConfigSource,
    #[serde(default)]
    pub updated_at: Option<String>,
}

/// Quote asset the fee amounts are denominated in (SOL unless a
/// stable-quoted coin).
#[derive(Debug, Clone, Deserialize)]
pub struct FeeQuote {
    pub symbol: String,
    pub decimals: i64,
    #[serde(default)]
    pub sol_usd: Option<f64>,
}

/// Roll-up of every `distribute_creator_fees` payout on the mint since
/// 2026-08-17 (pro-rata per shareholder).
#[derive(Debug, Clone, Deserialize)]
pub struct FeeDistributions {
    pub count: i64,
    /// Quote base units as a decimal STRING.
    pub total_raw: String,
    #[serde(default)]
    pub total: Option<f64>,
    #[serde(default)]
    pub total_usd: Option<f64>,
    #[serde(default)]
    pub last_at: Option<String>,
    /// Current shareholders with what each has received.
    #[serde(default)]
    pub recipients: Vec<FeeShareholder>,
    /// Addresses that received payouts but are no longer in the split.
    #[serde(default)]
    pub past_recipients: Vec<FeeShareholder>,
    #[serde(default)]
    pub payouts_considered: i64,
    #[serde(default)]
    pub payouts_truncated: bool,
}

/// One recent `distribute_creator_fees` payout.
#[derive(Debug, Clone, Deserialize)]
pub struct FeeRecentDistribution {
    pub at: String,
    pub tx_signature: String,
    /// Quote base units as a decimal STRING.
    pub amount_raw: String,
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub amount_usd: Option<f64>,
    /// Per-shareholder split of this payout (untyped — shape follows the
    /// decoded Anchor event).
    #[serde(default)]
    pub shareholders: Vec<serde_json::Value>,
    /// Transaction signer.
    #[serde(default)]
    pub actor: Option<String>,
}

/// `GET /tokens/{mint}/fee-shares` — pump.fun creator-fee sharing on a mint:
/// who receives what share of the creator fees, the distributions rollup and
/// the config change log. **Event history starts 2026-08-17.**
#[derive(Debug, Clone, Deserialize)]
pub struct TokenFeeSharesResponse {
    pub mint: String,
    /// `None` only when the live read failed on every RPC endpoint
    /// (`config_error` set).
    #[serde(default)]
    pub config: Option<FeeSharingConfig>,
    /// The SharingConfig PDA address.
    pub config_pda: String,
    #[serde(default)]
    pub config_error: Option<String>,
    pub quote: FeeQuote,
    pub distributions: FeeDistributions,
    /// Config changes + creator transfers, newest first (untyped rows).
    #[serde(default)]
    pub history: Vec<serde_json::Value>,
    #[serde(default)]
    pub recent_distributions: Vec<FeeRecentDistribution>,
    #[serde(default)]
    pub meta: Option<serde_json::Value>,
}

/// Platform identity on a `social_claim` / `social_pda_created` fee event.
#[derive(Debug, Clone, Deserialize)]
pub struct FeeClaimSocial {
    /// Raw platform id (2 = X).
    pub platform: i64,
    #[serde(default)]
    pub platform_label: Option<String>,
    /// Platform-native numeric user id, not the handle.
    pub user_id: String,
    /// The `SocialFeePda` address.
    #[serde(default)]
    pub pda: Option<String>,
}

/// A shareholder as recorded on a config-change event.
#[derive(Debug, Clone, Deserialize)]
pub struct FeeClaimShareholder {
    pub address: String,
    pub share_bps: i64,
}

/// `distribution` only: the pro-rata amount paid to one shareholder.
#[derive(Debug, Clone, Deserialize)]
pub struct FeeClaimPayout {
    pub address: String,
    pub share_bps: i64,
    /// Quote base units as a decimal STRING.
    pub amount_raw: String,
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub amount_usd: Option<f64>,
}

/// One decoded pump.fun fee event on the feed.
#[derive(Debug, Clone, Deserialize)]
pub struct FeeClaimEvent {
    pub id: i64,
    #[serde(rename = "type")]
    pub event_type: FeeEventType,
    /// The event's own on-chain timestamp, ISO 8601.
    pub at: String,
    pub tx_signature: String,
    #[serde(default)]
    pub slot: Option<i64>,
    /// `None` for social claims and creator vault claims (per identity / per
    /// creator).
    #[serde(default)]
    pub mint: Option<String>,
    #[serde(default)]
    pub admin: Option<String>,
    /// Transaction signer.
    #[serde(default)]
    pub actor: Option<String>,
    /// Payout / claim recipient wallet, or the new creator.
    #[serde(default)]
    pub recipient: Option<String>,
    /// Quote base units as a decimal STRING (SOL lamports unless a
    /// stable-quoted coin).
    #[serde(default)]
    pub amount_raw: Option<String>,
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub amount_usd: Option<f64>,
    /// Quote symbol (`"SOL"` …).
    #[serde(default)]
    pub quote: Option<String>,
    #[serde(default)]
    pub social: Option<FeeClaimSocial>,
    #[serde(default)]
    pub shareholders: Option<Vec<FeeClaimShareholder>>,
    /// `distribution` only: pro-rata amount per shareholder.
    #[serde(default)]
    pub payouts: Option<Vec<FeeClaimPayout>>,
    /// Full decoded Anchor event.
    #[serde(default)]
    pub payload: Option<serde_json::Value>,
}

/// Query params for [`Token::fee_claims`](crate::api::token::Token::fee_claims).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct TokenFeeClaimsParams {
    /// Comma list of event types (`"distribution,social_claim"`); default is
    /// every type except `creator_claim`. Serialised as `type=`.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub event_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mint: Option<String>,
    /// Payout / claim recipient wallet, or new creator.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recipient: Option<String>,
    /// Transaction signer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// Raw platform id (2 = X).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub social_platform: Option<i64>,
    /// Platform-native numeric user id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub social_user_id: Option<String>,
    /// Amount floor in SOL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_sol: Option<f64>,
    /// ISO 8601 cursor (`pagination.next_since`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    /// ISO 8601 — page back.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// 1–100; default 50.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// `GET /tokens/fee-claims` — pump.fun fee-event feed, newest first. Pushed
/// live as `token:fee_claim` on the `token:fee_claims` channel
/// ([`TokenFeeClaimEvent`]). **History starts 2026-08-17.**
#[derive(Debug, Clone, Deserialize)]
pub struct TokenFeeClaimsResponse {
    #[serde(default)]
    pub events: Vec<FeeClaimEvent>,
    pub pagination: TimeCursorPagination,
    #[serde(default)]
    pub stream: Option<StreamPointer>,
    #[serde(default)]
    pub meta: Option<serde_json::Value>,
}

/// Payload of a `token:fee_claim` stream event — one frame per stored
/// pump.fun fee event, emitted the moment the tx confirms. Delivered on the
/// `token:fee_claims` WebSocket channel (PRO+). NOTE: this is the writer's
/// raw row, not the enriched REST [`FeeClaimEvent`] — no `amount` /
/// `amount_usd`, and the social identity is flattened into
/// `social_platform` / `social_user_id` / `social_fee_pda`.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenFeeClaimEvent {
    pub id: i64,
    pub event_type: FeeEventType,
    pub tx_signature: String,
    #[serde(default)]
    pub slot: Option<i64>,
    /// The event's own on-chain timestamp, ISO 8601.
    pub block_time: String,
    /// `None` for social claims and creator vault claims.
    #[serde(default)]
    pub mint: Option<String>,
    #[serde(default)]
    pub sharing_config: Option<String>,
    #[serde(default)]
    pub admin: Option<String>,
    #[serde(default)]
    pub actor: Option<String>,
    #[serde(default)]
    pub recipient: Option<String>,
    /// Quote base units as a decimal STRING.
    #[serde(default)]
    pub amount_raw: Option<String>,
    #[serde(default)]
    pub quote_mint: Option<String>,
    #[serde(default)]
    pub social_platform: Option<i64>,
    #[serde(default)]
    pub social_user_id: Option<String>,
    #[serde(default)]
    pub social_fee_pda: Option<String>,
    #[serde(default)]
    pub shareholders: Option<serde_json::Value>,
}

// ─── Token OHLC candles (/tokens/{mint}/candles) ────────────────────────────

/// Query params for [`Token::candles`](crate::api::token::Token::candles).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CandlesParams {
    /// Timeframe / bucket size (e.g. "1m"). Defaults server-side when unset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tf: Option<String>,
    /// Max number of candles to return.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Lower bound of the time window (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Upper bound of the time window (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
}

/// A single OHLC candle. Each nullable field is `None` when the underlying data
/// was unavailable, and the ULTRA-only fields are absent for lower tiers.
#[derive(Debug, Clone, Deserialize)]
pub struct Candle {
    /// Bucket start time (ISO 8601).
    pub t: String,
    pub open: f64,
    pub high: f64,
    pub low: f64,
    pub close: f64,
    /// Total USD volume traded in the bucket.
    pub volume_usd: f64,
    /// Number of trades in the bucket.
    pub trades: i64,
    #[serde(default)]
    pub market_cap_usd: Option<f64>,
    /// ULTRA — buy-side USD volume.
    #[serde(default)]
    pub buy_volume_usd: Option<f64>,
    /// ULTRA — sell-side USD volume.
    #[serde(default)]
    pub sell_volume_usd: Option<f64>,
    /// ULTRA — net USD flow (buy minus sell).
    #[serde(default)]
    pub net_volume_usd: Option<f64>,
    /// ULTRA — liquidity USD at bucket open.
    #[serde(default)]
    pub open_liquidity_usd: Option<f64>,
    /// ULTRA — liquidity USD at bucket close.
    #[serde(default)]
    pub close_liquidity_usd: Option<f64>,
    /// ULTRA — highest market cap USD in the bucket.
    #[serde(default)]
    pub high_mc_usd: Option<f64>,
    /// ULTRA — lowest market cap USD in the bucket.
    #[serde(default)]
    pub low_mc_usd: Option<f64>,
    /// ULTRA — buy trade count.
    #[serde(default)]
    pub buy_count: Option<i64>,
    /// ULTRA — sell trade count.
    #[serde(default)]
    pub sell_count: Option<i64>,
    /// ULTRA — MEV-attributed USD volume.
    #[serde(default)]
    pub volume_mev_usd: Option<f64>,
}

/// 1-minute OHLC candle series for a token (PRO/ULTRA).
#[derive(Debug, Clone, Deserialize)]
pub struct CandlesResponse {
    pub mint: String,
    /// Timeframe of each candle (e.g. "1m").
    pub timeframe: String,
    /// Lower bound of the returned window (ISO 8601).
    pub from: String,
    /// Upper bound of the returned window (ISO 8601).
    pub to: String,
    pub count: i64,
    /// Whether ULTRA net-flow fields are populated on the candles.
    pub net_flow_included: bool,
    pub candles: Vec<Candle>,
}

// ─── Token flow (/tokens/{mint}/flow) ───────────────────────────────────────

/// Query params for [`Token::token_flow`](crate::api::token::Token::token_flow).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct TokenFlowParams {
    /// Lookback window — `"1h"` (default) or `"24h"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window: Option<String>,
}

/// Aggregated buy/sell flow for a token over a 1h or 24h window (PRO+).
#[derive(Debug, Clone, Deserialize)]
pub struct TokenFlowResponse {
    pub mint: String,
    /// Window the figures cover — `"1h"` or `"24h"`.
    pub window: String,
    /// Window start time (ISO 8601).
    pub from: String,
    pub unique_wallets: f64,
    pub unique_buyers: f64,
    pub unique_sellers: f64,
    pub buy_count: f64,
    pub sell_count: f64,
    pub total_trades: f64,
    pub buy_sol: f64,
    pub sell_sol: f64,
    /// Net SOL flow — `buy_sol` minus `sell_sol`.
    pub net_sol: f64,
    pub trades_per_wallet: f64,
    /// v0.23.4 — trade-coverage disclosure; when `in_scope` is `false` the
    /// zero counts mean "not covered", not "no activity".
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

// ─── Token trade tape (/tokens/{mint}/trades, v0.22) ────────────────────────

/// Query params for [`Token::trades`](crate::api::token::Token::trades).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct TokenTradesParams {
    /// 1–500; default 100.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// From `next_cursor` of a previous response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<WalletTradeAction>,
    /// Filter to a single wallet address (base58).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wallet: Option<String>,
    /// Unix epoch seconds; default FULL history (capture starts 2026-04-12).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<i64>,
    /// Unix epoch seconds; default now.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub until: Option<i64>,
}

/// One raw trade on a token's tape.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenTrade {
    pub tx_signature: String,
    pub wallet_address: String,
    /// `"buy"` | `"sell"`.
    pub action: String,
    pub sol_amount: f64,
    pub token_amount: f64,
    /// THIS TRADE's executed price: `sol_amount / token_amount`, so it reconciles
    /// exactly with the amounts on the same row and with the PnL endpoints.
    /// `sol_amount` is the wallet's net SOL movement, so this is the trader's
    /// all-in effective rate — swap fee and any account rent included, not the
    /// pool mid. `None` for dust and zero-SOL legs.
    ///
    /// Changed 2026-08-16: previously the canonical pool price, which disagreed
    /// with the row's own amounts by a 7.9% median. That value moved to
    /// [`TokenTrade::market_price_sol`].
    #[serde(default)]
    pub price_sol: Option<f64>,
    /// [`TokenTrade::price_sol`] in USD.
    #[serde(default)]
    pub price_usd: Option<f64>,
    /// Canonical pool price sampled near this trade's slot — one value per token
    /// per update, so every trade in the same slot shares it. Use for a per-token
    /// series; use `price_sol` for cost basis and PnL.
    #[serde(default)]
    pub market_price_sol: Option<f64>,
    /// [`TokenTrade::market_price_sol`] in USD.
    #[serde(default)]
    pub market_price_usd: Option<f64>,
    #[serde(default)]
    pub early_buyer_rank: Option<i64>,
    #[serde(default)]
    pub slot: Option<i64>,
    /// Unix epoch seconds.
    pub block_time: i64,
    /// ISO 8601 — `block_time` rendered as a timestamp.
    pub traded_at: String,
}

/// Echo of the filters a token-trades page was produced with.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenTradesFilters {
    #[serde(default)]
    pub action: Option<String>,
    #[serde(default)]
    pub wallet: Option<String>,
    pub since: i64,
    pub until: i64,
}

/// Coverage honesty block: where the tape starts and what pipeline feeds it.
///
/// v0.23.4 — also returned (as an optional `coverage` field) on bundle, risk,
/// flow, cap-table, buyer-quality and the wallet
/// stats/pnl/positions/holdings/trades endpoints, with the new `in_scope`
/// probe.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenTradesCoverage {
    /// Unix epoch seconds — capture starts 2026-04-12.
    pub history_start: i64,
    /// e.g. `"pump.fun pipeline"` — trades outside that pipeline aren't on the tape.
    pub scope: String,
    /// v0.23.4 — `Some(true)` = persisted trades exist for this mint/wallet ·
    /// `Some(false)` = the subject sits outside the launchpad write-gate (read
    /// zeros as "not covered", NOT "no activity") · `None` = probe unavailable
    /// or an older cached response.
    #[serde(default)]
    pub in_scope: Option<bool>,
    /// Present when `in_scope` is `false`/`null` (and always on `/risk`) —
    /// human-readable explanation of what the coverage gap means.
    #[serde(default)]
    pub note: Option<String>,
}

/// Preferred name for the coverage honesty block — it is no longer
/// trades-specific (see [`TokenTradesCoverage`]).
pub type TradeCoverage = TokenTradesCoverage;

/// Response of [`Token::trades`](crate::api::token::Token::trades).
#[derive(Debug, Clone, Deserialize)]
pub struct TokenTradesResponse {
    pub mint: String,
    pub trades: Vec<TokenTrade>,
    pub next_cursor: Option<String>,
    pub has_more: bool,
    pub filters: TokenTradesFilters,
    pub coverage: TokenTradesCoverage,
}

// ─── Token depth / price impact (/tokens/{mint}/depth, v0.23) ───────────────

/// Query params for [`Token::depth`](crate::api::token::Token::depth).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct DepthParams {
    /// CSV of SOL buy sizes — max 8 values, each `> 0` and `<= 10000`,
    /// e.g. `"0.5,1,5,10"`. Server default when unset: `0.5,1,5,10`.
    /// Prefer [`DepthParams::from_sizes`] to build this from numbers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sizes: Option<String>,
}

impl DepthParams {
    /// Build params from numeric SOL buy sizes — joined into the CSV the API
    /// expects (`?sizes=0.5,1,5,10`).
    pub fn from_sizes(sizes: &[f64]) -> Self {
        Self {
            sizes: Some(
                sizes
                    .iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<_>>()
                    .join(","),
            ),
        }
    }
}

/// Slippage quote for one requested buy size against one pool.
#[derive(Debug, Clone, Deserialize)]
pub struct DepthQuote {
    /// The requested buy size, in SOL.
    pub size_sol: f64,
    /// Tokens received for that buy (UI units).
    pub tokens_out: f64,
    /// Average execution price paid, SOL per token.
    pub avg_price_sol: f64,
    /// Price impact vs spot, percent (rounded to 2 decimals server-side).
    pub price_impact_pct: f64,
}

/// SOL required to move a pool's spot price up by 1% / 5% / 10%
/// (closed-form constant-product, fee-adjusted).
#[derive(Debug, Clone, Deserialize)]
pub struct DepthToMovePrice {
    #[serde(rename = "1pct")]
    pub pct_1: f64,
    #[serde(rename = "5pct")]
    pub pct_5: f64,
    #[serde(rename = "10pct")]
    pub pct_10: f64,
}

/// Per-pool depth breakdown: spot price, slippage quotes per buy size, and
/// how much SOL it takes to move the price 1/5/10%.
#[derive(Debug, Clone, Deserialize)]
pub struct DepthPool {
    pub pool_address: String,
    pub dex: String,
    pub quote_mint: String,
    /// Pool model the depth was computed under — `"constant_product"` or `"curve"`.
    pub pool_model: String,
    /// Pool liquidity in USD (rounded). `None` when unknown.
    #[serde(default)]
    pub liquidity_usd: Option<f64>,
    /// `true` when the pool saw a swap within the last hour.
    pub is_active: bool,
    /// Always `true` on entries in `pools` (unsupported pools are split into
    /// `unsupported_pools` instead).
    pub depth_available: bool,
    /// Same as `pool_model` — the model the math used.
    pub model: String,
    /// Swap fee applied, percent (e.g. `0.25`).
    pub fee_pct: f64,
    /// `"stream"` (DB reserves from the firehose) or `"live_rpc"` (curve
    /// virtual reserves read live on-chain).
    pub source: String,
    /// Age of the reserves snapshot in milliseconds. `0` for `live_rpc`.
    pub reserves_age_ms: i64,
    /// Current spot price, SOL per token.
    pub spot_price_sol: f64,
    /// One slippage quote per requested size, in `sizes_sol` order.
    pub quotes: Vec<DepthQuote>,
    pub to_move_price: DepthToMovePrice,
}

/// A pool depth could not be computed for, with the machine-readable `reason`
/// (e.g. `"concentrated_liquidity_depth_not_supported"`, `"pool_model_unknown"`,
/// `"curve_graduated_use_amm_pool"`, `"reserves_unavailable"`).
#[derive(Debug, Clone, Deserialize)]
pub struct DepthUnsupportedPool {
    pub pool_address: String,
    pub dex: String,
    pub quote_mint: String,
    /// `None` when the pool hasn't been classified yet (`reason = "pool_model_unknown"`).
    #[serde(default)]
    pub pool_model: Option<String>,
    /// Pool liquidity in USD (rounded). `None` when unknown.
    #[serde(default)]
    pub liquidity_usd: Option<f64>,
    /// `true` when the pool saw a swap within the last hour.
    pub is_active: bool,
    /// Why depth isn't available for this pool.
    pub reason: String,
}

/// Response of [`Token::depth`](crate::api::token::Token::depth).
///
/// When the mint has no tracked pools at all, `found` is `false`, `pools` and
/// `unsupported_pools` are empty, and `sol_usd` / `primary_pool` / `note` are
/// absent (`None`).
#[derive(Debug, Clone, Deserialize)]
pub struct TokenDepthResponse {
    pub mint: String,
    /// `true` when at least one pool has computable depth.
    pub found: bool,
    /// SOL/USD price used to convert stable-quoted pools. `None` when
    /// unavailable (or when the mint has no pools).
    #[serde(default)]
    pub sol_usd: Option<f64>,
    /// The SOL buy sizes the quotes were computed for (deduped, ascending).
    pub sizes_sol: Vec<f64>,
    /// Address of the deepest pool with depth available. `None` when no pool
    /// qualified (or when the mint has no pools).
    #[serde(default)]
    pub primary_pool: Option<String>,
    pub pools: Vec<DepthPool>,
    pub unsupported_pools: Vec<DepthUnsupportedPool>,
    /// Methodology caveat string. Absent when the mint has no pools.
    #[serde(default)]
    pub note: Option<String>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Signal Scorecard (/signals) ────────────────────────────────────────────

/// Query params for [`Signals::performance`](crate::api::signals::Signals::performance).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SignalPerformanceParams {
    /// When `Some(true)`, append the per-day snapshot series (`history`) for
    /// drift inspection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub history: Option<bool>,
}

/// A single per-bucket reliability row within a signal's scorecard.
#[derive(Debug, Clone, Deserialize)]
pub struct SignalBucket {
    /// Bucket label (e.g. a value or threshold band for the signal).
    pub bucket: String,
    /// Out-of-sample hit rate for this bucket (0–1).
    #[serde(default)]
    pub hit_rate: Option<f64>,
    /// Base rate the bucket is compared against (0–1).
    #[serde(default)]
    pub base_rate: Option<f64>,
    /// Lift over the base rate (`hit_rate / base_rate`).
    #[serde(default)]
    pub lift: Option<f64>,
    /// Number of samples backing this bucket.
    pub sample_n: i64,
    /// Length of the outcome window in days. Present on history rows.
    #[serde(default)]
    pub window_days: Option<i64>,
    /// Lower bound of the out-of-sample test window (ISO 8601). Present on history rows.
    #[serde(default)]
    pub test_from: Option<String>,
    /// Upper bound of the out-of-sample test window (ISO 8601). Present on history rows.
    #[serde(default)]
    pub test_to: Option<String>,
}

/// One daily snapshot of a signal's per-bucket scorecard (drift series).
/// Only present when [`SignalPerformanceParams::history`] is `Some(true)`.
#[derive(Debug, Clone, Deserialize)]
pub struct SignalHistoryEntry {
    /// When this snapshot was computed (ISO 8601).
    pub as_of: String,
    pub buckets: Vec<SignalBucket>,
}

/// Out-of-sample, machine-readable reliability for a named signal (any tier).
/// Each nullable field is `None` when the underlying data was unavailable.
#[derive(Debug, Clone, Deserialize)]
pub struct SignalPerformance {
    /// Signal name (e.g. "coordination_count").
    pub signal: String,
    /// Metric family (e.g. "forward_return"). Absent before any data is computed.
    #[serde(default)]
    pub metric_type: Option<String>,
    /// Outcome label being measured (e.g. "peak_2x_6h"). Absent before any data is computed.
    #[serde(default)]
    pub outcome: Option<String>,
    /// Human-readable description of the backtest methodology.
    #[serde(default)]
    pub methodology: Option<String>,
    /// When the latest snapshot was computed (ISO 8601). Absent before any data is computed.
    #[serde(default)]
    pub as_of: Option<String>,
    /// Length of the outcome window in days.
    #[serde(default)]
    pub window_days: Option<i64>,
    /// Overall base rate for the signal (0–1).
    #[serde(default)]
    pub base_rate: Option<f64>,
    /// Lower bound of the out-of-sample test window (ISO 8601).
    #[serde(default)]
    pub test_from: Option<String>,
    /// Upper bound of the out-of-sample test window (ISO 8601).
    #[serde(default)]
    pub test_to: Option<String>,
    /// Per-bucket reliability rows for the latest snapshot.
    pub buckets: Vec<SignalBucket>,
    /// Per-day snapshot series — only present when `history=true` was requested.
    #[serde(default)]
    pub history: Option<Vec<SignalHistoryEntry>>,
    /// Note set when no performance data has been computed yet.
    #[serde(default)]
    pub note: Option<String>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

/// A catalog entry describing one available signal.
#[derive(Debug, Clone, Deserialize)]
pub struct SignalCatalogEntry {
    /// Signal name — pass to [`Signals::performance`](crate::api::signals::Signals::performance).
    pub name: String,
    /// Human-readable description of the backtest methodology.
    pub methodology: String,
    /// Fully-qualified URL to fetch this signal's live efficacy.
    pub performance_endpoint: String,
}

/// Discovery index for the Signal Scorecard (any tier).
#[derive(Debug, Clone, Deserialize)]
pub struct SignalsCatalog {
    /// Catalog name.
    pub name: String,
    /// Catalog description.
    pub description: String,
    /// The available signals and how to fetch each one's efficacy.
    pub signals: Vec<SignalCatalogEntry>,
    /// Link to human-readable docs.
    pub docs: String,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Wallet Tracker ─────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct WatchlistAddParams {
    pub wallet_address: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct WatchlistUpdateParams {
    /// New label for the wallet, or `None` to clear it.
    pub label: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletEntry {
    pub wallet_address: String,
    pub label: Option<String>,
    pub added_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WatchlistAddResponse {
    pub wallet_address: String,
    pub label: Option<String>,
    pub added_at: String,
    pub remaining: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WatchlistResponse {
    pub wallets: Vec<WalletEntry>,
    pub count: u32,
    pub limit: u32,
    pub remaining: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTrackerEvent {
    pub id: String,
    pub wallet_address: String,
    pub label: Option<String>,
    pub event_type: WalletTrackerEventType,
    pub action: WalletTrackerAction,
    pub block_time: i64,
    pub block_time_iso: String,
    pub token_mint: Option<String>,
    pub token_symbol: Option<String>,
    pub token_name: Option<String>,
    pub sol_amount: f64,
    pub token_amount: Option<f64>,
    pub price_per_token_sol: Option<f64>,
    pub counterparty: Option<String>,
    pub tx_signature: Option<String>,
    pub program: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct WalletTrackerTradesParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wallet: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<WalletTrackerAction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_type: Option<WalletTrackerEventType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<i64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTrackerTradesResponse {
    pub events: Vec<WalletTrackerEvent>,
    pub count: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTrackerWalletStats {
    pub wallet_address: String,
    pub label: Option<String>,
    pub swap_count: u32,
    pub buys: u32,
    pub sells: u32,
    pub sol_bought: f64,
    pub sol_sold: f64,
    pub last_event_at: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct WalletTrackerSummaryParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<WalletTrackerSummaryPeriod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wallet: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTrackerSummaryResponse {
    pub wallets: Vec<WalletTrackerWalletStats>,
    pub period: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTrackerDeleteResponse {
    pub success: bool,
}

// ─── Sniper: deshred pre-confirm pump.fun deploy feed (PRO + ULTRA) ─────────

/// Slot-window launch-snipe rollup (v0.22): buys landing in slots
/// `[deploy-1 .. deploy+3]`. Appears on sniper deploys (`footprint`) and in
/// token risk inputs (`sniper_footprint`).
///
/// `data_available = false` means the mint has no rows in the trade pipeline
/// (write-gate) — "not observable", NOT "0 snipes". `supply_pct` is
/// pump.fun-only (fixed 1B supply denominator) and `None` otherwise.
#[derive(Debug, Clone, Deserialize)]
pub struct SniperFootprint {
    pub buys: i64,
    pub buyers: i64,
    pub sol: f64,
    #[serde(default)]
    pub supply_pct: Option<f64>,
    /// How many of the window's buys came from known sniper wallets.
    pub sniper_wallet_buys: i64,
    pub data_available: bool,
    /// ISO 8601 — when the rollup was computed.
    pub as_of: String,
}

/// A pump.fun deploy detected via shred-level ("deshred") reconstruction,
/// ~500ms before the chain confirms it. Detection is pre-execution, so
/// `confirmed_on_chain` is `None` until reconciled.
#[derive(Debug, Clone, Deserialize)]
pub struct SniperDeploy {
    pub mint: String,
    pub name: Option<String>,
    pub symbol: Option<String>,
    pub deployer_wallet: String,
    pub signature: String,
    pub slot: i64,
    pub detected_at: String,
    pub detection_region: String,
    pub deployer_tier: Option<String>,
    pub deployer_bond_rate: Option<f64>,
    pub deployer_total_bonded: Option<i64>,
    pub deployer_recent: Option<String>,
    /// Fraction of the deployer's labeled tokens that ran (peak >=60min after deploy) vs dumped.
    #[serde(default)]
    pub deployer_runner_rate: Option<f64>,
    /// Confidence denominator; gate on >=3.
    #[serde(default)]
    pub deployer_labeled_tokens: Option<i64>,
    pub confirmed_on_chain: Option<bool>,
    pub confirmed_at: Option<String>,
    /// v0.22 — slot-window snipe rollup. `None` for deploys younger than the
    /// rollup's ~10-min settle window or outside the trade-pipeline write-gate
    /// (absent, not zero).
    #[serde(default)]
    pub footprint: Option<SniperFootprint>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct SniperRecentParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployer_tier: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_bond_rate: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// ULTRA: narrow to your custom deployer watchlist (any tier).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub watchlist: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SniperRecentResponse {
    pub deploys: Vec<SniperDeploy>,
    pub count: u32,
    pub data_age_seconds: Option<i64>,
    #[serde(default)]
    pub watchlist_empty: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SniperByDeployerResponse {
    pub deployer: String,
    pub deploys: Vec<SniperDeploy>,
    pub count: u32,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct SniperByDeployerParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SniperWatchlistEntry {
    pub deployer_wallet: String,
    pub label: Option<String>,
    pub created_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SniperWatchlistResponse {
    pub deployers: Vec<SniperWatchlistEntry>,
    pub count: u32,
    pub limit: u32,
    pub remaining: u32,
}

/// Add one (`wallet`) or many (`wallets`, max 50) deployers, with an optional label.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SniperWatchlistAddParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wallet: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wallets: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SniperWatchlistAddResponse {
    pub added: u32,
    #[serde(default)]
    pub deployers: Vec<String>,
    #[serde(default)]
    pub message: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct SniperWatchlistRemoveResponse {
    pub removed: String,
}

// ─── Universal wallet (PRO+) ────────────────────────────────────────────────
// New 2026-05-20. Works on any Solana wallet — not just curated KOLs. Backed
// by FIFO cost-basis math over the last 90 days of token_trades. Cached in
// `wallet_analyses` with dynamic TTL (5min/1h/24h). Cache hits don't count
// against your daily quota.

#[derive(Debug, Clone, Deserialize)]
pub struct WalletStats {
    pub first_seen: String,
    pub last_seen: String,
    pub total_trades: u64,
    pub buys: u64,
    pub sells: u64,
    pub bought_sol: f64,
    pub sold_sol: f64,
    pub unique_tokens: u64,
    /// Lookback window in days — currently 90.
    pub window_days: u32,
}

/// Dump-cluster cohort counts for a wallet (rolling 42-day window, recomputed
/// daily — up to ~48h stale). `as_of` is the computation timestamp.
#[derive(Debug, Clone, Deserialize)]
pub struct WalletDumpCluster {
    pub dump_cohorts: i64,
    pub runner_cohorts: i64,
    pub total_cohorts: i64,
    pub as_of: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletFlags {
    pub is_kol: bool,
    pub kol_name: Option<String>,
    /// True if the wallet appears in `mv_alpha_wallets`.
    pub is_alpha_tracked: bool,
    /// Text enum `"none"` | `"low"` | `"medium"` | `"high"`; `None` when the
    /// wallet isn't alpha-tracked. Sourced from the alpha classifier.
    ///
    /// v0.22 type FIX: this was previously (mis)typed as `Option<f64>` — the
    /// wire value is a string enum, and a server bug made it always `null`
    /// before 2026-07-10; it now carries real values.
    pub bot_confidence: Option<String>,
    pub alpha_win_rate: Option<f64>,
    pub alpha_net_pnl_sol: Option<f64>,
    pub alpha_tokens_traded: Option<u64>,
    pub is_deployer: bool,
    pub deployer_tokens_deployed: Option<u64>,
    pub deployer_bonding_rate: Option<f64>,
    // v0.22 reputation flags. Scope caveat: all three derive from the pump.fun
    // trade pipeline — `false` means "not observed", NOT "verified clean".
    /// ≥5 tokens early-bought & ≥80% flipped <5min. Behavior-updated (~12min
    /// cron), so it can clear if the wallet reforms. Pipeline-scoped.
    #[serde(default)]
    pub is_sniper: bool,
    /// Bought >1 token in the same block, EVER — a lifetime flag.
    #[serde(default)]
    pub is_bundler: bool,
    /// ≥5 dump cohorts + 0 runner cohorts in a rolling 42-day window
    /// (recomputed daily, up to ~48h stale).
    #[serde(default)]
    pub is_dumper: bool,
    /// Raw dump-cluster cohort counts behind `is_dumper`; `None` when the
    /// wallet has no dump-cluster record.
    #[serde(default)]
    pub dump_cluster: Option<WalletDumpCluster>,
    /// v0.23.4 — semantics reminder carried in-band: `is_sniper` /
    /// `is_bundler` / `is_dumper` are launchpad-pipeline scoped, so `false`
    /// means "not observed in covered trades", not "verified clean".
    #[serde(default)]
    pub coverage_note: Option<String>,
}

// v1.8.1 enrichments — additive, all Option<...> so old SDK builds keep
// deserializing responses that omit them.

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTopToken {
    pub token_mint: String,
    pub token_symbol: Option<String>,
    pub buys: u64,
    pub sells: u64,
    pub sol_in: f64,
    pub sol_out: f64,
    pub realized_pnl_sol: f64,
    pub current_mc_usd: Option<f64>,
    pub peak_mc_usd: Option<f64>,
    pub last_traded_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTradingStyle {
    pub total_trades: u64,
    pub avg_trade_size_sol: f64,
    /// 0–1: fraction of trades placed with `early_buyer_rank ≤ 10`.
    pub sniper_rate: f64,
    pub early_entries: u64,
    /// 0–1: fraction of tokens with both buys and sells.
    pub round_trip_rate: f64,
    pub tokens_with_round_trips: u64,
    pub median_hold_minutes: Option<f64>,
    /// "buy" | "sell" | "balanced".
    pub dominant_action: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletDeployerTierEntry {
    /// "elite" | "good" | "rising" | "moderate" | "cold" | "unranked".
    pub tier: String,
    pub count: u64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletDeployerBreakdown {
    pub total_tokens: u64,
    pub tracked_deployers: u64,
    pub by_tier: Vec<WalletDeployerTierEntry>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletRecentTrade {
    pub token_mint: String,
    pub token_symbol: Option<String>,
    /// "buy" | "sell".
    pub action: String,
    pub sol_amount: f64,
    pub block_time: i64,
    pub traded_at: String,
    pub tx_signature: String,
}

// ─── Wallet derived stats (v1.9) ────────────────────────────────────────────

#[derive(Debug, Clone, Deserialize)]
pub struct WalletStandoutTrade {
    pub token_mint: String,
    #[serde(default)]
    pub token_symbol: Option<String>,
    pub pnl_sol: f64,
    pub sol_in: f64,
    pub sol_out: f64,
    pub roi_pct: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletBiggestMiss {
    pub token_mint: String,
    #[serde(default)]
    pub token_symbol: Option<String>,
    pub actual_sol_out: f64,
    pub potential_sol_at_ath: f64,
    pub missed_sol: f64,
    pub ath_mc_usd: f64,
    #[serde(default)]
    pub sold_at_mc_usd: Option<f64>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum WalletVerdictTone {
    Green,
    Red,
    Amber,
    Muted,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletVerdict {
    pub label: String,
    pub description: String,
    pub tone: WalletVerdictTone,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletDerivedStats {
    #[serde(default)]
    pub win_rate: Option<f64>,
    #[serde(default)]
    pub roi_pct: Option<f64>,
    pub total_realized_pnl_sol: f64,
    #[serde(default)]
    pub best_trade: Option<WalletStandoutTrade>,
    #[serde(default)]
    pub worst_trade: Option<WalletStandoutTrade>,
    #[serde(default)]
    pub biggest_miss: Option<WalletBiggestMiss>,
    #[serde(default)]
    pub verdict: Option<WalletVerdict>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletStatsResponse {
    pub address: String,
    /// None when the wallet has no trades in the 90-day window but does
    /// appear in one of the flag tables.
    pub stats: Option<WalletStats>,
    pub flags: WalletFlags,
    /// Top traded tokens with realized PnL (v1.8.1+).
    #[serde(default)]
    pub top_tokens: Vec<WalletTopToken>,
    /// Trading-style signals (v1.8.1+).
    #[serde(default)]
    pub trading_style: Option<WalletTradingStyle>,
    /// Pump.fun deployer-tier distribution (v1.8.1+).
    #[serde(default)]
    pub deployer_breakdown: Option<WalletDeployerBreakdown>,
    /// Last 10 raw trades with symbols joined (v1.8.1+).
    #[serde(default)]
    pub recent_trades: Vec<WalletRecentTrade>,
    /// Derived analytics: win rate, ROI, best/worst trade, biggest miss, verdict (v1.9+).
    #[serde(default)]
    pub derived: Option<WalletDerivedStats>,
    /// v0.23.4 — trade-coverage disclosure; when `in_scope` is `false` an
    /// empty `stats` block means "outside the write-gate", not "never traded".
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletBestWorstTrade {
    pub token_mint: String,
    pub realized_sol: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletPnlSummary {
    pub realized_sol: f64,
    pub unrealized_sol: f64,
    pub total_pnl_sol: f64,
    pub total_bought_sol: f64,
    pub total_sold_sol: f64,
    /// Closed-position win count (not per-trade).
    pub wins: u64,
    pub losses: u64,
    pub win_rate: Option<f64>,
    /// Gross wins / gross losses. None when no losses (undefined math).
    pub profit_factor: Option<f64>,
    pub avg_hold_minutes: Option<u64>,
    pub median_hold_minutes: Option<u64>,
    /// Running peak-to-trough drawdown on the realized SOL curve.
    pub max_drawdown_sol: f64,
    pub open_positions_count: u64,
    pub closed_positions_count: u64,
    pub total_tokens_traded: u64,
    pub best_realized: Option<WalletBestWorstTrade>,
    pub worst_realized: Option<WalletBestWorstTrade>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletPnlCurvePoint {
    /// YYYY-MM-DD (UTC).
    pub date: String,
    pub day_pnl: f64,
    pub cumulative_pnl: f64,
    pub trades: u64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletClosedPosition {
    pub token_mint: String,
    pub buy_count: u64,
    pub sell_count: u64,
    pub bought_sol: f64,
    pub sold_sol: f64,
    pub pnl_sol: f64,
    /// `realized_sol / total_bought_sol × 100`.
    pub roi_pct: Option<f64>,
    /// First buy → last sell, in minutes.
    pub hold_minutes: Option<u64>,
    pub result: String,
    pub first_trade: Option<String>,
    pub last_trade: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletOpenPosition {
    pub token_mint: String,
    pub token_amount: f64,
    pub cost_basis_sol: f64,
    pub avg_entry_price_sol: f64,
    /// Live from mc-tracker. None if the mint has no current price.
    pub current_price_sol: Option<f64>,
    pub current_value_sol: Option<f64>,
    pub unrealized_sol: Option<f64>,
    pub unrealized_pct: Option<f64>,
    pub first_buy_at: Option<String>,
    pub buys_in_position: u64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletPnlNotes {
    /// Cost basis is observable only from this timestamp onwards.
    pub cost_basis_observable_from: String,
    /// Present when the 50k-trade hard cap was hit.
    #[serde(default)]
    pub truncated_trades: Option<u64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletPnlResponse {
    pub address: String,
    pub window_days: u32,
    pub summary: WalletPnlSummary,
    /// Sparse daily UTC buckets — only days with at least one realized event.
    pub pnl_curve: Vec<WalletPnlCurvePoint>,
    /// Sorted by `pnl_sol` DESC — best winners first.
    pub closed_positions: Vec<WalletClosedPosition>,
    pub open_positions: Vec<WalletOpenPosition>,
    pub notes: WalletPnlNotes,
    #[serde(default)]
    pub cache_hit: Option<bool>,
    /// Only present on cache hits.
    #[serde(default)]
    pub computed_at: Option<String>,
    /// Only present on cache misses.
    #[serde(default)]
    pub ttl_seconds: Option<u64>,
    /// v0.23.4 — trade-coverage disclosure; `in_scope: Some(false)` means the
    /// PnL is built from zero covered trades, not that the wallet never traded.
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletPositionsResponse {
    pub address: String,
    pub positions: Vec<WalletOpenPosition>,
    #[serde(default)]
    pub cache_hit: Option<bool>,
    #[serde(default)]
    pub computed_at: Option<String>,
    #[serde(default)]
    pub ttl_seconds: Option<u64>,
    /// v0.23.4 — trade-coverage disclosure (`None` on older cached responses).
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum WalletTradeAction {
    Buy,
    Sell,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct WalletTradesParams {
    /// 1–500; default 100.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// From `next_cursor` of a previous response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<WalletTradeAction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_mint: Option<String>,
    /// Unix epoch seconds; default now-90d.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<i64>,
    /// Unix epoch seconds; default now.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub until: Option<i64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTrade {
    pub tx_signature: String,
    pub token_mint: String,
    pub action: String,
    pub sol_amount: f64,
    pub token_amount: f64,
    /// This trade's executed price — `sol_amount / token_amount`. Added
    /// 2026-08-16; this route returned amounts and no price before. Same
    /// definition as [`TokenTrade::price_sol`].
    #[serde(default)]
    pub price_sol: Option<f64>,
    /// [`WalletTrade::price_sol`] in USD.
    #[serde(default)]
    pub price_usd: Option<f64>,
    /// Canonical pool price near this trade's slot — NOT this trade's price.
    #[serde(default)]
    pub market_price_sol: Option<f64>,
    /// [`WalletTrade::market_price_sol`] in USD.
    #[serde(default)]
    pub market_price_usd: Option<f64>,
    pub block_time: i64,
    pub traded_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTradesFilters {
    pub action: Option<String>,
    pub token_mint: Option<String>,
    pub since: i64,
    pub until: i64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletTradesResponse {
    pub address: String,
    pub trades: Vec<WalletTrade>,
    pub next_cursor: Option<String>,
    pub has_more: bool,
    pub filters: WalletTradesFilters,
    /// v0.23.4 — trade-coverage disclosure; an empty tape with `in_scope:
    /// Some(false)` means "outside the write-gate", not "never traded".
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

// ─── Wallet batch classify (/wallet/batch/classify, v0.22) ──────────────────

/// Request body for [`Wallet::batch_classify`](crate::api::wallet::Wallet::batch_classify).
#[derive(Debug, Clone, Serialize)]
pub struct WalletBatchRequest {
    /// 1–100 base58 wallet addresses. Duplicates are removed server-side.
    pub wallets: Vec<String>,
}

/// Reputation flags for one wallet in a batch-classify response. Field values
/// match the `flags` block of [`WalletStatsResponse`] exactly.
///
/// Scope caveat: `is_sniper` / `is_bundler` / `is_dumper` derive from the
/// pump.fun trade pipeline — `false` means "not observed", NOT "verified
/// clean". `is_bundler` is a lifetime flag; `is_dumper` uses a rolling 42-day
/// window (recomputed daily, up to ~48h stale).
#[derive(Debug, Clone, Deserialize)]
pub struct WalletClassification {
    pub address: String,
    pub is_sniper: bool,
    pub is_bundler: bool,
    pub is_dumper: bool,
    pub is_kol: bool,
    #[serde(default)]
    pub kol_name: Option<String>,
    /// Text enum `"none"` | `"low"` | `"medium"` | `"high"`; `None` when the
    /// wallet isn't alpha-tracked.
    #[serde(default)]
    pub bot_confidence: Option<String>,
    /// Raw dump-cluster cohort counts behind `is_dumper`; `None` when the
    /// wallet has no dump-cluster record.
    #[serde(default)]
    pub dump_cluster: Option<WalletDumpCluster>,
}

/// Response of [`Wallet::batch_classify`](crate::api::wallet::Wallet::batch_classify).
#[derive(Debug, Clone, Deserialize)]
pub struct WalletBatchClassifyResponse {
    /// One entry per unique input wallet, in de-duplicated input order.
    pub wallets: Vec<WalletClassification>,
    /// Number of unique wallets classified.
    pub count: u32,
    /// ISO 8601 — when the batch was computed.
    pub as_of: String,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct WalletHoldingsParams {
    /// 1–500; default 200.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Minimum USD value per holding; default 0.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_value_usd: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Holding {
    pub mint: String,
    pub symbol: Option<String>,
    pub name: Option<String>,
    pub amount: f64,
    /// Raw base-unit amount as a decimal string (no precision loss).
    pub amount_raw: String,
    pub decimals: u32,
    /// "spl" | "token2022".
    pub token_program: String,
    pub price_usd: Option<f64>,
    pub value_usd: Option<f64>,
    pub market_cap_usd: Option<f64>,
    pub is_bonded: Option<bool>,
    pub trade_derived_amount: Option<f64>,
    /// On-chain amount minus trade-derived net position — exposes non-swap
    /// flows (airdrops, insider funding, wallet-hopping).
    pub transfer_delta: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletHoldingsSummary {
    pub token_accounts: u32,
    pub non_zero: u32,
    pub returned: u32,
    pub priced: u32,
    pub total_value_usd: f64,
    pub truncated: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WalletHoldingsResponse {
    pub address: String,
    pub sol_balance: f64,
    pub holdings: Vec<Holding>,
    pub summary: WalletHoldingsSummary,
    pub verified_at: String,
    pub trade_window_days: u32,
    #[serde(default)]
    pub cache_hit: Option<bool>,
    #[serde(default)]
    pub ttl_seconds: Option<u64>,
    /// v0.23.4 — trade-coverage disclosure for the trade-derived enrichments
    /// (`transfer_delta`, cost-basis fields); the holdings themselves are live
    /// on-chain reads and unaffected.
    #[serde(default)]
    pub coverage: Option<TokenTradesCoverage>,
}

// ─── Tools ──────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize)]
pub struct ToolsSearchParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Tool {
    pub name: String,
    pub slug: String,
    pub tagline: String,
    pub website_url: String,
    #[serde(default)]
    pub logo_url: Option<String>,
    pub categories: Vec<String>,
    #[serde(default)]
    pub pricing_model: Option<String>,
    #[serde(default)]
    pub average_rating: Option<f64>,
    #[serde(default)]
    pub review_count: Option<u32>,
    #[serde(default)]
    pub health_score: Option<f64>,
    #[serde(default)]
    pub url: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ToolsSearchResponse {
    pub tools: Vec<Tool>,
    pub count: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Streaming ──────────────────────────────────────────────────────────────

/// Your WebSocket streaming token, as returned by
/// [`Stream::get_token`](crate::api::stream::Stream::get_token) and
/// [`Stream::rotate_token`](crate::api::stream::Stream::rotate_token).
///
/// **Stream tokens do not expire** (since 2026-08-27). `get_token` returns the
/// same value on every call; it only stops working when your subscription
/// lapses or you explicitly rotate it (`{"rotate": true}` — the previous value
/// then stays valid for 60 s so live sockets can reconnect). A WebSocket close
/// code `4001` means "mint a new token", never "the timer ran out".
#[derive(Debug, Clone, Deserialize)]
pub struct StreamToken {
    pub token: String,
    /// Always `None` since 2026-08-27 — stream tokens do not expire; kept for
    /// wire compatibility. Do not schedule refreshes on it.
    #[serde(default)]
    pub expires_at: Option<String>,
    /// Always `None` since 2026-08-27 — stream tokens do not expire; kept for
    /// wire compatibility.
    #[serde(default)]
    pub next_refresh_at: Option<String>,
    /// `Some(true)` when this call replaced an existing token (a
    /// `{"rotate": true}` request — see
    /// [`Stream::rotate_token`](crate::api::stream::Stream::rotate_token));
    /// `Some(false)` when the existing token was returned unchanged or was
    /// minted for the first time. `None` from servers older than 2026-08-27.
    #[serde(default)]
    pub rotated: Option<bool>,
    /// Human-readable lifetime statement from the server: the token does not
    /// expire, is identical on every call, and dies only on subscription lapse
    /// or an explicit rotation. `None` from servers older than 2026-08-27.
    #[serde(default)]
    pub lifetime: Option<String>,
    pub ws_url: String,
    /// Only present for ULTRA-tier subscribers.
    #[serde(default)]
    pub dex_ws_url: Option<String>,
    pub usage: String,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

/// A single live WebSocket session for your account, as returned by
/// [`Stream::sessions`](crate::api::stream::Stream::sessions).
#[derive(Debug, Clone, Deserialize)]
pub struct StreamSession {
    /// Numeric session id (serialized as a string). Pass to
    /// [`Stream::kill_session`](crate::api::stream::Stream::kill_session).
    pub id: String,
    /// Originating service: `"ws-streaming"` or `"dex-stream"`.
    pub service: String,
    pub tier: String,
    pub channels: Vec<String>,
    pub connected_at: String,
    #[serde(default)]
    pub remote_ip: Option<String>,
    /// Messages pushed to this socket so far.
    pub messages_sent: u64,
}

/// Response of [`Stream::sessions`](crate::api::stream::Stream::sessions).
#[derive(Debug, Clone, Deserialize)]
pub struct StreamSessionsResponse {
    pub sessions: Vec<StreamSession>,
    pub count: u32,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

/// Response of [`Stream::kill_session`](crate::api::stream::Stream::kill_session).
#[derive(Debug, Clone, Deserialize)]
pub struct StreamSessionEvicted {
    pub evicted: bool,
    pub id: String,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Webhooks ───────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct WebhookCreateParams {
    pub url: String,
    pub events: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<HashMap<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct WebhookUpdateParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<HashMap<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Webhook {
    pub id: i64,
    pub url: String,
    pub events: Vec<String>,
    pub filters: Option<HashMap<String, serde_json::Value>>,
    pub status: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WebhookListResponse {
    pub webhooks: Vec<Webhook>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct WebhookDeleteResponse {
    pub success: bool,
}

// ─── /me — v0.8 (server-side v1.7, 2026-05-12) ───────────────────────────────

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ApiTier {
    Basic,
    Trader,
    Pro,
    Ultra,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeQuotaWindow {
    pub limit: u64,
    pub used: u64,
    pub remaining: u64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeDailyQuota {
    pub limit: u64,
    pub used: u64,
    pub remaining: u64,
    pub resets_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeBurstQuota {
    pub limit: u64,
    pub used: u64,
    pub remaining: u64,
    pub window_seconds: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeQuota {
    pub daily: MeDailyQuota,
    pub burst: MeBurstQuota,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeSubscription {
    pub status: String,
    pub billing_cycle: String,
    pub current_period_end: Option<String>,
    pub started_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeFeatureSlot {
    pub limit: u32,
    #[serde(default)]
    pub used: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeFeatureUsage {
    pub webhooks: MeFeatureSlot,
    pub ws_connections: MeFeatureSlot,
    pub dex_connections: MeFeatureSlot,
    pub copytrade_wallets: MeFeatureSlot,
    pub copytrade_rules: MeFeatureSlot,
    pub coordination_rules: MeFeatureSlot,
    pub first_touch_subscriptions: MeFeatureSlot,
    pub wallet_tracker_watchlist: MeWatchlistSlot,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeWatchlistSlot {
    #[serde(default)]
    pub used: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MeResponse {
    pub subscriber: String,
    pub tier: String,
    pub tier_label: String,
    pub subscription: Option<MeSubscription>,
    pub quota: MeQuota,
    pub features: MeFeatureUsage,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── /tokens (directory list) — v0.8 ─────────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize)]
pub struct TokensListParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_mc: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mc: Option<f64>,
    /// Default 2000. Set Some(0.0) to disable the dust floor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_liq: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_h: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub primary_dex: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authority_revoked: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exclude_token2022: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_lp_burnt_pct: Option<f64>,
    /// Post-filter: organic-volume floor in last 1h.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_volume_1h_usd: Option<f64>,
    /// Post-filter: MEV/bot share ceiling as % of total.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_mev_share_pct: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mc_change_1h_min_pct: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mc_change_1h_max_pct: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
    /// Lower bound on `liquidity_to_mc_ratio` (`liquidity_usd / market_cap`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_liq_mc_ratio: Option<f64>,
    /// Upper bound on `liquidity_to_mc_ratio`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_liq_mc_ratio: Option<f64>,
    /// Filter tokens by deployer reputation tier (e.g. `"elite"`, `"good"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployer_tier: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokenSummary {
    pub mint: String,
    pub symbol: Option<String>,
    pub name: Option<String>,
    pub price_usd: Option<f64>,
    pub market_cap_usd: Option<f64>,
    pub fdv_usd: Option<f64>,
    pub liquidity_usd: Option<f64>,
    pub primary_dex: Option<String>,
    pub authorities_revoked: bool,
    pub lp_burnt_pct: Option<f64>,
    pub is_token_2022: bool,
    pub last_trade_time: Option<String>,
    pub mc_change_5m_pct: Option<f64>,
    pub mc_change_1h_pct: Option<f64>,
    pub organic_volume_1h_usd: Option<f64>,
    pub mev_share_pct: Option<f64>,
    /// Liquidity-to-MC ratio (`liquidity_usd / market_cap`).
    pub liquidity_to_mc_ratio: Option<f64>,
    /// Deployer reputation tier (e.g. `"elite"`, `"good"`, `"unranked"`).
    pub deployer_tier: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokensListPagination {
    pub limit: u32,
    pub offset: u32,
    pub returned: u32,
    pub has_more: bool,
    pub post_filtered: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TokensListResponse {
    pub tokens: Vec<TokenSummary>,
    pub pagination: TokensListPagination,
    pub filters: serde_json::Value,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Price alerts (v1.9) ────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PriceAlertDeliveryMode {
    Webhook,
    Websocket,
    Both,
}

impl PriceAlertDeliveryMode {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Webhook => "webhook",
            Self::Websocket => "websocket",
            Self::Both => "both",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PriceAlertStatus {
    Watching,
    Dipped,
    Recovered,
    Expired,
}

impl PriceAlertStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Watching => "watching",
            Self::Dipped => "dipped",
            Self::Recovered => "recovered",
            Self::Expired => "expired",
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct PriceAlertCreateParams {
    /// Solana mint address.
    pub token_mint: String,
    /// Drop % threshold (0.01–99.99). Alert fires when MC drops below baseline x (1 - drop_pct/100).
    pub drop_pct: f64,
    /// Recovery % threshold (0.01–1000). After dip fires, alert fires again when MC rises
    /// above dip_low x (1 + recovery_pct/100). Optional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery_pct: Option<f64>,
    /// Optional label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Default: "webhook".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_mode: Option<PriceAlertDeliveryMode>,
    /// Required when delivery_mode is "webhook" or "both". Must be HTTPS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct PriceAlertUpdateParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_mode: Option<PriceAlertDeliveryMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlert {
    pub id: i64,
    #[serde(default)]
    pub name: Option<String>,
    pub token_mint: String,
    #[serde(default)]
    pub token_symbol: Option<String>,
    pub baseline_mc_usd: f64,
    pub drop_pct: f64,
    #[serde(default)]
    pub recovery_pct: Option<f64>,
    pub status: PriceAlertStatus,
    #[serde(default)]
    pub dip_low_mc_usd: Option<f64>,
    #[serde(default)]
    pub dip_fired_at: Option<String>,
    pub delivery_mode: PriceAlertDeliveryMode,
    #[serde(default)]
    pub webhook_url: Option<String>,
    pub is_active: bool,
    pub expires_at: String,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlertListResponse {
    pub alerts: Vec<PriceAlert>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlertCreateResponse {
    pub alert: PriceAlert,
    /// One-time HMAC secret. Save it — will not be shown again.
    #[serde(default)]
    pub webhook_secret: Option<String>,
    #[serde(default)]
    pub note: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlertGetResponse {
    pub alert: PriceAlert,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlertUpdateResponse {
    pub alert: PriceAlert,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlertDeleteResponse {
    pub deleted: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlertEvent {
    pub id: i64,
    pub alert_id: i64,
    /// "dip" or "recovery".
    pub event_type: String,
    pub fired_at: String,
    pub token_mint: String,
    pub baseline_mc_usd: f64,
    pub current_mc_usd: f64,
    #[serde(default)]
    pub drop_pct_actual: Option<f64>,
    #[serde(default)]
    pub dip_low_mc_usd: Option<f64>,
    #[serde(default)]
    pub recovery_pct_actual: Option<f64>,
    pub delivered: bool,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct PriceAlertEventsParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alert_id: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PriceAlertEventsResponse {
    pub events: Vec<PriceAlertEvent>,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}

// ─── Almost-bonded (/tokens/almost-bonded) — v0.18 ──────────────────────────

/// Sort order for [`Token::almost_bonded`](crate::api::token::Token::almost_bonded).
/// Defaults to [`AlmostBondedSort::VelocityDesc`] server-side when unset.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum AlmostBondedSort {
    /// Fastest bonding-progress velocity first (default).
    #[default]
    VelocityDesc,
    /// Closest to graduation first.
    ProgressDesc,
    /// Shortest estimated time-to-bond first.
    EtaAsc,
}

impl AlmostBondedSort {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::VelocityDesc => "velocity_desc",
            Self::ProgressDesc => "progress_desc",
            Self::EtaAsc => "eta_asc",
        }
    }
}

/// Query params for [`Token::almost_bonded`](crate::api::token::Token::almost_bonded).
/// Unset fields are omitted from the query string.
#[derive(Debug, Clone, Default, Serialize)]
pub struct AlmostBondedParams {
    /// Lower bound on bonding progress (percent, 0–100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_progress: Option<f64>,
    /// Upper bound on bonding progress (percent, 0–100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_progress: Option<f64>,
    /// Lower bound on bonding-progress velocity (percentage points per minute).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_velocity_pct_per_min: Option<f64>,
    /// Upper bound on token age in minutes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_age_minutes: Option<f64>,
    /// Filter by deployer reputation tier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployer_tier: Option<DeployerTier>,
    /// Only tokens whose mint+freeze authorities are revoked.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authority_revoked: Option<bool>,
    /// Lower bound on liquidity (USD).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_liq: Option<f64>,
    /// Sort order — defaults to `velocity_desc`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<AlmostBondedSort>,
    /// Max number of tokens to return.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// A pre-bond pump.fun token near graduation. Nullable fields are `None` when
/// the underlying data was unavailable.
#[derive(Debug, Clone, Deserialize)]
pub struct AlmostBondedToken {
    pub mint: String,
    #[serde(default)]
    pub symbol: Option<String>,
    #[serde(default)]
    pub name: Option<String>,
    /// Bonding-curve progress toward graduation (percent, 0–100).
    pub progress_pct: f64,
    /// Bonding-progress velocity (percentage points per minute).
    #[serde(default)]
    pub velocity_pct_per_min: Option<f64>,
    /// Estimated minutes until graduation at the current velocity.
    #[serde(default)]
    pub eta_minutes: Option<f64>,
    /// Whether progress has stalled (no recent forward movement).
    pub stalled: bool,
    /// Real SOL reserves currently in the bonding curve.
    #[serde(default)]
    pub real_sol_reserves: Option<f64>,
    #[serde(default)]
    pub market_cap_usd: Option<f64>,
    #[serde(default)]
    pub liquidity_usd: Option<f64>,
    /// Whether mint+freeze authorities are revoked.
    pub authorities_revoked: bool,
    /// Deployer reputation tier (e.g. `"elite"`, `"good"`, `"unranked"`).
    #[serde(default)]
    pub deployer_tier: Option<String>,
    #[serde(default)]
    pub age_minutes: Option<f64>,
}

/// Pre-bond pump.fun tokens near graduation, ranked by velocity (PRO/ULTRA).
#[derive(Debug, Clone, Deserialize)]
pub struct AlmostBondedResponse {
    pub tokens: Vec<AlmostBondedToken>,
    pub filters: serde_json::Value,
    pub returned: u32,
    pub note: String,
    #[serde(default, rename = "_rid")]
    pub _rid: Option<String>,
}