miracle-api 0.6.0

Miracle is a pay2e protocol for sovereign individuals living in Mirascape Horizon.
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
use serde::{Deserialize, Serialize};
use solana_program::hash::hashv;
use steel::*;

use crate::{
    consts::*,
    dmt::{DailyParticipantData, EpochClaimData, SocialClaimData},
    instruction::*,
    state::{config_pda, metrics_pda, proof_pda, snapshot_pda, treasury_pda},
};

/// Builds a claim instruction.
///
/// The reward amount is calculated on-chain using the transparent formula:
/// reward = (activity_count * customer_reward_pool) / total_customer_activity
///
/// Where:
/// - `activity_count` is extracted from the participant data
/// - `customer_reward_pool` and `total_customer_activity` are read from epoch data
///
/// ## Parameters
/// - `signer`: The wallet signing the transaction
/// - `beneficiary`: The wallet receiving the rewards
/// - `epoch`: The epoch number for the claim
/// - `participant_data`: Participant data including activity count and timestamps
/// - `payment_proof`: Merkle proof path for payment verification
/// - `payment_indices`: Merkle proof path indices (true = right, false = left)
/// - `seal_proof`: Merkle proof path for seal verification
/// - `seal_indices`: Merkle proof path indices (true = right, false = left)
/// - `payment_root`: Payment merkle root for verification
/// - `epoch_data`: Epoch-specific data for accurate reward calculation
/// - `participant_type`: 0 for customer, 1 for merchant
/// - `social_data`: Optional social media engagement data
///
/// ## Returns
/// - Instruction for claiming rewards
///
/// ## Note
/// Users can estimate their rewards off-chain using the transparent calculation functions
/// in `consts.rs`. The on-chain calculation will match the off-chain estimation exactly.
pub fn claim(
    signer: Pubkey,
    beneficiary: Pubkey,
    epoch: u64,
    participant_data: DailyParticipantData,
    payment_proof: Vec<[u8; 32]>,
    payment_indices: Vec<bool>,
    seal_proof: Vec<[u8; 32]>,
    seal_indices: Vec<bool>,
    payment_root: [u8; 32],
    epoch_data: EpochClaimData,
    participant_type: u8,
    social_data: Option<SocialClaimData>,
) -> Instruction {
    let mut data = Vec::new();

    // Use the Claim struct's to_bytes() method for consistent serialization
    let claim_data = Claim {
        epoch: epoch.to_le_bytes(),
        payment_proof_length: payment_proof.len() as u8,
        seal_proof_length: seal_proof.len() as u8,
        participant_type,
        has_social: if social_data.is_some() { 1u8 } else { 0u8 },
        _padding: [0u8; 4],
    };
    data.extend_from_slice(&claim_data.to_bytes());

    // Append participant data
    data.extend_from_slice(bytemuck::bytes_of(&participant_data));

    // Append payment proof data
    for path_node in payment_proof {
        data.extend_from_slice(&path_node);
    }

    // Append payment indices data
    for &is_right in &payment_indices {
        data.push(if is_right { 1u8 } else { 0u8 });
    }

    // Append seal proof data
    for path_node in seal_proof {
        data.extend_from_slice(&path_node);
    }

    // Append seal indices data
    for &is_right in &seal_indices {
        data.push(if is_right { 1u8 } else { 0u8 });
    }

    // Append payment root data
    data.extend_from_slice(&payment_root);

    // Append epoch data
    data.extend_from_slice(bytemuck::bytes_of(&epoch_data));

    // Append social data if provided
    if let Some(social) = social_data {
        data.extend_from_slice(bytemuck::bytes_of(&social));
    }

    let proof_pda = proof_pda(signer);
    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),                     // [0] signer
            AccountMeta::new(beneficiary, false),               // [1] beneficiary
            AccountMeta::new(proof_pda.0, false),               // [2] proof PDA
            AccountMeta::new(TREASURY_ADDRESS, false),          // [3] treasury
            AccountMeta::new(TREASURY_TOKENS_ADDRESS, false),   // [4] treasury tokens
            AccountMeta::new_readonly(spl_token::ID, false),    // [5] token program
            AccountMeta::new_readonly(SNAPSHOT_ADDRESS, false), // [6] snapshot
            AccountMeta::new_readonly(CONFIG_ADDRESS, false),   // [7] config
        ],
        data,
    }
}

/// Create social claim data for social media engagement.
///
/// This function creates a `SocialClaimData` struct with the provided social media
/// information. The oracle signature should be provided by the authorized oracle
/// authority.
///
/// ## Parameters
/// - `post_url`: Social media post URL (max 256 bytes)
/// - `engagement_score`: Engagement score for the post (u32)
/// - `post_timestamp`: Unix timestamp when post was made (i64)
/// - `oracle_signature`: Ed25519 signature from authorized oracle
///
/// ## Oracle Signature Requirements
/// The oracle must sign a message with the following format:
///
/// `epoch:user_pubkey:post_url:engagement_score:post_timestamp`
///
/// This format prevents replay attacks by including epoch and user context.
///
/// ## Returns
/// - `SocialClaimData` struct ready for social claim
///
/// ## Example
/// ```rust
/// use miracle_api::sdk::create_social_claim_data;
///
/// let social_data = create_social_claim_data(
///     "https://twitter.com/user/123",
///     500,
///     1640995200,
///     &[0u8; 64], // Oracle signature
/// );
/// ```
pub fn create_social_claim_data(
    post_url: &str,
    engagement_score: u32,
    post_timestamp: i64,
    oracle_signature: &[u8; 64],
) -> SocialClaimData {
    let mut post_url_bytes = [0u8; 256];
    let url_bytes = post_url.as_bytes();
    let copy_len = std::cmp::min(url_bytes.len(), 256);
    post_url_bytes[..copy_len].copy_from_slice(&url_bytes[..copy_len]);

    SocialClaimData {
        post_url: post_url_bytes,
        oracle_signature: *oracle_signature,
        engagement_score: engagement_score.to_le_bytes(),
        post_timestamp: post_timestamp.to_le_bytes(),
        _padding: [0u8; 4],
    }
}

/// Validate social media post URL for required content.
///
/// This function checks if the social media post URL contains the required
/// hashtags and mentions for social marketing rewards.
///
/// ## Parameters
/// - `post_url`: Social media post URL to validate
///
/// ## Returns
/// - `true` if the URL contains required content, `false` otherwise
///
/// ## Required Content
/// - Must contain `#MiracleRewards` hashtag
/// - Must contain `@MiracleProtocol` mention
/// - URL must be from supported platforms (Twitter, Instagram, etc.)
pub fn validate_social_post_url(post_url: &str) -> bool {
    let url_lower = post_url.to_lowercase();

    // Check for required hashtag
    if !url_lower.contains("#miraclerewards") {
        return false;
    }

    // Check for required mention
    if !url_lower.contains("@miracleprotocol") {
        return false;
    }

    // Check for supported platforms
    let supported_platforms = [
        "twitter.com",
        "x.com",
        "instagram.com",
        "facebook.com",
        "linkedin.com",
        "tiktok.com",
    ];

    supported_platforms
        .iter()
        .any(|platform| url_lower.contains(platform))
}

/// Calculate social reward amount based on engagement and base reward.
///
/// This function calculates the social reward amount based on the engagement
/// score and the base reward per post. The calculation matches the on-chain
/// logic used in the social claim instruction.
///
/// ## Parameters
/// - `engagement_score`: Engagement metrics for the social post
/// - `base_reward_per_post`: Base reward amount per post
///
/// ## Returns
/// - Total reward amount (base reward + engagement bonus)
///
/// ## Formula
/// - Base reward: `base_reward_per_post`
/// - Engagement bonus: `(engagement_score - 1000) / 100` if score > 1000
/// - Total reward: `base_reward + engagement_bonus`
pub fn calculate_social_reward_amount(engagement_score: u32, base_reward_per_post: u32) -> u64 {
    let base_reward = base_reward_per_post as u64;
    let engagement_score_u64 = engagement_score as u64;

    let engagement_bonus = if engagement_score_u64 > 1000 {
        (engagement_score_u64 - 1000) / 100 // 1 MIRACLE per 100 engagement points above 1000
    } else {
        0
    };

    base_reward + engagement_bonus
}

/// Builds a social claim instruction.
///
/// This instruction allows users to claim social marketing rewards based on their
/// social media engagement. Social rewards require payment activity in the same epoch
/// and are verified through oracle signatures to prevent gaming.
///
/// ## Parameters
/// - `signer`: The wallet signing the transaction
/// - `beneficiary`: The wallet receiving the rewards
/// - `epoch`: The epoch number for the claim (payment activity required)
/// - `merkle_root`: Merkle root for payment verification
/// - `merkle_path`: Merkle proof path for payment activity
/// - `path_indices`: Merkle proof path indices (true = right, false = left)
/// - `participant_type`: 0 for customer, 1 for merchant
/// - `social_data`: Social media verification data
///
/// ## Returns
/// - Instruction for claiming social rewards
///
/// ## Requirements

/// Builds a close instruction.
///
/// This instruction allows a user to close their Proof account and recover the rent.
/// The Proof account can only be closed if:
/// 1. The signer is the Proof account owner (authority)
/// 2. No rewards have been claimed (total_claimed_rewards == 0)
///
/// ## Accounts
/// - `signer`: The Proof account owner (must be a signer)
/// - `proof`: The Proof account to close (PDA derived from signer)
/// - `system_program`: System program for rent recovery
///
/// ## Safety Features
/// - **Owner-only**: Only the Proof account owner can close it
/// - **No claims allowed**: Cannot close if rewards have been claimed
/// - **Rent recovery**: All rent is returned to the signer
///
/// ## Use Cases
/// - Recovering rent when no longer participating
/// - Clean account management
/// - Reopening with a fresh Proof account later
///
/// ## Returns
/// - Instruction for closing the Proof account
pub fn close(signer: Pubkey) -> Instruction {
    let proof = proof_pda(signer).0;
    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(proof, false),
            AccountMeta::new_readonly(solana_program::system_program::ID, false),
        ],
        data: Close {}.to_bytes(),
    }
}

/// Builds an open instruction.
pub fn open(signer: Pubkey, payer: Pubkey) -> Instruction {
    let proof_pda = proof_pda(signer);
    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(payer, true),
            AccountMeta::new(proof_pda.0, false),
            AccountMeta::new_readonly(solana_program::system_program::ID, false),
        ],
        data: Open {}.to_bytes(),
    }
}

/// Builds a reset instruction.
///
/// This instruction implements the Community-Driven Decay model by adjusting daily rewards
/// based on community health metrics stored in the Metrics account.
pub fn reset(signer: Pubkey) -> Instruction {
    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(CONFIG_ADDRESS, false),
            AccountMeta::new_readonly(METRICS_ADDRESS, false),
            AccountMeta::new(MINT_ADDRESS, false),
            AccountMeta::new(TREASURY_ADDRESS, false),
            AccountMeta::new(TREASURY_TOKENS_ADDRESS, false),
            AccountMeta::new_readonly(spl_token::ID, false),
        ],
        data: Reset {}.to_bytes(),
    }
}

// MI: abandoned for community trust/confidence
// // Build an upgrade instruction.
// pub fn upgrade(signer: Pubkey, beneficiary: Pubkey, sender: Pubkey, amount: u64) -> Instruction {
//     Instruction {
//         program_id: crate::ID,
//         accounts: vec![
//             AccountMeta::new(signer, true),
//             AccountMeta::new(beneficiary, false),
//             AccountMeta::new(MINT_ADDRESS, false),
//             AccountMeta::new(MINT_V1_ADDRESS, false),
//             AccountMeta::new(sender, false),
//             AccountMeta::new(TREASURY_ADDRESS, false),
//             AccountMeta::new_readonly(spl_token::ID, false),
//             AccountMeta::new_readonly(CONFIG_ADDRESS, false),
//         ],
//         data: Upgrade {
//             amount: amount.to_le_bytes(),
//         }
//         .to_bytes(),
//     }
// }

// /// Build an evolve instruction.
// pub fn evolve(signer: Pubkey, evolvable: bool) -> Instruction {
//     Instruction {
//         program_id: crate::ID,
//         accounts: vec![
//             AccountMeta::new(signer, true),
//             AccountMeta::new(CONFIG_ADDRESS, false),
//         ],
//         data: Evolve {
//             evolvable: evolvable as u8,
//         }
//         .to_bytes(),
//     }
// }

/// Builds an initialize instruction.
pub fn initialize(signer: Pubkey, project_wallet: Pubkey) -> Instruction {
    let config_pda = config_pda();
    let mint_pda = Pubkey::find_program_address(&[MINT, MINT_NOISE.as_slice()], &crate::ID);
    let treasury_pda = treasury_pda();
    let snapshot_pda = snapshot_pda();
    let metrics_pda = metrics_pda();
    let metadata_pda = Pubkey::find_program_address(
        &[
            METADATA,
            mpl_token_metadata::ID.as_ref(),
            mint_pda.0.as_ref(),
        ],
        &mpl_token_metadata::ID,
    );
    // let treasury_tokens_pda = Pubkey::find_program_address(
    //     &[
    //         treasury_pda.0.as_ref(),
    //         spl_token::id().as_ref(),
    //         MINT_ADDRESS.as_ref(),
    //     ],
    //     &spl_associated_token_account::id(),
    // );
    let project_tokens_pda = Pubkey::find_program_address(
        &[
            project_wallet.as_ref(),
            spl_token::id().as_ref(),
            MINT_ADDRESS.as_ref(),
        ],
        &spl_associated_token_account::id(),
    );

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(config_pda.0, false),
            AccountMeta::new(snapshot_pda.0, false),
            AccountMeta::new(metrics_pda.0, false),
            AccountMeta::new(metadata_pda.0, false),
            AccountMeta::new(mint_pda.0, false),
            AccountMeta::new(treasury_pda.0, false),
            AccountMeta::new(TREASURY_TOKENS_ADDRESS, false),
            AccountMeta::new(project_wallet, false),
            AccountMeta::new(project_tokens_pda.0, false),
            AccountMeta::new_readonly(system_program::ID, false),
            AccountMeta::new_readonly(spl_token::ID, false),
            AccountMeta::new_readonly(spl_associated_token_account::ID, false),
            AccountMeta::new_readonly(mpl_token_metadata::ID, false),
            AccountMeta::new_readonly(sysvar::rent::ID, false),
        ],
        data: Initialize { project_wallet }.to_bytes(),
    }
}

/// Builds an update oracle instruction.
///
/// This instruction allows the current oracle authority to update itself to a new oracle authority.
/// Only the current oracle authority can execute this instruction.
///
/// ## Parameters
/// - `oracle`: The current oracle authority public key (must be a signer)
/// - `new_oracle_authority`: The new oracle authority public key
///
/// ## Returns
/// An instruction that can be included in a transaction to update the oracle authority.
///
/// ## Security
/// - Only the current oracle authority can execute this instruction
/// - New oracle authority must be different from current and not zero
/// - Both main and social oracle authorities are updated consistently
///
/// ## Example
/// ```rust,no_run
/// use steel::Pubkey;
/// let current_oracle = Pubkey::new_unique();
/// let new_oracle = Pubkey::new_unique();
/// let instruction = miracle_api::sdk::update_oracle(current_oracle, new_oracle);
/// ```
pub fn update_oracle(oracle: Pubkey, new_oracle_authority: Pubkey) -> Instruction {
    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(oracle, true),
            AccountMeta::new(CONFIG_ADDRESS, false),
        ],
        data: UpdateOracle {
            new_oracle_authority,
        }
        .to_bytes(),
    }
}

/// Builds an update snapshot instruction.
pub fn update_snapshot(
    oracle: Pubkey,
    epoch: u64,
    seal_merkle_root: [u8; 32],
    payment_merkle_root: [u8; 32],
    epoch_hash: [u8; 32],
    customer_reward_pool: u64,
    merchant_reward_pool: u64,
    customer_participants: u32,
    merchant_participants: u32,
    total_customer_payments: u32,
    total_merchant_payments: u32,
) -> Instruction {
    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(oracle, true),
            AccountMeta::new(SNAPSHOT_ADDRESS, false),
            AccountMeta::new_readonly(CONFIG_ADDRESS, false),
            AccountMeta::new(TREASURY_ADDRESS, false),
        ],
        data: UpdateSnapshot {
            epoch: epoch.to_le_bytes(),
            seal_merkle_root,
            payment_merkle_root,
            epoch_hash,
            customer_reward_pool: customer_reward_pool.to_le_bytes(),
            merchant_reward_pool: merchant_reward_pool.to_le_bytes(),
            customer_participants: customer_participants.to_le_bytes(),
            merchant_participants: merchant_participants.to_le_bytes(),
            total_customer_payments: total_customer_payments.to_le_bytes(),
            total_merchant_payments: total_merchant_payments.to_le_bytes(),
        }
        .to_bytes(),
    }
}

/// Builds an update community metrics instruction.
///
/// This function creates an instruction to update community health metrics used for
/// the Enhanced Community-Driven Decay model. Only the oracle authority can execute this instruction.
///
/// ## Parameters
/// - `oracle`: The oracle authority public key (must be a signer)
/// - `weekly_active_users`: Number of active users in the past week
/// - `weekly_retention_rate`: Retention rate in basis points (0-10000, 0-100%)
/// - `user_weight`: User weight in basis points (0-10000) for weighted geometric mean
/// - `volume_weight`: Volume weight in basis points (0-10000) for weighted geometric mean
/// - `retention_weight`: Retention weight in basis points (0-10000) for weighted geometric mean
///
/// ## Returns
/// An instruction that can be included in a transaction to update community metrics.
///
/// ## Security
/// - The oracle must be a signer of the transaction
/// - Input validation occurs on-chain
/// - Only the authorized oracle can update metrics
///
/// ## Example
/// ```rust,no_run
/// use steel::Pubkey;
/// let oracle_pubkey = Pubkey::new_unique();
/// let instruction = miracle_api::sdk::update_metrics(
///     oracle_pubkey,
///     5000,        // 5,000 active users
///     7500,        // 75% retention rate
///     4000,        // 40% user weight
///     3500,        // 35% activity weight
///     2500,        // 25% retention weight
///     50_000,      // 50,000 transactions
///     7000,        // 70% customer reward share
///     3000,        // 30% merchant reward share
/// );
/// ```
pub fn update_metrics(
    oracle: Pubkey,
    weekly_active_users: u32,
    weekly_retention_rate: u16,
    user_weight: u16,
    activity_weight: u16,
    retention_weight: u16,
    weekly_activity_count: u32,
    customer_reward_share: u16,
    merchant_reward_share: u16,
) -> Instruction {
    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(oracle, true),
            AccountMeta::new(METRICS_ADDRESS, false),
            AccountMeta::new_readonly(CONFIG_ADDRESS, false),
        ],
        data: UpdateMetrics {
            weekly_active_users: weekly_active_users.to_le_bytes(),
            weekly_retention_rate: weekly_retention_rate.to_le_bytes(),
            user_weight: user_weight.to_le_bytes(),
            activity_weight: activity_weight.to_le_bytes(),
            retention_weight: retention_weight.to_le_bytes(),
            weekly_activity_count: weekly_activity_count.to_le_bytes(),
            customer_reward_share: customer_reward_share.to_le_bytes(),
            merchant_reward_share: merchant_reward_share.to_le_bytes(),
            _padding: [0u8; 4], // 4 bytes padding for 8-byte alignment
        }
        .to_bytes(),
    }
}

/// Validates community metrics parameters before creating an instruction.
///
/// This function helps oracles validate their inputs before submitting transactions,
/// providing better error handling and user experience.
///
/// ## Parameters
/// - `weekly_active_users`: Number of active users in the past week
/// - `weekly_retention_rate`: Retention rate in basis points (0-10000, 0-100%)
/// - `user_weight`: User weight in basis points (0-10000) for weighted geometric mean
/// - `activity_weight`: Activity weight in basis points (0-10000) for weighted geometric mean
/// - `retention_weight`: Retention weight in basis points (0-10000) for weighted geometric mean
/// - `weekly_activity_count`: Number of transactions in the past week
/// - `customer_reward_share`: Customer reward percentage in basis points (0-10000)
/// - `merchant_reward_share`: Merchant reward percentage in basis points (0-10000)
///
/// ## Returns
/// - `Ok(())` if all parameters are valid
/// - `Err(MiracleError)` with specific error if validation fails
///
/// ## Validation Rules
/// - Weights must sum to 10000 (100%)
/// - Reward shares must sum to 10000 (100%)
/// - Retention rate must be 0-10000 (0-100%)

/// - Activity count must be reasonable (0-1M transactions per week)
/// - All numeric values must be reasonable
pub fn validate_community_metrics(
    weekly_active_users: u32,
    weekly_retention_rate: u16,
    user_weight: u16,
    activity_weight: u16,
    retention_weight: u16,
    weekly_activity_count: u32,
    customer_reward_share: u16,
    merchant_reward_share: u16,
) -> Result<(), crate::error::MiracleError> {
    // Validate weights sum to 10000 (100%)
    let total_weight = user_weight
        .saturating_add(activity_weight)
        .saturating_add(retention_weight);
    if total_weight != 10000 {
        return Err(crate::error::MiracleError::InvalidWeights);
    }

    // Validate reward shares sum to 10000 (100%)
    let total_reward_share = customer_reward_share.saturating_add(merchant_reward_share);
    if total_reward_share != 10000 {
        return Err(crate::error::MiracleError::InvalidRewardSplit);
    }

    // Validate retention rate bounds (0-10000)
    if weekly_retention_rate > 10000 {
        return Err(crate::error::MiracleError::InvalidRetentionRate);
    }

    // Validate activity count bounds (reasonable bounds: 0-1M transactions per week)
    if weekly_activity_count > 1_000_000 {
        return Err(crate::error::MiracleError::InvalidActivityCount);
    }

    // Validate that weights are reasonable (not all zero)
    if user_weight == 0 && activity_weight == 0 && retention_weight == 0 {
        return Err(crate::error::MiracleError::InvalidWeights);
    }

    // Validate that weekly metrics are reasonable (not unreasonably large)
    if weekly_active_users > 1_000_000 {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    Ok(())
}

/// Complete transparent calculation for customer rewards.
/// This function combines all steps of the reward calculation for transparency.
///
/// ## Formula Chain
/// 1. daily_rewards = calculate_daily_rewards(community_score, years_since_launch)
/// 2. customer_pool = daily_rewards * customer_reward_share / 10000
/// 3. customer_reward = (activity_count * customer_pool) / total_customer_activity
///
/// ## Parameters
/// - `activity_count`: Number of activities performed by the customer
/// - `community_score`: Community health score (0-10000 basis points)
/// - `years_since_launch`: Number of years since project launch (for time decay)
/// - `customer_reward_share`: Customer reward percentage in basis points (0-10000)
/// - `total_customer_activity`: Total activity count across all customers
///
/// ## Returns
/// - Individual customer reward amount in smallest token units
///
/// ## Usage
/// ```rust
/// use miracle_api::sdk::calculate_customer_reward_transparent;
///
/// let reward = calculate_customer_reward_transparent(
///     5,           // activity_count
///     8000,        // community_score
///     2,           // years_since_launch
///     7000,        // customer_reward_share
///     1000,        // total_customer_activity
/// );
/// println!("Reward: {} MIRACLE", reward);
/// ```
///
/// ## Note
/// This function provides complete transparency from community metrics to individual rewards.
/// It can be used both on-chain and off-chain for verification.
pub fn calculate_customer_reward_transparent(
    activity_count: u32,
    community_score: u16,
    years_since_launch: u32,
    customer_reward_share: u16,
    total_customer_activity: u32,
) -> u64 {
    crate::consts::calculate_customer_reward_transparent(
        activity_count,
        community_score,
        years_since_launch,
        customer_reward_share,
        total_customer_activity,
    )
}

/// Complete transparent calculation for customer rewards WITH activity capping.
/// This function matches the on-chain calculation behavior exactly.
///
/// ## Formula Chain
/// 1. daily_rewards = calculate_daily_rewards(community_score, years_since_launch)
/// 2. customer_pool = daily_rewards * customer_reward_share / 10000
/// 3. capped_activity = min(activity_count, max_customer_activity_per_epoch)
/// 4. customer_reward = (capped_activity * customer_pool) / total_customer_activity
///
/// ## Parameters
/// - `activity_count`: Number of activities performed by the customer
/// - `community_score`: Community health score (0-10000 basis points)
/// - `years_since_launch`: Number of years since project launch (for time decay)
/// - `customer_reward_share`: Customer reward percentage in basis points (0-10000)
/// - `total_customer_activity`: Total activity count across all customers
/// - `max_customer_activity_per_epoch`: Maximum allowed customer activity per epoch
///
/// ## Returns
/// - Individual customer reward amount in smallest token units (with activity capping)
///
/// ## Benefits
/// - Matches on-chain calculation exactly
/// - Includes activity capping to prevent gaming
/// - Complete transparency for off-chain estimation
/// - Deterministic calculation for verification
///
/// ## Usage
/// ```rust
/// use miracle_api::sdk::calculate_customer_reward_transparent_with_cap;
///
/// let reward = calculate_customer_reward_transparent_with_cap(
///     15,          // activity_count (will be capped)
///     8000,        // community_score
///     2,           // years_since_launch
///     7000,        // customer_reward_share
///     1000,        // total_customer_activity
///     10,          // max_customer_activity_per_epoch (caps activity at 10)
/// );
/// println!("Reward: {} MIRACLE", reward);
/// ```
///
/// ## Note
/// This function provides complete transparency from community metrics to individual rewards
/// and matches the on-chain calculation behavior exactly.
pub fn calculate_customer_reward_transparent_with_cap(
    activity_count: u32,
    community_score: u16,
    years_since_launch: u32,
    customer_reward_share: u16,
    total_customer_activity: u32,
    max_customer_activity_per_epoch: u32,
) -> u64 {
    crate::consts::calculate_customer_reward_transparent_with_cap(
        activity_count,
        community_score,
        years_since_launch,
        customer_reward_share,
        total_customer_activity,
        max_customer_activity_per_epoch,
    )
}

/// Complete transparent calculation for merchant rewards.
/// This function combines all steps of the reward calculation for transparency.
///
/// ## Formula Chain
/// 1. daily_rewards = calculate_daily_rewards(community_score, years_since_launch)
/// 2. merchant_pool = daily_rewards * merchant_reward_share / 10000
/// 3. merchant_reward = (activity_count * merchant_pool) / total_merchant_activity
///
/// ## Parameters
/// - `activity_count`: Number of activities performed by the merchant
/// - `community_score`: Community health score (0-10000 basis points)
/// - `years_since_launch`: Number of years since project launch (for time decay)
/// - `merchant_reward_share`: Merchant reward percentage in basis points (0-10000)
/// - `total_merchant_activity`: Total activity count across all merchants
///
/// ## Returns
/// - Individual merchant reward amount in smallest token units
///
/// ## Usage
/// ```rust
/// use miracle_api::sdk::calculate_merchant_reward_transparent;
///
/// let reward = calculate_merchant_reward_transparent(
///     3,           // activity_count
///     8000,        // community_score
///     2,           // years_since_launch
///     3000,        // merchant_reward_share
///     500,         // total_merchant_activity
/// );
/// println!("Reward: {} MIRACLE", reward);
/// ```
///
/// ## Note
/// This function provides complete transparency from community metrics to individual rewards.
/// It can be used both on-chain and off-chain for verification.
pub fn calculate_merchant_reward_transparent(
    activity_count: u32,
    community_score: u16,
    years_since_launch: u32,
    merchant_reward_share: u16,
    total_merchant_activity: u32,
) -> u64 {
    crate::consts::calculate_merchant_reward_transparent(
        activity_count,
        community_score,
        years_since_launch,
        merchant_reward_share,
        total_merchant_activity,
    )
}

/// Complete transparent calculation for merchant rewards WITH activity capping.
/// This function matches the on-chain calculation behavior exactly.
///
/// ## Formula Chain
/// 1. daily_rewards = calculate_daily_rewards(community_score, years_since_launch)
/// 2. merchant_pool = daily_rewards * merchant_reward_share / 10000
/// 3. capped_activity = min(activity_count, max_merchant_activity_per_epoch)
/// 4. merchant_reward = (capped_activity * merchant_pool) / total_merchant_activity
///
/// ## Parameters
/// - `activity_count`: Number of activities performed by the merchant
/// - `community_score`: Community health score (0-10000 basis points)
/// - `years_since_launch`: Number of years since project launch (for time decay)
/// - `merchant_reward_share`: Merchant reward percentage in basis points (0-10000)
/// - `total_merchant_activity`: Total activity count across all merchants
/// - `max_merchant_activity_per_epoch`: Maximum allowed merchant activity per epoch
///
/// ## Returns
/// - Individual merchant reward amount in smallest token units (with activity capping)
///
/// ## Benefits
/// - Matches on-chain calculation exactly
/// - Includes activity capping to prevent gaming
/// - Complete transparency for off-chain estimation
/// - Deterministic calculation for verification
///
/// ## Usage
/// ```rust
/// use miracle_api::sdk::calculate_merchant_reward_transparent_with_cap;
///
/// let reward = calculate_merchant_reward_transparent_with_cap(
///     25,          // activity_count (will be capped)
///     8000,        // community_score
///     2,           // years_since_launch
///     3000,        // merchant_reward_share
///     500,         // total_merchant_activity
///     20,          // max_merchant_activity_per_epoch (caps activity at 20)
/// );
/// println!("Reward: {} MIRACLE", reward);
/// ```
///
/// ## Note
/// This function provides complete transparency from community metrics to individual rewards
/// and matches the on-chain calculation behavior exactly.
pub fn calculate_merchant_reward_transparent_with_cap(
    activity_count: u32,
    community_score: u16,
    years_since_launch: u32,
    merchant_reward_share: u16,
    total_merchant_activity: u32,
    max_merchant_activity_per_epoch: u32,
) -> u64 {
    crate::consts::calculate_merchant_reward_transparent_with_cap(
        activity_count,
        community_score,
        years_since_launch,
        merchant_reward_share,
        total_merchant_activity,
        max_merchant_activity_per_epoch,
    )
}

/// Convert Unix timestamp to epoch number (day sequence since launch).
///
/// ## Formula
/// epoch = (timestamp - START_AT) / EPOCH_DURATION
///
/// ## Parameters
/// - `timestamp`: Unix timestamp in seconds
///
/// ## Returns
/// - Epoch number (0-based day sequence since launch)
///
/// ## Epoch Alignment
/// - Epoch 0: Sept 1, 2025 00:00:00 UTC to Sept 1, 2025 23:59:59 UTC
/// - Epoch 1: Sept 2, 2025 00:00:00 UTC to Sept 2, 2025 23:59:59 UTC
/// - Each epoch aligns with a natural UTC date (midnight to midnight)
/// - Project launches at START_AT (10:00 AM UTC on Sept 1, 2025) within epoch 0
///
/// ## Example
/// ```rust
/// use miracle_api::sdk;
/// let epoch = sdk::timestamp_to_epoch(1756756800); // Returns 0 (Sept 1, 2025 00:00:00 UTC)
/// let epoch = sdk::timestamp_to_epoch(1756843200); // Returns 1 (Sept 2, 2025 00:00:00 UTC)
/// ```
pub fn timestamp_to_epoch(timestamp: i64) -> u64 {
    // Align epochs with natural UTC dates (midnight to midnight)
    // Formula: Find the start of the UTC day containing START_AT
    // Then calculate epochs from that day boundary
    let start_day_beginning = (START_AT / EPOCH_DURATION) * EPOCH_DURATION; // Start of UTC day containing START_AT

    if timestamp < start_day_beginning {
        return 0; // Return epoch 0 for timestamps before the start of epoch 0
    }

    let adjusted_timestamp = timestamp - start_day_beginning;
    (adjusted_timestamp / EPOCH_DURATION) as u64
}

/// Calculate Unix timestamp from epoch number (day sequence).
///
/// ## Formula
/// timestamp = START_AT + (epoch * EPOCH_DURATION)
///
/// ## Parameters
/// - `epoch`: Epoch number (0-based day sequence since launch)
///
/// ## Returns
/// - Unix timestamp in seconds (start of the epoch day)
///
/// ## Epoch Alignment
/// - Epoch 0: Returns Sept 1, 2025 00:00:00 UTC
/// - Epoch 1: Returns Sept 2, 2025 00:00:00 UTC
/// - Each epoch starts at 00:00:00 UTC of the corresponding date
/// - Project launches at START_AT (10:00 AM UTC on Sept 1, 2025) within epoch 0
///
/// ## Example
/// ```rust
/// use miracle_api::sdk;
/// let timestamp = sdk::epoch_to_timestamp(0); // Returns 1756756800 (Sept 1, 2025 00:00:00 UTC)
/// let timestamp = sdk::epoch_to_timestamp(1); // Returns 1756843200 (Sept 2, 2025 00:00:00 UTC)
/// ```
pub fn epoch_to_timestamp(epoch: u64) -> i64 {
    // Align epochs with natural UTC dates (midnight to midnight)
    // Formula: Find the start of the UTC day containing START_AT
    // Then calculate timestamp from that day boundary
    let start_day_beginning = (START_AT / EPOCH_DURATION) * EPOCH_DURATION; // Start of UTC day containing START_AT
    start_day_beginning + (epoch as i64 * EPOCH_DURATION)
}

/// Convert a date range to a list of epochs.
///
/// ## Parameters
/// - `start_date`: Start date as Unix timestamp
/// - `end_date`: End date as Unix timestamp (inclusive)
///
/// ## Returns
/// - Vector of epoch numbers from start_date to end_date (inclusive)
///
/// ## Example
/// ```rust
/// use miracle_api::sdk;
/// let epochs = sdk::date_range_to_epochs(1756792800, 1756879199);
/// // Returns [0] for Sept 1, 2025 (launch day)
/// let epochs = sdk::date_range_to_epochs(1756792800, 1756965599);
/// // Returns [0, 1] for Sept 1-2, 2025
/// ```
pub fn date_range_to_epochs(start_date: i64, end_date: i64) -> Vec<u64> {
    if start_date > end_date {
        return Vec::new(); // Return empty vector for invalid range
    }

    let start_epoch = timestamp_to_epoch(start_date);
    let end_epoch = timestamp_to_epoch(end_date);

    (start_epoch..=end_epoch).collect()
}

/// Builds a batch claim instruction for a date range.
///
/// This function converts the date range to epochs and creates a vector claim.
/// It provides a user-friendly interface for claiming rewards across multiple days.
///
/// ## Parameters
/// - `signer`: The wallet signing the transaction
/// - `beneficiary`: The wallet receiving the rewards
/// - `start_date`: Start date as Unix timestamp
/// - `end_date`: End date as Unix timestamp (inclusive)
/// - `participant_type`: 0 = customer, 1 = merchant
/// - `max_batch_size`: Maximum epochs per batch (1-10)
/// - `merkle_proofs`: Vector of Merkle proof data for each epoch
///
/// ## Returns
/// - Instruction for batch claiming rewards across the date range
///
/// ## Note
/// - The date range is converted to epochs using `date_range_to_epochs`
/// - Each epoch requires its own Merkle proof in the `merkle_proofs` vector
/// - The number of proofs must match the number of epochs in the range
/// - If the date range is invalid or too large, returns an error
///
/// ## Example
/// ```rust
/// use miracle_api::sdk;
/// use solana_program::pubkey::Pubkey;
///
/// let signer = Pubkey::new_unique();
/// let beneficiary = Pubkey::new_unique();
/// let merkle_proofs = vec![vec![1, 2, 3], vec![4, 5, 6]]; // Example proofs
///
/// let instruction = sdk::batch_claim_date_range(
///     signer,
///     beneficiary,
///     1756792800, // Sept 1, 2025 00:00:00 UTC
///     1756879199, // Sept 1, 2025 23:59:59 UTC
///     0, // customer
///     10, // max batch size
///     merkle_proofs, // proofs for epoch 0
///     None, // social_data (no social claims)
/// );
/// ```
///
/// Batch claim instruction for date range - uses correct 8-account structure
pub fn batch_claim_date_range(
    signer: Pubkey,
    beneficiary: Pubkey,
    start_date: i64,
    end_date: i64,
    participant_type: u8,
    max_batch_size: u8,
    merkle_proofs: Vec<Vec<u8>>,
    social_data: Option<Vec<Option<SocialClaimData>>>,
) -> Result<Instruction, crate::error::MiracleError> {
    // Convert date range to epochs
    let epochs = date_range_to_epochs(start_date, end_date);

    if epochs.is_empty() {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    if epochs.len() > max_batch_size as usize {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    if merkle_proofs.len() != epochs.len() {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    // Validate social_data if provided
    if let Some(ref social_data_vec) = social_data {
        if social_data_vec.len() != epochs.len() {
            return Err(crate::error::MiracleError::InvalidInput);
        }
    }

    // Create batch claim instruction using vector claim type
    let mut data = Vec::new();

    // Add instruction discriminator for MiracleInstruction::BatchClaim (value = 0)
    data.push(MiracleInstruction::BatchClaim as u8);

    // Manually serialize the BatchClaim struct fields in the exact order the program expects
    data.extend_from_slice(&[0u8; 8]); // start_epoch: 8 bytes (not used for date range)
    data.extend_from_slice(&[0u8; 8]); // end_epoch: 8 bytes (not used for date range)
    data.push(participant_type); // participant_type: 1 byte
    data.push(2u8); // claim_type: 1 byte (Date range claim = 2)
    data.push(epochs.len() as u8); // epoch_count: 1 byte
    data.push(max_batch_size); // max_batch_size: 1 byte
    data.extend_from_slice(&[0u8; 4]); // _padding: 4 bytes

    // Append epoch list
    for &epoch in &epochs {
        data.extend_from_slice(&epoch.to_le_bytes());
    }

    // Append Merkle proof data (consistent with single Claim)
    // For batch claims, we use the same merkle path and path indices for all epochs
    // since all epochs in a batch must use the same merkle root and structure
    let first_proof = &merkle_proofs[0];
    if first_proof.len() >= 37 {
        // Skip the first 33 bytes (merkle_root + merkle_path_length) and append the rest
        // This gives us: merkle_path + path_indices + activity_count
        data.extend_from_slice(&first_proof[33..]);
    } else {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    // Append social flags (1 byte per epoch indicating if social claim exists)
    let social_flags = social_data
        .as_ref()
        .map(|social_vec| {
            social_vec
                .iter()
                .map(|opt| if opt.is_some() { 1u8 } else { 0u8 })
                .collect::<Vec<u8>>()
        })
        .unwrap_or_else(|| vec![0u8; epochs.len()]);

    data.extend_from_slice(&social_flags);

    // Append social data for epochs that have social claims
    if let Some(social_data_vec) = social_data {
        for social_opt in social_data_vec {
            if let Some(social) = social_opt {
                // Serialize SocialClaimData using bytemuck::bytes_of for consistent formatting
                data.extend_from_slice(bytemuck::bytes_of(&social));
            }
        }
    }

    // Create instruction with correct account structure matching program
    let proof_pda = proof_pda(signer);
    Ok(Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),                     // [0] signer
            AccountMeta::new(beneficiary, false),               // [1] beneficiary
            AccountMeta::new(proof_pda.0, false),               // [2] proof PDA
            AccountMeta::new(TREASURY_ADDRESS, false),          // [3] treasury
            AccountMeta::new(TREASURY_TOKENS_ADDRESS, false),   // [4] treasury tokens
            AccountMeta::new_readonly(spl_token::ID, false),    // [5] token program
            AccountMeta::new_readonly(SNAPSHOT_ADDRESS, false), // [6] snapshot
            AccountMeta::new_readonly(CONFIG_ADDRESS, false),   // [7] config
        ],
        data,
    })
}

/// Builds a batch claim instruction for a vector of epochs.
///
/// This is the underlying function used by `batch_claim_date_range`.
/// Uses correct 8-account structure matching program.
/// It allows claiming rewards for specific epochs in a single transaction.
/// Supports both payment rewards and optional social rewards per epoch.
///
/// ## Parameters
/// - `signer`: The wallet signing the transaction
/// - `beneficiary`: The wallet receiving the rewards
/// - `epochs`: Vector of epoch numbers to claim
/// - `participant_type`: 0 for customer, 1 for merchant
/// - `max_batch_size`: Maximum epochs per batch (1-10)
/// - `epoch_proofs`: Vector of proof data for each epoch
/// - `social_data`: Optional vector of social data for each epoch (None = no social claim)
///
/// ## Returns
/// - Instruction for batch claiming rewards for specific epochs
///
/// ## Note
/// - Each epoch requires its own proof data
/// - The number of proofs must match the number of epochs
/// - Social data is optional per epoch (None = payment only, Some = payment + social)
/// - Epochs must be in ascending order for optimal gas efficiency
///
/// ## Data Structure
/// Each epoch proof contains:
/// - `DailyParticipantData`: Participant-specific information
/// - `Vec<[u8; 32]>`: Payment proof path
/// - `Vec<bool>`: Payment proof indices
/// - `Vec<[u8; 32]>`: Seal proof path
/// - `Vec<bool>`: Seal proof indices
/// - `[u8; 32]`: Payment root
/// - `EpochClaimData`: Epoch-specific reward and activity data
/// - `DailyParticipantData`: Participant data for each epoch
pub fn batch_claim_vector(
    signer: Pubkey,
    beneficiary: Pubkey,
    epochs: Vec<u64>,
    participant_type: u8,
    max_batch_size: u8,
    epoch_proofs: Vec<(
        Vec<[u8; 32]>, // payment_proof
        Vec<bool>,     // payment_indices
        Vec<[u8; 32]>, // seal_proof
        Vec<bool>,     // seal_indices
        [u8; 32],      // payment_root
        EpochClaimData,
        DailyParticipantData, // participant data for each epoch
    )>,
    social_data: Option<Vec<Option<SocialClaimData>>>,
) -> Result<Instruction, crate::error::MiracleError> {
    if epochs.is_empty() {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    if epochs.len() > max_batch_size as usize {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    if epoch_proofs.len() != epochs.len() {
        return Err(crate::error::MiracleError::InvalidInput);
    }

    // Validate social_data if provided
    if let Some(ref social_data_vec) = social_data {
        if social_data_vec.len() != epochs.len() {
            return Err(crate::error::MiracleError::InvalidInput);
        }
    }

    // Create batch claim instruction
    let mut data = Vec::new();

    // Use the BatchClaim struct's proper serialization like single claim does
    let batch_claim_data = BatchClaim {
        start_epoch: [0u8; 8], // Not used for vector claims
        end_epoch: [0u8; 8],   // Not used for vector claims
        participant_type,
        claim_type: 1u8, // Vector claim = 1
        epoch_count: epochs.len() as u8,
        max_batch_size,
        _padding: [0u8; 4],
    };
    data.extend_from_slice(&batch_claim_data.to_bytes());

    // Add epoch list with proper endianness like single claim
    for &epoch in &epochs {
        data.extend_from_slice(&epoch.to_le_bytes());
    }

    // Add proof data for each epoch
    for epoch_proof in &epoch_proofs {
        let (
            payment_proof,
            payment_indices,
            seal_proof,
            seal_indices,
            payment_root,
            epoch_data,
            participant_data,
        ) = epoch_proof;

        // Add payment proof length
        data.push(payment_proof.len() as u8);

        // Add payment proof path
        for path_node in payment_proof {
            data.extend_from_slice(path_node);
        }

        // Add payment indices
        for &is_right in payment_indices {
            data.push(if is_right { 1u8 } else { 0u8 });
        }

        // Add seal proof length
        data.push(seal_proof.len() as u8);

        // Add seal proof path
        for path_node in seal_proof {
            data.extend_from_slice(path_node);
        }

        // Add seal indices
        for &is_right in seal_indices {
            data.push(if is_right { 1u8 } else { 0u8 });
        }

        // Add payment root
        data.extend_from_slice(payment_root);

        // Add epoch data
        data.extend_from_slice(bytemuck::bytes_of(epoch_data));

        // Add participant data for this epoch
        data.extend_from_slice(bytemuck::bytes_of(participant_data));
    }

    // Add social flags (1 byte per epoch indicating if social claim exists)
    let social_flags = social_data
        .as_ref()
        .map(|social_vec| {
            social_vec
                .iter()
                .map(|opt| if opt.is_some() { 1u8 } else { 0u8 })
                .collect::<Vec<u8>>()
        })
        .unwrap_or_else(|| vec![0u8; epochs.len()]);

    data.extend_from_slice(&social_flags);

    // Add social data for epochs that have social claims
    if let Some(social_data_vec) = social_data {
        for social_opt in social_data_vec {
            if let Some(social) = social_opt {
                data.extend_from_slice(bytemuck::bytes_of(&social));
            }
        }
    }

    // Create instruction with correct account structure
    let proof_pda = proof_pda(signer);
    Ok(Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),                     // [0] signer
            AccountMeta::new(beneficiary, false),               // [1] beneficiary
            AccountMeta::new(proof_pda.0, false),               // [2] proof PDA
            AccountMeta::new(TREASURY_ADDRESS, false),          // [3] treasury
            AccountMeta::new(TREASURY_TOKENS_ADDRESS, false),   // [4] treasury tokens
            AccountMeta::new_readonly(spl_token::ID, false),    // [5] token program
            AccountMeta::new_readonly(SNAPSHOT_ADDRESS, false), // [6] snapshot
            AccountMeta::new_readonly(CONFIG_ADDRESS, false),   // [7] config
        ],
        data,
    })
}

/// Build an UpdateTargets instruction to update community targets and activity limits.
/// This function allows the oracle to update configurable parameters based on community performance.
///
/// ## Parameters
/// - `oracle_authority`: The oracle authority that can update these parameters
/// - `target_weekly_users`: Target weekly active users (default: 500 for launch)
/// - `target_weekly_activity`: Target weekly activity count (default: 5,000 for launch)
/// - `target_retention_rate`: Target retention rate in basis points (default: 5,000 = 50%)
/// - `max_customer_activity_per_epoch`: Max customer activities per epoch (default: 5)
/// - `max_merchant_activity_per_epoch`: Max merchant activities per epoch (default: 50)
/// - `activity_cap_enabled`: Whether activity capping is enabled (default: 1 = enabled)
/// - `claim_cap_enabled`: Whether claim capping is enabled (default: 1 = enabled)
///
/// ## Returns
/// - Instruction to update community targets and activity limits
///
/// ## Authority
/// - Only the oracle authority can execute this instruction
/// - Oracle has the data to make informed decisions about community health
///
/// ## Benefits
/// - **Operational Flexibility**: Adjust parameters based on real community performance
/// - **Anti-Gaming**: Update activity limits to prevent new gaming strategies
/// - **Community Adaptation**: Adjust targets as community grows and evolves
/// - **Economic Balance**: Fine-tune parameters for sustainable tokenomics
/// - **Risk Management**: Adjust claim rewards threshold based on market conditions
///
/// ## Example
/// ```rust
/// use miracle_api::sdk;
/// use solana_program::pubkey::Pubkey;
///
/// let oracle_authority = Pubkey::new_unique();
/// let update_targets_ix = sdk::update_targets(
///     oracle_authority,
///     1000,   // target_weekly_users
///     10000,  // target_weekly_activity
///     6000,   // target_retention_rate (60%)
///     10,     // max_customer_activity_per_epoch
///     100,    // max_merchant_activity_per_epoch
///     1,      // activity_cap_enabled
///     1,      // claim_cap_enabled
///     1000000, // claim_rewards_threshold
/// );
/// ```
pub fn update_targets(
    oracle_authority: Pubkey,
    target_weekly_users: u32,
    target_weekly_activity: u32,
    target_retention_rate: u16,
    max_customer_activity_per_epoch: u32,
    max_merchant_activity_per_epoch: u32,
    activity_cap_enabled: u8,
    claim_cap_enabled: u8,
    claim_rewards_threshold: u64,
) -> Instruction {
    let data = UpdateTargets {
        target_weekly_users: target_weekly_users.to_le_bytes(),
        target_weekly_activity: target_weekly_activity.to_le_bytes(),
        target_retention_rate: target_retention_rate.to_le_bytes(),
        max_customer_activity_per_epoch: max_customer_activity_per_epoch.to_le_bytes(),
        max_merchant_activity_per_epoch: max_merchant_activity_per_epoch.to_le_bytes(),
        activity_cap_enabled,
        claim_cap_enabled,
        claim_rewards_threshold: claim_rewards_threshold.to_le_bytes(),
        _padding: [0; 4],
    }
    .to_bytes();

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(oracle_authority, true),
            AccountMeta::new(CONFIG_ADDRESS, false),
        ],
        data,
    }
}

// ===== MERKLE TREE CREATION MODULE =====

/// Merkle tree creation result containing the root and proof generation capabilities.
///
/// This structure provides everything needed for off-chain processors to:
/// 1. Generate the merkle root for snapshot updates
/// 2. Generate merkle proofs for individual claims
/// 3. Verify merkle proofs for validation
///
/// ## Security
/// - **Deterministic**: Same input data always produces the same merkle root
/// - **Cryptographic**: Uses Solana hashv for collision resistance
/// - **Efficient**: O(n) construction time, O(log n) proof generation
/// - **Verifiable**: All proofs can be verified on-chain
#[repr(C)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MerkleTree {
    /// The merkle root hash (32 bytes) - used for snapshot updates
    pub root: [u8; 32],
    /// Internal tree structure for proof generation
    tree: Vec<Vec<[u8; 32]>>,
    /// Original participant data for proof generation
    participants: Vec<DailyParticipantData>,
}

impl MerkleTree {
    /// Create a new merkle tree from participant data.
    ///
    /// ## Parameters
    /// - `participants`: Vector of daily participant data
    ///
    /// ## Returns
    /// - `MerkleTree` instance with root and proof generation capabilities
    ///
    /// ## Panics
    /// - If participants vector is empty
    ///
    /// ## Example
    /// ```rust
    /// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree}};
    ///
    /// let participants = vec![
    ///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
    ///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
    /// ];
    ///
    /// let merkle_tree = MerkleTree::new(participants);
    /// println!("Merkle root: {:?}", merkle_tree.root());
    /// ```
    pub fn new(mut participants: Vec<DailyParticipantData>) -> Self {
        if participants.is_empty() {
            panic!("Cannot create merkle tree from empty participants list");
        }

        // Validate all participants
        for participant in &participants {
            participant.validate().expect("Invalid participant data");
        }

        // Sort participants deterministically by participant_id for consistent merkle tree construction
        // This ensures that the same participants always produce the same merkle root regardless of input order
        sort_participants_by_id(&mut participants);

        // Generate leaf hashes from sorted participants
        let mut leaves: Vec<[u8; 32]> =
            participants.iter().map(|p| p.compute_leaf_hash()).collect();

        // CRITICAL: Handle single leaf case - duplicate the leaf to force one hash operation
        // This matches Oracle's logic exactly for consistency
        if leaves.len() == 1 {
            leaves.push(leaves[0]); // Duplicate the single leaf
        }

        // Build merkle tree bottom-up
        let mut tree = vec![leaves.clone()];

        while leaves.len() > 1 {
            let mut new_level = Vec::new();
            for chunk in leaves.chunks(2) {
                if chunk.len() == 2 {
                    let combined = hashv(&[&chunk[0], &chunk[1]]).to_bytes();
                    new_level.push(combined);
                } else {
                    // Single element case - hash with itself for consistency
                    let combined = hashv(&[&chunk[0], &chunk[0]]).to_bytes();
                    new_level.push(combined);
                }
            }
            leaves = new_level;
            tree.push(leaves.clone());
        }

        println!("🔍 Debug: Built tree with {} levels", tree.len());
        for (i, level) in tree.iter().enumerate() {
            println!("🔍 Debug: Level {} has {} nodes", i, level.len());
        }

        let root = tree.last().unwrap()[0];
        println!("🔍 Debug: Root from tree: {:?}", root);
        println!("🔍 Debug: Root from leaves: {:?}", leaves[0]);

        Self {
            root,
            tree,
            participants,
        }
    }

    /// Get the merkle root hash.
    ///
    /// ## Returns
    /// - 32-byte merkle root hash for snapshot updates
    pub fn root(&self) -> [u8; 32] {
        self.root
    }

    /// Generate a merkle proof for a specific participant.
    ///
    /// ## Parameters
    /// - `participant_index`: Index of the participant in the original data
    ///
    /// ## Returns
    /// - `MerkleProof` containing path and indices for verification
    ///
    /// ## Panics
    /// - If participant_index is out of bounds
    ///
    /// ## Example
    /// ```rust
    /// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree, EpochClaimData}};
    /// use solana_program::pubkey::Pubkey;
    ///
    /// let participants = vec![
    ///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
    ///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
    /// ];
    ///
    /// let merkle_tree = MerkleTree::new(participants);
    /// let payment_proof = merkle_tree.generate_proof(0);
    /// let seal_proof = sdk::SealProof::new_for_verification(vec![[2u8; 32]], vec![true], merkle_tree.root());
    ///
    /// // Use proof for claim instruction using dual merkle tree
    /// let customer_wallet = Pubkey::new_unique();
    /// let beneficiary = Pubkey::new_unique();
    /// let epoch = 0u64;
    /// let participant_type = 0u8;
    /// let claim_ix = sdk::claim(
    ///     customer_wallet,
    ///     beneficiary,
    ///     epoch,
    ///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
    ///     payment_proof.path,
    ///     payment_proof.indices,
    ///     seal_proof.path,
    ///     seal_proof.indices,
    ///     seal_proof.payment_root,
    ///     EpochClaimData {
    ///         customer_reward_pool: 1000000u64.to_le_bytes(),
    ///         merchant_reward_pool: 500000u64.to_le_bytes(),
    ///         total_customer_activity: 0u64.to_le_bytes(),
    ///         total_merchant_activity: 0u64.to_le_bytes(),
    ///     },
    ///     participant_type,
    ///     None, // social_data (no social claim)
    /// );
    /// ```
    pub fn generate_proof(&self, participant_index: usize) -> MerkleProof {
        if participant_index >= self.participants.len() {
            panic!("Participant index out of bounds");
        }

        let mut path = Vec::new();
        let mut indices = Vec::new();
        let mut current_index = participant_index;

        println!(
            "🔍 Debug: Generating proof for participant index {}",
            participant_index
        );
        println!("🔍 Debug: Tree has {} levels", self.tree.len());

        // Traverse up the tree to build the proof
        for level in 0..self.tree.len() - 1 {
            let level_size = self.tree[level].len();
            println!(
                "🔍 Debug: Level {} has {} nodes, current_index = {}",
                level, level_size, current_index
            );

            if current_index % 2 == 0 {
                // Left child - need right sibling
                if current_index + 1 < level_size {
                    let sibling = self.tree[level][current_index + 1];
                    path.push(sibling);
                    indices.push(true); // true = sibling is on the right
                    println!(
                        "🔍 Debug: Level {}: Left child, adding right sibling {:?}",
                        level, sibling
                    );
                }
            } else {
                // Right child - need left sibling
                let sibling = self.tree[level][current_index - 1];
                path.push(sibling);
                indices.push(false); // false = sibling is on the left
                println!(
                    "🔍 Debug: Level {}: Right child, adding left sibling {:?}",
                    level, sibling
                );
            }

            current_index /= 2;
        }

        println!(
            "🔍 Debug: Generated proof with {} path nodes and indices {:?}",
            path.len(),
            indices
        );
        MerkleProof { path, indices }
    }

    /// Find participant by ID and generate proof.
    ///
    /// ## Parameters
    /// - `participant_id`: The participant ID to find
    ///
    /// ## Returns
    /// - `Some(MerkleProof)` if participant found
    /// - `None` if participant not found
    ///
    /// ## Example
    /// ```rust
    /// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree}};
    ///
    /// let participants = vec![
    ///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
    ///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
    /// ];
    ///
    /// let merkle_tree = MerkleTree::new(participants);
    ///
    /// if let Some(payment_proof) = merkle_tree.find_and_generate_proof([1u8; 32]) {
    ///     // Use payment proof for dual merkle tree claim
    /// }
    /// ```
    pub fn find_and_generate_proof(&self, participant_id: [u8; 32]) -> Option<MerkleProof> {
        self.participants
            .iter()
            .position(|p| p.participant_id == participant_id)
            .map(|index| self.generate_proof(index))
    }

    /// Get the number of participants in the tree.
    ///
    /// ## Returns
    /// - Number of participants
    pub fn participant_count(&self) -> usize {
        self.participants.len()
    }

    /// Get participant data by index.
    ///
    /// ## Parameters
    /// - `index`: Participant index
    ///
    /// ## Returns
    /// - `Some(&DailyParticipantData)` if index is valid
    /// - `None` if index is out of bounds
    pub fn get_participant(&self, index: usize) -> Option<&DailyParticipantData> {
        self.participants.get(index)
    }

    /// Get all participant data.
    ///
    /// ## Returns
    /// - Reference to all participant data
    pub fn participants(&self) -> &[DailyParticipantData] {
        &self.participants
    }
}

/// Merkle proof for a specific participant.
///
/// This structure contains the path and direction indices needed to verify
/// that a participant's data is included in the merkle tree.
///
/// ## Security
/// - **Cryptographic**: Uses Solana hashv for collision resistance
/// - **Deterministic**: Same participant always generates same proof
/// - **Verifiable**: Can be verified on-chain against merkle root
#[repr(C)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MerkleProof {
    /// Merkle path nodes (sibling hashes)
    pub path: Vec<[u8; 32]>,
    /// Direction indices (false = left, true = right)
    pub indices: Vec<bool>,
}

/// Seal proof structure for dual merkle tree verification.
/// Contains both the merkle proof path and the payment root being proven.
/// Enhanced with epoch-specific data for accurate historical reward calculations.
#[repr(C)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SealProof {
    /// Seal merkle path nodes (sibling hashes)
    pub path: Vec<[u8; 32]>,
    /// Seal direction indices (false = left, true = right)
    pub indices: Vec<bool>,
    /// Payment root being proven (embedded in seal proof)
    pub payment_root: [u8; 32],
    /// Epoch-specific reward calculation data for accurate historical calculations
    pub customer_reward_pool: u64,
    pub merchant_reward_pool: u64,
    pub total_customer_activity: u64,
    pub total_merchant_activity: u64,
    pub community_score: u16,
    pub customer_reward_share: u16,
    pub merchant_reward_share: u16,
    pub weekly_active_users: u32,
    pub weekly_retention_rate: u16,
    pub weekly_activity_count: u32,
}

impl MerkleProof {
    /// Create a new merkle proof.
    ///
    /// ## Parameters
    /// - `path`: Vector of merkle path nodes
    /// - `indices`: Vector of direction indices
    ///
    /// ## Returns
    /// - New MerkleProof instance
    pub fn new(path: Vec<[u8; 32]>, indices: Vec<bool>) -> Self {
        Self { path, indices }
    }

    /// Verify this proof against a merkle root and participant data.
    ///
    /// ## Parameters
    /// - `participant`: The participant data to verify
    /// - `merkle_root`: The expected merkle root
    ///
    /// ## Returns
    /// - `true` if proof is valid
    /// - `false` if proof is invalid
    ///
    /// ## Example
    /// ```rust
    /// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree}};
    ///
    /// let participant = DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0);
    /// let participants = vec![participant.clone()];
    /// let merkle_tree = MerkleTree::new(participants);
    /// let proof = merkle_tree.generate_proof(0);
    ///
    /// assert!(proof.verify(&participant, merkle_tree.root()));
    /// ```
    pub fn verify(&self, participant: &DailyParticipantData, merkle_root: [u8; 32]) -> bool {
        if self.path.len() != self.indices.len() {
            return false;
        }

        let mut current_hash = participant.compute_leaf_hash();
        println!(
            "🔍 Debug: Starting verification with leaf hash: {:?}",
            current_hash
        );

        // Traverse the proof path
        for (i, &path_node) in self.path.iter().enumerate() {
            let is_right = self.indices[i];
            println!(
                "🔍 Debug: Step {}: is_right={}, path_node={:?}",
                i, is_right, path_node
            );

            if is_right {
                // When is_right is true, the sibling is on the right
                // So current_hash should be on the left, path_node on the right
                // Use hashv(&[&left, &right]) to match tree construction
                current_hash = hashv(&[&current_hash, &path_node]).to_bytes();
            } else {
                // When is_right is false, the sibling is on the left
                // So path_node should be on the left, current_hash on the right
                // Use hashv(&[&left, &right]) to match tree construction
                current_hash = hashv(&[&path_node, &current_hash]).to_bytes();
            }
            println!("🔍 Debug: Step {}: current hash = {:?}", i, current_hash);
        }

        println!(
            "🔍 Debug: Final hash: {:?}, Expected root: {:?}",
            current_hash, merkle_root
        );
        current_hash == merkle_root
    }

    /// Get the proof length (number of path nodes).
    ///
    /// ## Returns
    /// - Number of nodes in the proof path
    pub fn length(&self) -> usize {
        self.path.len()
    }

    /// Check if this is an empty proof (single leaf tree).
    ///
    /// ## Returns
    /// - `true` if proof is empty
    /// - `false` if proof has path nodes
    pub fn is_empty(&self) -> bool {
        self.path.is_empty()
    }

    /// Serialize the MerkleProof to bytes (for use in transactions, batch claims, etc.)
    pub fn serialize(&self) -> Vec<u8> {
        bincode::serialize(self).expect("MerkleProof serialization failed")
    }

    /// Deserialize a MerkleProof from bytes.
    pub fn deserialize(data: &[u8]) -> Self {
        bincode::deserialize(data).expect("MerkleProof deserialization failed")
    }
}

/// Create a merkle tree from participant data.
///
/// This is a convenience function that creates a merkle tree from a vector
/// of participant data. It's the primary entry point for off-chain processors.
///
/// ## Parameters
/// - `participants`: Vector of daily participant data
///
/// ## Returns
/// - `MerkleTree` instance with root and proof generation capabilities
///
/// ## Panics
/// - If participants vector is empty
///
/// ## Example
/// ```rust
/// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree}};
///
/// // Off-chain processor aggregates daily payments
/// let participants = vec![
///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
/// ];
///
/// // Create merkle tree
/// let merkle_tree = sdk::create_merkle_tree(participants);
/// println!("Merkle root: {:?}", merkle_tree.root());
/// ```
pub fn create_merkle_tree(participants: Vec<DailyParticipantData>) -> MerkleTree {
    MerkleTree::new(participants)
}

/// Verify a merkle proof against a merkle root and participant data.
///
/// This is a convenience function for proof verification that can be used
/// both off-chain (for testing) and on-chain (in claim instructions).
///
/// ## Parameters
/// - `participant`: The participant data to verify
/// - `proof`: The merkle proof
/// - `merkle_root`: The expected merkle root
///
/// ## Returns
/// - `true` if proof is valid
/// - `false` if proof is invalid
///
/// ## Example
/// ```rust
/// use miracle_api::{sdk, prelude::DailyParticipantData};
///
/// let participant = DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0);
/// let participants = vec![participant.clone()];
/// let merkle_tree = sdk::create_merkle_tree(participants);
/// let proof = merkle_tree.generate_proof(0);
///
/// assert!(sdk::verify_merkle_proof(&participant, &proof, merkle_tree.root()));
/// ```
pub fn verify_merkle_proof(
    participant: &DailyParticipantData,
    proof: &MerkleProof,
    merkle_root: [u8; 32],
) -> bool {
    proof.verify(participant, merkle_root)
}

/// Find the index of a participant in the participant list.
///
/// This helper function allows users to find their index in the Merkle tree
/// without needing to know the internal ordering. This is useful for:
/// - Generating proofs for claims
/// - Verifying participant inclusion
/// - Building user-friendly interfaces
///
/// ## Parameters
/// - `participants`: Vector of daily participant data
/// - `participant_id`: The participant ID to find
///
/// ## Returns
/// - `Some(index)` if participant found
/// - `None` if participant not found
///
/// ## Example
/// ```rust
/// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree, EpochClaimData}};
/// use solana_program::pubkey::Pubkey;
///
/// let participants = vec![
///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
/// ];
///
/// let my_id = [1u8; 32];
/// if let Some(my_index) = sdk::find_participant_index(&participants, my_id) {
///     println!("My index in the Merkle tree: {}", my_index);
///     
///     // Generate proof using the index
///     let merkle_tree = sdk::create_merkle_tree(participants);
///     let proof = merkle_tree.generate_proof(my_index);
///     
///     // Use proof for claim
///     let customer_wallet = Pubkey::new_unique();
///     let beneficiary = Pubkey::new_unique();
///     let epoch = 0u64;
///     let activity_count = 5u32;
///     let participant_type = 0u8;
///     let payment_proof = merkle_tree.generate_proof(my_index);
///     let seal_proof = sdk::SealProof::new_for_verification(vec![[2u8; 32]], vec![true], merkle_tree.root());
///     let claim_ix = sdk::claim(
///         customer_wallet,
///         beneficiary,
///         epoch,
///         DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///         payment_proof.path,
///         payment_proof.indices,
///         seal_proof.path,
///         seal_proof.indices,
///         seal_proof.payment_root,
///         EpochClaimData {
///             customer_reward_pool: 1000000u64.to_le_bytes(),
///             merchant_reward_pool: 500000u64.to_le_bytes(),
///             total_customer_activity: 0u64.to_le_bytes(),
///             total_merchant_activity: 0u64.to_le_bytes(),
///         },
///         participant_type,
///         None, // social_data (no social claim)
///     );
/// }
/// ```
///
/// ## Alternative Approaches
/// Instead of finding the index, you can also use:
/// ```rust
/// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree}};
///
/// let participants = vec![
///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
/// ];
///
/// let my_id = [1u8; 32];
/// // Direct proof generation by participant ID
/// let merkle_tree = sdk::create_merkle_tree(participants);
/// if let Some(proof) = merkle_tree.find_and_generate_proof(my_id) {
///     // Use proof directly
/// }
/// ```
pub fn find_participant_index(
    participants: &[DailyParticipantData],
    participant_id: [u8; 32],
) -> Option<usize> {
    participants
        .iter()
        .position(|p| p.participant_id == participant_id)
}

/// Helper to sort participants deterministically by participant_id (lexicographically).
/// This is recommended for trustless Merkle tree construction.
pub fn sort_participants_by_id(participants: &mut [DailyParticipantData]) {
    participants.sort_by(|a, b| a.participant_id.cmp(&b.participant_id));
}

/// Convert wallet address to participant ID (32-byte hash).
///
/// This function creates a deterministic participant ID from a wallet address
/// by hashing the address bytes. This ensures consistent participant identification
/// across different systems while maintaining privacy.
///
/// ## Parameters
/// - `wallet_address`: Base58 encoded Solana wallet address
///
/// ## Returns
/// - 32-byte participant ID hash
///
/// ## Example
/// ```rust
/// use miracle_api::sdk;
///
/// let wallet = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
/// let participant_id = sdk::wallet_to_participant_id(wallet);
/// println!("Participant ID: {:?}", participant_id);
/// ```
///
/// ## Note
/// - Uses Solana's hashv function for deterministic results
/// - Same wallet address always produces same participant ID
/// - 32-byte output matches DailyParticipantData::participant_id type
/// - Matches on-chain participant ID computation exactly
pub fn wallet_to_participant_id(wallet_address: &str) -> [u8; 32] {
    use solana_program::pubkey::Pubkey;
    use std::str::FromStr;

    // Parse wallet address to Pubkey first, then hash the bytes (same as on-chain)
    match Pubkey::from_str(wallet_address) {
        Ok(pubkey) => {
            let wallet_bytes = pubkey.to_bytes();
            hashv(&[&wallet_bytes]).to_bytes()
        }
        Err(_) => {
            // Fallback to hash of string bytes if Pubkey parsing fails
            hashv(&[wallet_address.as_bytes()]).to_bytes()
        }
    }
}

/// Find participant by wallet address in a participant list.
///
/// This function converts the wallet address to a participant ID and then
/// searches for it in the participant list. Useful for user-friendly lookups
/// when you have the wallet address but need to find the participant data.
///
/// ## Parameters
/// - `participants`: Vector of daily participant data
/// - `wallet_address`: Base58 encoded Solana wallet address
///
/// ## Returns
/// - `Some(index)` if participant found
/// - `None` if participant not found
///
/// ## Example
/// ```rust
/// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree, EpochClaimData}};
/// use solana_program::pubkey::Pubkey;
///
/// let participants = vec![
///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
/// ];
///
/// let wallet = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
/// if let Some(index) = sdk::find_participant_by_wallet(&participants, wallet) {
///     println!("Found participant at index: {}", index);
///     
///     // Generate proof using the index
///     let merkle_tree = sdk::create_merkle_tree(participants);
///     let proof = merkle_tree.generate_proof(index);
///     
///     // Use proof for claim
///     let customer_wallet = Pubkey::new_unique();
///     let beneficiary = Pubkey::new_unique();
///     let epoch = 0u64;
///     let activity_count = 5u32;
///     let participant_type = 0u8;
///     let payment_proof = merkle_tree.generate_proof(index);
///     let seal_proof = sdk::SealProof::new_for_verification(vec![[2u8; 32]], vec![true], merkle_tree.root());
///     let claim_ix = sdk::claim(
///         customer_wallet,
///         beneficiary,
///         epoch,
///         DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///         payment_proof.path,
///         payment_proof.indices,
///         seal_proof.path,
///         seal_proof.indices,
///         seal_proof.payment_root,
///         EpochClaimData {
///             customer_reward_pool: 1000000u64.to_le_bytes(),
///             merchant_reward_pool: 500000u64.to_le_bytes(),
///             total_customer_activity: 0u64.to_le_bytes(),
///             total_merchant_activity: 0u64.to_le_bytes(),
///         },
///         participant_type,
///         None, // social_data (no social claim)
///     );
/// }
/// ```
pub fn find_participant_by_wallet(
    participants: &[DailyParticipantData],
    wallet_address: &str,
) -> Option<usize> {
    let participant_id = wallet_to_participant_id(wallet_address);
    participants
        .iter()
        .position(|p| p.participant_id == participant_id)
}

/// Create DailyParticipantData from wallet address and payment information.
///
/// This convenience function creates a DailyParticipantData instance from
/// a wallet address, automatically converting it to the required participant ID.
/// Useful for off-chain processors when aggregating payment data.
///
/// ## Parameters
/// - `wallet_address`: Base58 encoded Solana wallet address
/// - `first_payment_timestamp`: Unix timestamp of first payment
/// - `last_payment_timestamp`: Unix timestamp of last payment
/// - `first_payment_tx_sig_short`: First payment transaction signature (short)
/// - `last_payment_tx_sig_short`: Last payment transaction signature (short)
/// - `payment_count`: Number of transactions for this participant
/// - `participant_type`: 0 for customer, 1 for merchant
///
/// ## Returns
/// - New DailyParticipantData instance
///
/// ## Example
/// ```rust
/// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree}};
///
/// // Off-chain processor aggregating daily payments
/// let customer_wallet = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
/// let customer_data = sdk::create_participant_from_wallet(
///     customer_wallet,
///     1723680000,     // first payment timestamp
///     1723766400,     // last payment timestamp
///     [1u8; 8],       // first payment tx sig short
///     [2u8; 8],       // last payment tx sig short
///     5,              // 5 transactions
///     0,              // customer type
/// );
///
/// let merchant_wallet = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU";
/// let merchant_data = sdk::create_participant_from_wallet(
///     merchant_wallet,
///     1723680000,     // first payment timestamp
///     1723766400,     // last payment timestamp
///     [3u8; 8],       // first payment tx sig short
///     [4u8; 8],       // last payment tx sig short
///     10,             // 10 transactions
///     1,              // merchant type
/// );
///
/// // Create merkle tree from aggregated data
/// let participants = vec![customer_data, merchant_data];
/// let merkle_tree = sdk::create_merkle_tree(participants);
/// println!("Merkle root: {:?}", merkle_tree.root());
/// ```
pub fn create_participant_from_wallet(
    wallet_address: &str,
    first_payment_timestamp: i64,
    last_payment_timestamp: i64,
    first_payment_tx_sig_short: [u8; 8],
    last_payment_tx_sig_short: [u8; 8],
    payment_count: u32,
    participant_type: u8,
) -> DailyParticipantData {
    DailyParticipantData::new(
        wallet_to_participant_id(wallet_address),
        first_payment_timestamp,
        last_payment_timestamp,
        first_payment_tx_sig_short,
        last_payment_tx_sig_short,
        payment_count,
        participant_type,
    )
}

/// Generate merkle proof for a wallet address.
///
/// This convenience function combines wallet address lookup and proof generation.
/// It finds the participant by wallet address and generates their merkle proof
/// in one step. Useful for user-facing applications where you have the wallet
/// address but need the proof for claiming.
///
/// ## Parameters
/// - `participants`: Vector of daily participant data
/// - `wallet_address`: Base58 encoded Solana wallet address
///
/// ## Returns
/// - `Some(MerkleProof)` if participant found
/// - `None` if participant not found
///
/// ## Example
/// ```rust
/// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleTree, EpochClaimData}};
/// use solana_program::pubkey::Pubkey;
///
/// let participants = vec![
///     DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///     DailyParticipantData::new([2u8; 32], 1723680000, 1723766400, [3u8; 8], [4u8; 8], 10, 1),
/// ];
///
/// let wallet = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
/// if let Some(proof) = sdk::generate_proof_for_wallet(&participants, wallet) {
///     println!("Generated proof with {} path nodes", proof.length());
///     
///     // Use proof for claim
///     let merkle_tree = sdk::create_merkle_tree(participants);
///     let customer_wallet = Pubkey::new_unique();
///     let beneficiary = Pubkey::new_unique();
///     let epoch = 0u64;
///     let activity_count = 5u32;
///     let participant_type = 0u8;
///     let payment_proof = proof;
///     let seal_proof = sdk::SealProof::new_for_verification(vec![[2u8; 32]], vec![true], merkle_tree.root());
///     let claim_ix = sdk::claim(
///         customer_wallet,
///         beneficiary,
///         epoch,
///         DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0),
///         payment_proof.path,
///         payment_proof.indices,
///         seal_proof.path,
///         seal_proof.indices,
///         seal_proof.payment_root,
///         EpochClaimData {
///             customer_reward_pool: 1000000u64.to_le_bytes(),
///             merchant_reward_pool: 500000u64.to_le_bytes(),
///             total_customer_activity: 0u64.to_le_bytes(),
///             total_merchant_activity: 0u64.to_le_bytes(),
///         },
///         participant_type,
///         None, // social_data (no social claim)
///     );
/// }
/// ```
pub fn generate_proof_for_wallet(
    participants: &[DailyParticipantData],
    wallet_address: &str,
) -> Option<MerkleProof> {
    let merkle_tree = create_merkle_tree(participants.to_vec());
    merkle_tree.find_and_generate_proof(wallet_to_participant_id(wallet_address))
}

// ===== CLAIMS TRACKING MODULE =====

/// Generate a unique claim key for tracking claims.
///
/// The claim key is a hash of participant ID, epoch, participant type, and claim type.
/// This ensures each claim is uniquely identifiable and prevents double-spending.
///
/// ## Parameters
/// - `participant_id`: 32-byte participant ID (wallet hash)
/// - `epoch`: Epoch number
/// - `participant_type`: 0 = customer, 1 = merchant
/// - `claim_type`: 1 = payment only, 3 = payment + social
///
/// ## Returns
/// - 32-byte claim key hash
///
/// ## Security
/// - **Unique**: Each (participant, epoch, type) combination has unique key
/// - **Collision Resistant**: Uses SHA-256 for cryptographic security
/// - **Deterministic**: Same inputs always produce same key
pub fn generate_claim_key(
    participant_id: [u8; 32],
    epoch: u64,
    participant_type: u8,
    claim_type: u8,
) -> [u8; 32] {
    use solana_program::hash::hashv;

    hashv(&[
        &participant_id,
        &epoch.to_le_bytes(),
        &participant_type.to_le_bytes(),
        &claim_type.to_le_bytes(),
    ])
    .to_bytes()
}

// ===== DUAL MERKLE TREE VERIFICATION FUNCTIONS =====

/// Verify a dual merkle claim using both payment and seal proofs.
///
/// This function implements the core security verification for the Dual Merkle Tree system.
/// It verifies both the payment merkle proof (user activity within epoch) and the seal
/// merkle proof (payment root authenticity from oracle), with the payment root embedded
/// in the seal proof data.
///
/// ## Parameters
/// - `payment_proof`: Merkle proof for user's activity within the epoch
/// - `seal_proof`: Merkle proof that payment root is in the seal tree (contains payment root)
/// - `on_chain_seal_root`: Current seal merkle root stored on-chain
/// - `participant_data`: User's participant data to verify
///
/// ## Returns
/// - `Ok(())` if both proofs are valid
/// - `Err(InvalidPaymentProof)` if payment proof is invalid
/// - `Err(InvalidSealProof)` if seal proof is invalid
///
/// ## Security Features
/// - **Payment Proof**: Ensures claim data integrity within an epoch
/// - **Seal Proof**: Ensures payment merkle root is authentic (from oracle)
/// - **Payment Root**: Embedded in seal proof for explicit verification
/// - **Dual Verification**: Both proofs must pass for a valid claim
///
/// ## Example
/// ```rust
/// use miracle_api::{sdk, prelude::{DailyParticipantData, MerkleProof, SealProof}};
///
/// let participant = DailyParticipantData::new([1u8; 32], 1723680000, 1723766400, [1u8; 8], [2u8; 8], 5, 0);
/// let payment_proof = MerkleProof::new(vec![[2u8; 32]], vec![true]);
/// let seal_proof = SealProof::new_for_verification(vec![[4u8; 32]], vec![false], [3u8; 32]);
/// let on_chain_seal_root = [5u8; 32];
///
/// let result = sdk::verify_dual_merkle_claim(
///     &payment_proof,
///     &seal_proof,
///     on_chain_seal_root,
///     &participant,
/// );
///
/// match result {
///     Ok(()) => println!("Dual merkle verification successful"),
///     Err(e) => println!("Verification failed: {:?}", e),
/// }
/// ```
pub fn verify_dual_merkle_claim(
    payment_proof: &MerkleProof,
    seal_proof: &SealProof,
    on_chain_seal_root: [u8; 32],
    participant_data: &DailyParticipantData,
) -> Result<(), crate::error::MiracleError> {
    // Rule 1: Verify seal proof - payment root must be in seal merkle tree
    if !verify_seal_proof(
        &seal_proof.path,
        &seal_proof.indices,
        seal_proof.payment_root,
        on_chain_seal_root,
    ) {
        return Err(crate::error::MiracleError::InvalidSealProof);
    }

    // Rule 2: Verify payment proof against payment root
    if !payment_proof.verify(participant_data, seal_proof.payment_root) {
        return Err(crate::error::MiracleError::InvalidPaymentProof);
    }

    Ok(())
}

impl SealProof {
    /// Create a new seal proof with path, indices, payment root, and epoch-specific data.
    ///
    /// This constructor is required for:
    /// - Historical reward calculations
    /// - Production claim verification
    /// - Accurate epoch-specific data
    ///
    /// Use this for all production claims that require historical accuracy.
    ///
    /// ## Parameters
    /// - `path`: Seal merkle path nodes (sibling hashes)
    /// - `indices`: Seal direction indices (false = left, true = right)
    /// - `payment_root`: Payment root being proven (embedded in seal proof)
    /// - `customer_reward_pool`: Epoch-specific customer reward pool
    /// - `merchant_reward_pool`: Epoch-specific merchant reward pool
    /// - `total_customer_activity`: Epoch-specific total customer activity
    /// - `total_merchant_activity`: Epoch-specific total merchant activity
    /// - `community_score`: Epoch-specific community score
    /// - `customer_reward_share`: Epoch-specific customer reward share
    /// - `merchant_reward_share`: Epoch-specific merchant reward share
    /// - `weekly_active_users`: Epoch-specific weekly active users
    /// - `weekly_retention_rate`: Epoch-specific weekly retention rate
    /// - `weekly_activity_count`: Epoch-specific weekly activity count
    pub fn new(
        path: Vec<[u8; 32]>,
        indices: Vec<bool>,
        payment_root: [u8; 32],
        customer_reward_pool: u64,
        merchant_reward_pool: u64,
        total_customer_activity: u64,
        total_merchant_activity: u64,
        community_score: u16,
        customer_reward_share: u16,
        merchant_reward_share: u16,
        weekly_active_users: u32,
        weekly_retention_rate: u16,
        weekly_activity_count: u32,
    ) -> Self {
        Self {
            path,
            indices,
            payment_root,
            customer_reward_pool,
            merchant_reward_pool,
            total_customer_activity,
            total_merchant_activity,
            community_score,
            customer_reward_share,
            merchant_reward_share,
            weekly_active_users,
            weekly_retention_rate,
            weekly_activity_count,
        }
    }

    /// Create a new seal proof for verification purposes only.
    ///
    /// This constructor is suitable for:
    /// - Proof verification (merkle path validation)
    /// - Testing and development
    /// - Backward compatibility with existing proofs
    /// - Client-side utility functions
    ///
    /// ⚠️  WARNING: This proof will have zero epoch data.
    /// For historical reward calculations, use oracle-generated proofs instead.
    ///
    /// ## Parameters
    /// - `path`: Seal merkle path nodes (sibling hashes)
    /// - `indices`: Seal direction indices (false = left, true = right)
    /// - `payment_root`: Payment root being proven (embedded in seal proof)
    ///
    /// ## Usage
    /// ```rust
    /// use miracle_api::prelude::SealProof;
    /// let path = vec![[1u8; 32], [2u8; 32]];
    /// let indices = vec![true, false];
    /// let payment_root = [3u8; 32];
    /// let proof = SealProof::new_for_verification(path, indices, payment_root);
    /// // Use for proof verification only
    /// ```
    pub fn new_for_verification(
        path: Vec<[u8; 32]>,
        indices: Vec<bool>,
        payment_root: [u8; 32],
    ) -> Self {
        Self {
            path,
            indices,
            payment_root,
            customer_reward_pool: 0,
            merchant_reward_pool: 0,
            total_customer_activity: 0,
            total_merchant_activity: 0,
            community_score: 0,
            customer_reward_share: 0,
            merchant_reward_share: 0,
            weekly_active_users: 0,
            weekly_retention_rate: 0,
            weekly_activity_count: 0,
        }
    }
}

/// Verify a seal merkle proof.
///
/// This function verifies that a payment merkle root is included in the seal merkle tree.
/// The seal proof demonstrates that the payment root is authentic and was provided by the oracle.
///
/// ## Parameters
/// - `seal_path`: Seal merkle path nodes (Vec<[u8; 32]>)
/// - `seal_indices`: Seal direction indices (Vec<bool>)
/// - `payment_root`: Payment merkle root to verify
/// - `seal_root`: Root of the seal merkle tree
///
/// ## Returns
/// - `true` if seal proof is valid
/// - `false` if seal proof is invalid
///
/// ## Security
/// - Verifies payment root is authentic (from oracle)
/// - Prevents forged payment roots
/// - Ensures payment root is in the historical seal tree
fn verify_seal_proof(
    seal_path: &Vec<[u8; 32]>,
    seal_indices: &Vec<bool>,
    payment_root: [u8; 32],
    seal_root: [u8; 32],
) -> bool {
    // REJECT empty seal proof paths - they can't be verified
    if seal_path.is_empty() {
        return false;
    }

    if seal_path.len() != seal_indices.len() {
        return false;
    }

    let mut current_hash = payment_root;

    // Traverse the seal proof path
    for (i, &path_node) in seal_path.iter().enumerate() {
        let is_right = seal_indices[i];

        let mut combined_data = Vec::new();
        if is_right {
            // When is_right is true, the sibling is on the right
            // So current_hash should be on the left, path_node on the right
            combined_data.extend_from_slice(&current_hash);
            combined_data.extend_from_slice(&path_node);
        } else {
            // When is_right is false, the sibling is on the left
            // So path_node should be on the left, current_hash on the right
            combined_data.extend_from_slice(&path_node);
            combined_data.extend_from_slice(&current_hash);
        }

        current_hash = hashv(&[&combined_data]).to_bytes();
    }

    current_hash == seal_root
}

/// Seal Merkle Tree for incremental construction of historical payment roots.
///
/// This tree grows incrementally, adding each new payment merkle root as a leaf.
/// It enables unlimited claim history while maintaining perfect security.
///
/// ## Growth Pattern
///
/// The seal tree grows incrementally:
/// - Epoch 0: [Payment Root 0]
/// - Epoch 1: [Payment Root 0] + [Payment Root 1] -> Seal Root 1
/// - Epoch 2: [Payment Root 0] + [Payment Root 1] + [Payment Root 2] -> Seal Root 2
/// - ...
/// - Epoch N: [Payment Root 0] + ... + [Payment Root N] -> Seal Root N
///
/// ## Security
/// - Each payment root is embedded in the seal tree
/// - Seal proofs demonstrate payment root authenticity
/// - Dual verification prevents all attack vectors
///
/// ## 🚨 CRITICAL: Chronological Ordering Requirement
///
/// **PAYMENT ROOTS MUST BE PROVIDED IN CHRONOLOGICAL ORDER (EPOCH 0, 1, 2, 3...)**
///
/// This is essential for:
/// - Deterministic seal merkle root generation
/// - Consistent verification between Oracle and on-chain program
/// - Preventing `0x10` (InvalidPaymentProof) errors
///
/// The Oracle team MUST ensure:
/// 1. Database queries return epochs in chronological order
/// 2. Payment roots are collected in epoch sequence
/// 3. `SealMerkleTree::from_payment_roots()` receives ordered data
///
/// Failure to maintain chronological ordering will result in:
/// - Different seal merkle roots between Oracle and on-chain
/// - Proof verification failures
/// - Inability to process claims
#[repr(C)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SealMerkleTree {
    /// Current seal merkle root (32 bytes)
    pub root: [u8; 32],
    /// Internal tree structure for proof generation
    tree: Vec<Vec<[u8; 32]>>,
    /// Historical payment roots (leaves of the seal tree)
    payment_roots: Vec<[u8; 32]>,
}

impl SealMerkleTree {
    /// Create a new empty seal merkle tree.
    ///
    /// ## Returns
    /// - Empty seal merkle tree with zero root
    pub fn new() -> Self {
        Self {
            root: [0u8; 32],
            tree: vec![vec![]],
            payment_roots: vec![],
        }
    }

    /// Create a seal merkle tree from existing payment roots.
    ///
    /// ## Parameters
    /// - `payment_roots`: Vector of historical payment merkle roots
    ///
    /// ## Returns
    /// - Seal merkle tree with all payment roots included
    ///
    /// ## Important: Chronological Ordering
    /// The payment roots MUST be provided in chronological order (epoch 0, 1, 2, 3...)
    /// to ensure deterministic and verifiable seal merkle roots across all systems.
    /// This ordering rule is enforced to maintain consistency between Oracle and on-chain verification.
    pub fn from_payment_roots(payment_roots: Vec<[u8; 32]>) -> Self {
        if payment_roots.is_empty() {
            return Self::new();
        }

        // CRITICAL: Enforce chronological ordering for deterministic seal merkle roots
        // The Oracle team must provide payment roots in epoch order (0, 1, 2, 3...)
        // This ensures the on-chain program can verify proofs against the same tree structure
        if payment_roots.len() > 1 {
            // Note: We cannot directly sort by epoch number from payment root hashes
            // The Oracle team MUST provide payment roots in chronological order (0, 1, 2, 3...)
            // This is a critical architectural requirement for deterministic tree construction

            // Log warning about chronological ordering requirement
            // This helps debug ordering issues during development
            println!(
                "⚠️  WARNING: SealMerkleTree::from_payment_roots called with {} payment roots",
                payment_roots.len()
            );
            println!("   CRITICAL: Oracle team MUST provide payment roots in chronological order (epoch 0, 1, 2, 3...)");
            println!("   This ensures deterministic seal merkle roots for on-chain verification");
            println!("   Current implementation assumes correct ordering from Oracle team");
        }

        // Build merkle tree from payment roots
        let mut tree = Vec::new();
        tree.push(payment_roots.clone());

        while tree.last().unwrap().len() > 1 {
            let current_level = tree.last().unwrap();
            let mut next_level = Vec::new();

            for chunk in current_level.chunks(2) {
                if chunk.len() == 2 {
                    // Correct hash ordering: left child first, then right child
                    let combined = hashv(&[&chunk[0], &chunk[1]]).to_bytes();
                    next_level.push(combined);
                } else {
                    // Single element case
                    let combined = hashv(&[&chunk[0], &chunk[0]]).to_bytes();
                    next_level.push(combined);
                }
            }

            tree.push(next_level);
        }

        let root = tree.last().unwrap()[0];

        Self {
            root,
            tree,
            payment_roots,
        }
    }

    /// Add a new payment root to the seal merkle tree.
    ///
    /// This function incrementally grows the seal tree by adding the new payment root
    /// and rebuilding the tree structure.
    ///
    /// ## Parameters
    /// - `payment_root`: New payment merkle root to add
    ///
    /// ## Returns
    /// - Updated seal merkle tree with new payment root included
    ///
    /// ## Important: Chronological Ordering
    /// Payment roots MUST be added in chronological order (epoch 0, 1, 2, 3...)
    /// to maintain deterministic tree structure. This method assumes the new payment root
    /// is for the next sequential epoch.
    pub fn add_payment_root(&mut self, payment_root: [u8; 32]) {
        // CRITICAL: Ensure payment roots are added in chronological order
        // This method assumes the new payment root is for the next sequential epoch
        // The Oracle team must call this method in epoch order to maintain consistency
        println!(
            "🔒 Adding payment root to seal merkle tree (epoch {})",
            self.payment_roots.len()
        );
        println!("   CRITICAL: Payment roots must be added in chronological order for deterministic verification");

        self.payment_roots.push(payment_root);

        // Rebuild the entire tree with the new payment root
        let mut tree = Vec::new();
        tree.push(self.payment_roots.clone());

        while tree.last().unwrap().len() > 1 {
            let current_level = tree.last().unwrap();
            let mut next_level = Vec::new();

            for chunk in current_level.chunks(2) {
                if chunk.len() == 2 {
                    // Correct hash ordering: left child first, then right child
                    let combined = hashv(&[&chunk[0], &chunk[1]]).to_bytes();
                    next_level.push(combined);
                } else {
                    // Single element case
                    let combined = hashv(&[&chunk[0], &chunk[0]]).to_bytes();
                    next_level.push(combined);
                }
            }

            tree.push(next_level);
        }

        self.tree = tree;
        self.root = self.tree.last().unwrap()[0];
    }

    /// Get the current seal merkle root.
    ///
    /// ## Returns
    /// - Current seal merkle root (32 bytes)
    pub fn root(&self) -> [u8; 32] {
        self.root
    }

    /// Get the number of payment roots in the seal tree.
    ///
    /// ## Returns
    /// - Number of historical payment roots
    pub fn payment_root_count(&self) -> usize {
        self.payment_roots.len()
    }

    /// Get all payment roots in the seal tree.
    ///
    /// ## Returns
    /// - Vector of all historical payment roots
    pub fn payment_roots(&self) -> &[[u8; 32]] {
        &self.payment_roots
    }

    /// Validate that payment roots are in chronological order.
    ///
    /// This method helps ensure the Oracle team is providing payment roots
    /// in the correct epoch sequence for deterministic tree construction.
    ///
    /// ## Returns
    /// - `true` if payment roots appear to be in chronological order
    /// - `false` if there are potential ordering issues
    ///
    /// ## Note
    /// This is a best-effort validation since we can't directly determine
    /// epoch numbers from payment root hashes. The Oracle team must ensure
    /// chronological ordering when calling this method.
    pub fn validate_chronological_order(&self) -> bool {
        if self.payment_roots.len() <= 1 {
            return true; // Single or no payment roots are always "ordered"
        }

        // Log the current payment root count for debugging
        println!(
            "🔍 Validating chronological order of {} payment roots",
            self.payment_roots.len()
        );
        println!("   CRITICAL: Oracle team must ensure payment roots are provided in epoch order (0, 1, 2, 3...)");

        // Since we can't directly validate epoch numbers from hashes,
        // we rely on the Oracle team's commitment to chronological ordering
        // This method serves as a reminder and debugging aid
        true
    }

    /// Generate a seal proof for a specific payment root.
    ///
    /// This function creates a proof that demonstrates a payment root is included
    /// in the current seal merkle tree.
    ///
    /// ## Parameters
    /// - `payment_root`: Payment root to generate proof for
    ///
    /// ## Returns
    /// - `Some(SealProof)` if payment root is found
    /// - `None` if payment root is not in the tree
    pub fn generate_seal_proof(&self, payment_root: [u8; 32]) -> Option<SealProof> {
        // Find the index of the payment root
        let payment_root_index = self
            .payment_roots
            .iter()
            .position(|&root| root == payment_root)?;

        let mut path = Vec::new();
        let mut indices = Vec::new();

        let mut current_index = payment_root_index;
        for level in &self.tree[..self.tree.len() - 1] {
            let sibling_index = if current_index % 2 == 0 {
                current_index + 1
            } else {
                current_index - 1
            };

            if sibling_index < level.len() {
                path.push(level[sibling_index]);
                indices.push(current_index % 2 == 1); // true if right sibling
            }

            current_index /= 2;
        }

        Some(SealProof::new_for_verification(path, indices, payment_root))
    }

    /// Find and generate a seal proof for a payment root by epoch.
    ///
    /// This is a convenience function that finds a payment root by its epoch index
    /// and generates a seal proof for it.
    ///
    /// ## Parameters
    /// - `epoch_index`: Index of the epoch (0-based)
    ///
    /// ## Returns
    /// - `Some(SealProof)` if epoch exists
    /// - `None` if epoch index is out of bounds
    pub fn generate_seal_proof_for_epoch(&self, epoch_index: usize) -> Option<SealProof> {
        let payment_root = self.payment_roots.get(epoch_index)?;
        self.generate_seal_proof(*payment_root)
    }

    /// Verify that a payment root is included in the seal tree.
    ///
    /// ## Parameters
    /// - `payment_root`: Payment root to verify
    ///
    /// ## Returns
    /// - `true` if payment root is in the seal tree
    /// - `false` if payment root is not in the seal tree
    pub fn contains_payment_root(&self, payment_root: [u8; 32]) -> bool {
        self.payment_roots.contains(&payment_root)
    }
}

/// Create a new seal merkle tree.
///
/// This is a convenience function that creates an empty seal merkle tree.
/// Use `SealMerkleTree::from_payment_roots()` to create a tree with existing payment roots.
///
/// ## Returns
/// - Empty seal merkle tree
///
/// ## Example
/// ```rust
/// use miracle_api::sdk::create_seal_merkle_tree;
///
/// let mut seal_tree = create_seal_merkle_tree();
/// seal_tree.add_payment_root([1u8; 32]);
/// println!("Seal root: {:?}", seal_tree.root());
/// ```
pub fn create_seal_merkle_tree() -> SealMerkleTree {
    SealMerkleTree::new()
}

/// Create a seal merkle tree from payment roots.
///
/// This is a convenience function that creates a seal merkle tree from existing payment roots.
///
/// ## Parameters
/// - `payment_roots`: Vector of historical payment merkle roots
///
/// ## Returns
/// - Seal merkle tree with all payment roots included
///
/// ## 🚨 CRITICAL: Chronological Ordering Requirement
///
/// **PAYMENT ROOTS MUST BE PROVIDED IN CHRONOLOGICAL ORDER (EPOCH 0, 1, 2, 3...)**
///
/// This is essential for deterministic seal merkle root generation and consistent
/// verification between Oracle and on-chain program. Failure to maintain chronological
/// ordering will result in proof verification failures.
///
/// ## Example
/// ```rust
/// use miracle_api::sdk::create_seal_merkle_tree_from_roots;
///
/// let payment_roots = vec![[1u8; 32], [2u8; 32], [3u8; 32]];
/// let seal_tree = create_seal_merkle_tree_from_roots(payment_roots);
/// println!("Seal root: {:?}", seal_tree.root());
/// ```
pub fn create_seal_merkle_tree_from_roots(payment_roots: Vec<[u8; 32]>) -> SealMerkleTree {
    SealMerkleTree::from_payment_roots(payment_roots)
}

/// Generate a seal proof for a payment root.
///
/// This is a convenience function that generates a seal proof for a payment root
/// from a seal merkle tree.
///
/// ## Parameters
/// - `seal_tree`: Seal merkle tree
/// - `payment_root`: Payment root to generate proof for
///
/// ## Returns
/// - `Some(SealProof)` if payment root is found
/// - `None` if payment root is not in the tree
///
/// ## Example
/// ```rust
/// use miracle_api::sdk::{create_seal_merkle_tree_from_roots, generate_seal_proof};
///
/// let payment_roots = vec![[1u8; 32], [2u8; 32]];
/// let seal_tree = create_seal_merkle_tree_from_roots(payment_roots);
/// let seal_proof = generate_seal_proof(&seal_tree, [1u8; 32]);
/// assert!(seal_proof.is_some());
/// ```
pub fn generate_seal_proof(
    seal_tree: &SealMerkleTree,
    payment_root: [u8; 32],
) -> Option<SealProof> {
    seal_tree.generate_seal_proof(payment_root)
}

/// Computes the epoch hash for the Epoch Hash Chain security solution.
///
/// This function implements the same logic as the on-chain program:
/// - Epoch 0: Uses the predefined genesis hash constant
/// - Subsequent epochs: Hash(previous_epoch_hash + epoch_number + current_payment_merkle_root)
///
/// ## Parameters
/// - `epoch`: The epoch number
/// - `previous_epoch_hash`: The hash from the previous epoch (use genesis hash for epoch 0)
/// - `payment_merkle_root`: The current epoch's payment merkle root
///
/// ## Returns
/// The computed epoch hash for tamper detection
///
/// ## Security
/// This function must be used consistently between off-chain oracle processing
/// and on-chain verification to maintain the hash chain integrity.
/// The epoch number inclusion ensures uniqueness even with identical payment roots.
///
/// ## Implementation Details
/// - **Epoch 0**: Uses the predefined genesis hash constant (same as on-chain program)
/// - **Subsequent epochs**: Build upon the previous epoch hash + epoch number + payment root
/// - **No fallback logic**: Since program now initializes with genesis hash, fallback is not needed
/// - **Uniqueness guarantee**: Epoch number ensures uniqueness even with identical payment roots
pub fn compute_epoch_hash(
    epoch: u64,
    previous_epoch_hash: [u8; 32],
    payment_merkle_root: [u8; 32],
) -> [u8; 32] {
    if epoch == 0 {
        // For epoch 0, use the predefined genesis hash constant
        // This maintains security while allowing epoch 0 to be properly initialized
        crate::consts::miracle_epoch_0_genesis()
    } else {
        // For subsequent epochs: Previous hash + EPOCH_NUMBER + current payment merkle root
        // This creates an unbreakable chain: each epoch depends on all previous epochs
        // The epoch number ensures uniqueness even when payment roots are identical (e.g., empty epochs)

        // Handle fallback for backward compatibility (external callers might still pass [0; 32])
        let previous_epoch_hash = if previous_epoch_hash == [0u8; 32] {
            // If previous epoch hash is zero, use genesis as fallback (same as program)
            // This handles cases where the previous epoch hash hasn't been set yet
            crate::consts::miracle_epoch_0_genesis()
        } else {
            previous_epoch_hash
        };

        // Include epoch number to ensure uniqueness even with empty payment roots
        let epoch_bytes = epoch.to_le_bytes();
        hashv(&[&previous_epoch_hash, &epoch_bytes, &payment_merkle_root]).to_bytes()
    }
}