pallet-xp 0.1.2

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

// ===============================================================================
// ``````````````````````````````` XP TRAITS IMPLS ```````````````````````````````
// ===============================================================================

//! Implementations of [`XP`](frame_suite::xp) traits for
//! the [`Pallet`] Type.
//!
//! [`Pallet`] implements:
//! - [`XpSystem`]
//! - [`XpOwner`]
//! - [`XpMutate`]
//! - [`XpReap`]
//! - [`XpReserve`]
//! - [`XpLock`]
//! - and other helper traits include
//!     - [`DiscreteAccumulator`]
//!     - [`XpErrorHandler`]
//!
//! Local Tests for these traits are covered in `tests`.

// ===============================================================================
// `````````````````````````````````` IMPORTS ````````````````````````````````````
// ===============================================================================

// --- Core ---
use core::cmp::Ordering;

// --- Local crate imports ---
use crate::{
    types::{Accumulator, IdXp, Stepper, Xp, XpId},
    Config, Error, Event, InitXp, LockedXpOf, MinPulse, MinTimeStamp, Pallet, PulseFactor,
    ReapedXp, ReservedXpOf, XpOf, XpOwners,
};

// --- FRAME Suite ---
use frame_suite::{
    accumulators::DiscreteAccumulator,
    keys::{KeyGenFor, KeySeedFor},
    xp::{
        XpError, XpErrorHandler, XpLock, XpLockListener, XpMutate, XpMutateListener, XpOwner,
        XpOwnerListener, XpReap, XpReapListener, XpReserve, XpReserveListener, XpSystem,
    },
};

// --- FRAME Support ---
use frame_support::{dispatch::DispatchResult, ensure, traits::VariantCountOf};

// --- FRAME System ---
use frame_system::pallet_prelude::BlockNumberFor;

// --- Substrate primitives ---
use sp_core::Get;
use sp_runtime::{
    traits::{CheckedAdd, CheckedMul, CheckedSub, One, Zero},
    BoundedVec, DispatchError, Saturating, Vec,
};

// ===============================================================================
// ````````````````````````````````` XP SYSTEM ```````````````````````````````````
// ===============================================================================

/// Implementation of the `XpSystem` trait for the XP pallet.
///
/// This provides the core, read-only interface for querying XP state, metadata,
/// and key management. All methods are implemented in terms of the pallet's storage
/// items and types.
impl<T: Config<I>, I: 'static> XpSystem for Pallet<T, I> {
    /// The primary data structure for XP accounts in this pallet.
    ///
    /// It encapsulates all metadata information for an XP entry,
    /// including liquid, reserved, and locked XP, as well as reputation pulse
    /// and timestamp.
    type Xp = Xp<T, I>;

    /// The scalar type representing XP points (the main XP balance unit).
    type Points = T::Xp;

    /// The unique key type for XP entries (distinct from the owner).
    ///
    /// Same as [`frame_system::Config::AccountId`]
    type XpKey = XpId<T>;

    /// The type representing the timestamp (block number) for XP lifecycle tracking.
    type TimeStamp = BlockNumberFor<T>;

    /// Pallet Extensions includes external listeners and their triggers.
    type Extension = T::Extensions;

    /// Checks if an XP entry exists for the given key.
    ///
    /// This function verifies the existence of an XP entry in storage by checking
    /// if the provided key exists in the `XpOf` storage map.
    ///
    /// ## Returns
    /// - `Ok(())` if the XP entry exists for the given key
    /// - `Err(DispatchError)` if the entry does not exist
    fn xp_exists(key: &Self::XpKey) -> DispatchResult {
        ensure!(XpOf::<T, I>::contains_key(key), Error::<T, I>::XpNotFound);
        Ok(())
    }

    /// Retrieves the complete XP struct for the given key.
    ///
    /// This function fetches the full XP data structure from storage,
    /// containing all metadata including liquid, reserved, locked XP,
    /// reputation pulse, and timestamp.
    ///
    /// ## Returns
    /// - `Ok(Xp)` containing the complete XP struct if found
    /// - `Err(DispatchError)` if the entry does not exist
    fn get_xp(key: &Self::XpKey) -> Result<Self::Xp, DispatchError> {
        let Some(xp) = XpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpNotFound.into());
        };
        Ok(xp)
    }

    /// Validates if the XP entry meets the minimum timestamp threshold.
    ///
    /// This function checks whether an XP entry's timestamp satisfies the
    /// minimum timestamp requirement, which is used for XP liveness validation
    /// and reaping logic.
    ///
    /// ## Returns
    /// - `Ok(())` if the XP entry meets the minimum timestamp threshold
    /// - `Err(DispatchError)` if the timestamp is below the minimum
    fn has_minimum_xp(key: &Self::XpKey) -> DispatchResult {
        let xp = Self::get_xp(key)?;
        // Instead of asserting scalar xp points, we enforce
        // minimum timestamp as criteria
        ensure!(
            xp.timestamp >= MinTimeStamp::<T, I>::get(),
            Error::<T, I>::LowTimeStamp
        );
        Ok(())
    }

    /// Retrieves the liquid (free) XP balance for the given key.
    ///
    /// This function returns liquid XP points, which represents the freely
    /// spendable XP balance that is not reserved or locked for any specific purpose.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the liquid XP balance if found
    /// - `Err(DispatchError)` if the entry does not exist
    fn get_liquid_xp(key: &Self::XpKey) -> Result<Self::Points, DispatchError> {
        let xp = Self::get_xp(key)?;
        Ok(xp.free)
    }

    /// Retrieves the total usable XP (liquid + reserved) for the given key.
    ///
    /// This function calculates and returns the sum of liquid and reserved XP,
    /// representing the total amount of XP that can be utilized by the account.
    /// Locked XP is excluded as it cannot be spent or transferred.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the total usable XP balance if found
    /// - `Err(DispatchError)` if the entry does not exist
    fn get_usable_xp(key: &Self::XpKey) -> Result<Self::Points, DispatchError> {
        let xp = Self::get_xp(key)?;
        Ok(xp.free.saturating_add(xp.reserve))
    }
}

// ===============================================================================
// ``````````````````````````````````` XP OWNER ``````````````````````````````````
// ===============================================================================

/// Implementation of the `XpOwner` trait for the XP pallet.
///
/// This provides the interface for XP ownership and access control, including
/// checking ownership, enumerating all XP keys owned by an account, transferring
/// ownership, and emitting ownership events.
///
/// All methods are implemented in terms of the pallet's storage items and types.
impl<T: Config<I>, I: 'static> XpOwner for Pallet<T, I> {
    /// The account ID type representing the owner of an XP entry.
    type Owner = T::AccountId;

    /// Checks if the given owner possesses ownership of the specified XP key.
    ///
    /// This function verifies ownership by checking if the owner-key pair exists
    /// in the [`XpOwners`] storage map.
    ///
    /// ## Returns
    /// - `Ok(())` if the owner possesses ownership of the XP key
    /// - `Err(DispatchError)` if the owner does not have ownership rights
    fn is_owner(owner: &Self::Owner, key: &Self::XpKey) -> DispatchResult {
        ensure!(
            XpOwners::<T, I>::contains_key((owner, key)),
            Error::<T, I>::InvalidXpOwner
        );
        Ok(())
    }

    /// Retrieves all XP keys currently owned by the given owner.
    ///
    /// ## Returns
    /// - `Ok(Vec<XpKey>)` containing all valid XP keys owned by the account
    /// - `Err(DispatchError)` if there are issues accessing storage
    fn xp_of_owner(owner: &Self::Owner) -> Result<Vec<Self::XpKey>, DispatchError> {
        let mut vec = Vec::new();
        // Direct iteration on the owner, hence carries no wasted compute
        let iter = XpOwners::<T, I>::iter_prefix((owner,));
        for (key, _) in iter {
            vec.push(key)
        }
        Ok(vec)
    }

    /// Sets the owner of the given XP key.
    ///
    /// ## Note
    /// This is a low-level primitive that directly mutates storage without
    /// performing access control checks.
    ///
    /// It should generally only be used internally. Prefer higher-level
    /// APIs such as [`Self::transfer_owner`] for safe ownership transitions.
    ///
    /// ## Returns
    /// - `Ok(())` if the owner is successfully updated
    /// - `Err(DispatchError)` if the operation fails
    fn set_owner(
        owner: &Self::Owner,
        key: &Self::XpKey,
        new_owner: &Self::Owner,
    ) -> DispatchResult {
        XpOwners::<T, I>::remove((owner, key));
        XpOwners::<T, I>::insert((new_owner, key), ());
        Ok(())
    }
    /// Generates a deterministic XP key from the provided owner and XP data.
    ///
    /// This function creates a unique XP key using the owner's account ID, the XP struct,
    /// and the owner's current nonce as salt to ensure uniqueness and prevent collisions.
    /// The key generation is deterministic for the same inputs and state-variables.
    ///
    /// ## Returns
    /// - `Ok(XpKey)` containing the generated XP key if successful
    /// - `Err(DispatchError)` if the key generation process fails
    fn xp_key_gen(owner: &Self::Owner, xp: &Self::Xp) -> Result<Self::XpKey, DispatchError> {
        let target: &Self::XpKey = owner;
        let salt = frame_system::Pallet::<T>::account_nonce(owner);
        let Some(key) =
            KeySeedFor::<Self::XpKey, Self::Xp, T::Nonce, T::Hashing, T>::gen_key(target, xp, salt)
        else {
            return Err(Error::<T, I>::CannotGenerateXpKey.into());
        };
        Ok(key)
    }

    /// Hook invoked after a successful XP ownership transfer.
    ///
    /// Emits an `XpOwner` event with the new owner and XP key.
    fn on_xp_transfer(key: &Self::XpKey, new_owner: &Self::Owner) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpOwner {
                id: key.clone(),
                owner: new_owner.clone(),
            });
        }
        Self::Extension::xp_transferred(key, new_owner)
    }
}

/// Implementation of the `XpMutate` trait for the XP pallet.
///
/// This provides the interface for mutating XP entries, including creation,
/// earning (with reputation effects), direct setting, and lifecycle hooks
/// for XP changes.
///
/// All methods are implemented in terms of the pallet's storage items and types.
impl<T: Config<I>, I: 'static> XpMutate for Pallet<T, I> {
    /// Returns the configured initial XP value for new entries.
    ///
    /// This value is retrieved from runtime storage ([`InitXp`]) and is used
    /// during [`Self::create_xp`] to initialize newly created XP records.
    fn init_xp() -> Self::Points {
        InitXp::<T, I>::get()
    }

    /// Creates and initializes a new XP entry for the given key and owner.
    ///
    /// **Use with caution!** as this bypasses typical XP flow and permission
    /// checks. Overwrites any existing XP entry without validation.
    ///
    /// For absolute safety, utilize [`frame_suite::xp::BeginXp::begin_xp`]
    fn new_xp(owner: &Self::Owner, key: &Self::XpKey) {
        let xp = Xp::<T, I>::default();
        XpOf::<T, I>::insert(key, xp);
        XpOwners::<T, I>::insert((&owner, &key), ());
    }

    /// **Use with caution!** This function bypasses typical XP flow and
    /// permission checks.
    ///
    /// Directly sets the liquid XP (`free`) for the given key.
    ///
    /// Unlike [`Self::earn_xp`], this method does not compute or validate the
    /// provided points. It simply overwrites the current liquid XP value.
    ///
    /// Intended for low-level runtime intents (e.g., migrations or internal resets).
    ///
    /// ## Returns
    /// - `Ok(())` if the XP was successfully set
    /// - `Err(DispatchError)` if the XP entry does not exist
    fn set_xp(key: &Self::XpKey, points: Self::Points) -> DispatchResult {
        XpOf::<T, I>::mutate(key, |result| -> DispatchResult {
            let value = result.as_mut().ok_or(Error::<T, I>::XpNotFound)?;
            value.free = points;
            Ok(())
        })?;
        Ok(())
    }

    /// Increments the liquid XP of a given key, applying pulse-based reputation mechanics.
    ///
    /// This function is the primary entry point for awarding XP from user-driven
    /// runtime actions such as task completion, participation events, or other
    /// domain-specific intents.
    ///
    /// Instead of directly crediting raw XP on every call, this method integrates
    /// a pulse-based reputation system that:
    /// - Prevents inflation from repeated calls within the same block
    /// - Gradually builds reputation (pulse) before scaling XP rewards
    /// - Multiplies earned XP once sufficient reputation is achieved
    /// - Provides accelerated reputation growth for locked (committed/staked) accounts
    ///
    /// ### Core Mechanics
    ///
    /// 1. **Same-block protection**
    ///    - If XP is earned multiple times within the same block and the pulse
    ///      is already above the minimum threshold, only raw XP is added.
    ///    - Pulse is intentionally NOT incremented to discourage rapid intra-block spamming.
    ///
    /// 2. **Pulse warm-up phase**
    ///    - If the pulse reputation is below [`MinPulse`], XP is not granted yet.
    ///    - Instead, the pulse accumulator is incremented, encouraging consistent
    ///      long-term participation rather than burst activity.
    ///
    /// 3. **Scaled XP phase**
    ///    - Once `MinPulse` is reached, earned XP is multiplied by the current
    ///      pulse value, rewarding reputable accounts with higher returns.
    ///
    /// 4. **Lock-based acceleration**
    ///    - If a lock exists on the XP key (e.g., staking or commitment),
    ///      the pulse is incremented again to accelerate future reputation growth.
    ///
    /// ### Note
    ///
    /// `MinPulse` is dynamic-storage value to support a live, gamified XP economy.
    /// As the ecosystem evolves, the required reputation tier can be
    /// adjusted to maintain fair progression, prevent early-stage farming,
    /// and keep long-term engagement meaningful without resetting user progress.
    ///
    /// ### Returns
    /// - `Ok(Points)` containing the actual XP credited after pulse scaling
    /// - `Err(DispatchError)` if computation or storage mutation fails
    fn earn_xp(key: &Self::XpKey, points: Self::Points) -> Result<Self::Points, DispatchError> {
        // Tracks the actual XP credited after all pulse scaling and checks.
        let mut actual = Self::Points::zero();

        XpOf::<T, I>::mutate(key, |result| -> DispatchResult {
            // Fetch the XP entry; fail if it does not exist.
            let value = result.as_mut().ok_or(Error::<T, I>::XpNotFound)?;

            // Current block number used for anti-spam and time-bound pulse logic.
            let current_block_height = <frame_system::Pallet<T>>::block_number();

            // -----------------------------------------------------------------
            // Same-block protection:
            // If XP earning is attempted again within the same block AND the
            // pulse reputation is already above the minimum threshold, we only
            // add raw XP without increasing pulse.
            //
            // This prevents artificial inflation of reputation from repeated
            // calls within a single block while still allowing XP crediting.
            // -----------------------------------------------------------------
            if current_block_height <= value.timestamp
                && value.pulse.value >= MinPulse::<T, I>::get()
            {
                let old_points = value.free;

                let new_points = old_points
                    .checked_add(&points)
                    .ok_or(Error::<T, I>::XpCapOverflowed)?;

                // Actual credited XP (safe difference computation).
                actual = new_points.saturating_sub(old_points);
                value.free = new_points;

                return Ok(());
            }

            // Update timestamp to indicate XP processing for this block.
            value.timestamp = current_block_height;

            // -----------------------------------------------------------------
            // Pulse warm-up phase:
            // If the pulse reputation has not yet reached the minimum threshold,
            // we do not grant XP. Instead, we increment the pulse accumulator
            // to gradually build reputation over time.
            // -----------------------------------------------------------------
            if value.pulse.value < MinPulse::<T, I>::get() {
                <Pallet<T, I> as DiscreteAccumulator>::increment(
                    &mut value.pulse,
                    &PulseFactor::<T, I>::get(),
                );
                return Ok(());
            }

            // -----------------------------------------------------------------
            // Scaled XP phase:
            // Once the pulse meets the minimum threshold, XP is multiplied by
            // the pulse value to reward reputable and consistent participants.
            // -----------------------------------------------------------------
            let multiplied = points
                .checked_mul(&value.pulse.value.into())
                .ok_or(Error::<T, I>::ReputationDeriveOverflowed)?;

            let new_points = multiplied
                .checked_add(&value.free)
                .ok_or(Error::<T, I>::XpCapOverflowed)?;

            let old_points = value.free;

            // Compute actual credited XP after scaling.
            actual = new_points
                .checked_sub(&old_points)
                .ok_or(Error::<T, I>::XpComputationError)?;

            value.free = new_points;

            // -----------------------------------------------------------------
            // Lock-based pulse acceleration:
            // If the account has an active lock (e.g., staked or committed),
            // increment pulse again to accelerate future reputation growth.
            //
            // This incentivizes stronger long-term participation by allowing
            // locked accounts to climb reputation tiers faster.
            // -----------------------------------------------------------------
            if <Self as XpLock>::has_lock(key).is_ok() {
                <Pallet<T, I> as DiscreteAccumulator>::increment(
                    &mut value.pulse,
                    &PulseFactor::<T, I>::get(),
                );
            }

            Ok(())
        })?;
        Self::on_xp_earn(key, actual);

        Ok(actual)
    }

    /// Determines the effective XP that would be earned for a given key,
    /// applying pulse-based reputation mechanics.
    ///
    /// This method mirrors the logic of [`XpMutate::earn_xp`] but does not mutate state.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the actual XP that would be credited after pulse scaling
    /// - `Err(DispatchError)` if computation fails or the XP key does not exist
    fn quote_earn_xp(
        key: &Self::XpKey,
        points: Self::Points,
    ) -> Result<Self::Points, DispatchError> {
        let value = XpOf::<T, I>::get(key).ok_or(Error::<T, I>::XpNotFound)?;

        let current_block_height = <frame_system::Pallet<T>>::block_number();

        // Same-block protection
        if current_block_height <= value.timestamp && value.pulse.value >= MinPulse::<T, I>::get() {
            return Ok(points);
        }

        // Pulse warm-up phase
        if value.pulse.value < MinPulse::<T, I>::get() {
            return Ok(Self::Points::zero());
        }

        // Scaled XP phase
        let multiplied = points
            .checked_mul(&value.pulse.value.into())
            .ok_or(Error::<T, I>::ReputationDeriveOverflowed)?;

        Ok(multiplied)
    }

    /// Hook invoked after an XP entry is updated reflecting
    /// currently available XP Points.
    ///
    /// Emits an `Xp` event with the XP key and liquid points if
    /// [`Config::EmitEvents`] is `true`.
    /// - Calls the Listener [`XpMutateListener::xp_updated`]
    fn on_xp_update(key: &Self::XpKey, points: Self::Points) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::Xp {
                id: key.clone(),
                xp: points,
            });
        }
        Self::Extension::xp_updated(key, points)
    }

    /// Hook invoked after a XP is earned.
    ///
    /// Emits an `XpEarn` event with the XP key and earned points if
    /// [`Config::EmitEvents`] is `true`.
    /// - Calls the Listener [`XpMutateListener::xp_earned`]
    fn on_xp_earn(key: &Self::XpKey, points: Self::Points) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpEarn {
                id: key.clone(),
                xp: points,
            });
        }
        Self::Extension::xp_earned(key, points);
    }

    /// Hook invoked after a new XP entry is created.
    ///
    /// Emits an `XpCreate` event with the XP key and owner if
    /// [`Config::EmitEvents`] is `true`.
    /// - Calls the listener [`XpMutateListener::xp_created`]
    fn on_xp_create(key: &Self::XpKey, owner: &Self::Owner) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpOwner {
                id: key.clone(),
                owner: owner.clone(),
            });
        }
        T::Extensions::xp_created(key, owner);
    }

    /// Hook invoked after XP points are slashed.
    ///
    /// Emits an `XpSlash` event with the XP key and slashed points if
    /// [`Config::EmitEvents`] is `true`.
    /// - Calls the listener [`XpMutateListener::xp_slashed`]
    fn on_xp_slash(key: &Self::XpKey, slashed_points: Self::Points) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpSlash {
                id: key.clone(),
                xp: slashed_points,
            });
        }
        T::Extensions::xp_slashed(key, slashed_points);
    }
}

// ===============================================================================
// `````````````````````````````````` XP RESERVE `````````````````````````````````
// ===============================================================================

/// Implementation of the `XpReserve` trait for the XP pallet.
///
/// This provides the interface for managing XP reserves, including
/// creation, mutation, querying, and event emission for reserved XP.
/// All methods are implemented in terms of the pallet's storage items and types.
///
impl<T: Config<I>, I: 'static> XpReserve for Pallet<T, I> {
    /// The structure representing reserve metadata (reason and reserved XP amount).
    type Reserve = IdXp<T::ReserveReason, T::Xp>;

    /// The lock reason identifier used to categorize locked XP points.
    type ReserveReason = T::ReserveReason;

    /// Checks if a reserve exists for the given XP key and reserve reason.
    ///
    /// ## Returns
    /// - `Ok(())` if the reserve exists for the given key and reason
    /// - `Err(DispatchError)` if the reserve does not exist
    fn reserve_exists(key: &Self::XpKey, reason: &Self::ReserveReason) -> DispatchResult {
        let Some(reserves) = ReservedXpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpReserveNotFound.into());
        };
        if !(reserves.iter().any(|reserve| reserve.id == *reason)) {
            return Err(Error::<T, I>::XpReserveNotFound.into());
        }
        Ok(())
    }

    /// Retrieves the XP points reserved under the specified reserve reason.
    ///
    /// This function returns the amount of XP points currently reserved for a specific
    /// reason on the given XP key.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the reserved XP points if found
    /// - `Err(DispatchError)` if the XP key or reserve reason does not exist
    fn get_reserve_xp(
        key: &Self::XpKey,
        reason: &Self::ReserveReason,
    ) -> Result<Self::Points, DispatchError> {
        let Some(reserves) = ReservedXpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpReserveNotFound.into());
        };
        let Some(reserve) = reserves.iter().find(|reserve| reserve.id == *reason) else {
            return Err(Error::<T, I>::XpReserveNotFound.into());
        };
        Ok(reserve.points)
    }

    /// Retrieves the total XP points actively reserved for the given key.
    ///
    /// This function returns the sum of all reserved XP across all reserve reasons
    /// for the specified XP key.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the total reserved XP points if found
    /// - `Err(DispatchError)` if the XP key does not exist
    fn total_reserved(key: &Self::XpKey) -> Result<Self::Points, DispatchError> {
        let Some(xp) = XpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpNotFound.into());
        };
        Ok(xp.reserve)
    }

    /// Checks if the given XP key has at least one active reserve.
    ///
    /// This function verifies that the XP key has one or more active reserves by
    /// checking if the reserves vector is non-empty.
    ///
    /// ## Returns
    /// - `Ok(())` if the XP key has at least one active reserve
    /// - `Err(DispatchError)` if no reserves exist for the XP key
    fn has_reserve(key: &Self::XpKey) -> DispatchResult {
        let Some(reserve) = ReservedXpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpReserveNotFound.into());
        };
        if reserve.is_empty() {
            return Err(Error::<T, I>::XpReserveNotFound.into());
        }
        Ok(())
    }

    /// Retrieves all active reserve reasons associated with the XP key.
    ///
    /// This function returns a list of all reserve reason identifiers currently
    /// active for the specified XP key.
    ///
    /// ## Returns
    /// - `Ok(Vec<Self::ReserveReason>)` containing all active reserve reasons
    /// - Empty vector if no reserves exist for the XP key
    fn get_all_reserves(key: &Self::XpKey) -> Result<Vec<Self::ReserveReason>, DispatchError> {
        let all_reserves = ReservedXpOf::<T, I>::get(key)
            .map(|reserves| reserves.iter().map(|reserve| reserve.id).collect())
            .unwrap_or_default();
        Ok(all_reserves)
    }

    /// Forcefully sets the reserved XP for a specific reserve reason.
    ///
    /// This function bypasses typical XP flow and permission checks, directly
    /// modifying reserve state without enforcing invariants.
    ///
    /// Creates a new reserve if none exists for the given reason, or updates an existing reserve.
    ///
    /// Use with caution as this is intended for internal runtime operations such
    /// as migrations, resets, or exceptional administrative flows.
    ///
    /// ## Returns
    /// - `Ok(())` if the reserve was successfully set
    /// - `Err(DispatchError)` if operation fails due to overflow or other constraints
    fn set_reserve(
        key: &Self::XpKey,
        reason: &Self::ReserveReason,
        points: Self::Points,
    ) -> DispatchResult {
        // Creates a new reserve if no reserve exist for the given key and reason.
        if Self::reserve_exists(key, reason).is_err() {
            // Permission and overflow checks are performed before creation to avoid inconsistent state.
            Self::can_reserve_new(key, points)?;
            let reserve = Self::Reserve::new(*reason, points);

            ReservedXpOf::<T, I>::mutate(key, |result| -> DispatchResult {
                let value = result.get_or_insert_with(|| {
                    BoundedVec::<Self::Reserve, VariantCountOf<Self::ReserveReason>>::default()
                });
                let result = value.try_push(reserve);

                debug_assert!(
                    result.is_ok(),
                    "reserves vector already bounded by reason, hence 
                    additional reserves cannot be attempted itself, inconsistency detected 
                    at set new reserve of points {points:?} for xp-key {key:?} for reason {reason:?}"
                );

                result.map_err(|_| Error::<T, I>::TooManyReserves)?;

                Ok(())
            })?;

            XpOf::<T, I>::mutate(key, |result| -> DispatchResult {
                let value = result.as_mut();
                debug_assert!(
                    value.is_some(),
                    "xp-key {key:?} reserve of reason {reason:?} newly created but Xp 
                    Meta not available to update high-level storage"
                );
                let value = value.ok_or(Error::<T, I>::XpNotFound)?;
                value.reserve = value
                    .reserve
                    .checked_add(&points)
                    .ok_or(Error::<T, I>::XpReserveCapOverflowed)?;

                Ok(())
            })?;
            return Ok(());
        }

        // Update an existing reserve
        // Permission and overflow checks are performed before mutation to avoid inconsistent state.
        Self::can_reserve_mutate(key, reason, points)?;
        ReservedXpOf::<T, I>::mutate(key, |result| -> DispatchResult {
            let value = result.as_mut();
            debug_assert!(
                value.is_some(),
                "can mutate reserve of xp-key {key:?} for reason {reason:?} but 
                cannot access the specific reserve-meta"
            );
            let value = value.ok_or(Error::<T, I>::XpReserveNotFound)?;
            let reserve = value
                .iter_mut()
                .find(|reserve| reserve.id == *reason)
                .ok_or(Error::<T, I>::XpReserveNotFound)?;
            let current_reserved = reserve.points;
            reserve.points = points;

            XpOf::<T, I>::mutate(key, |result| -> DispatchResult {
                let value = result.as_mut();
                debug_assert!(
                    value.is_some(),
                    "xp-key {key:?} reserve of reason {reason:?} recently mutated, but now Xp-meta 
                    not available to mutate"
                );
                let value = value.ok_or(Error::<T, I>::XpNotFound)?;

                let total_reserved = value.reserve;

                match current_reserved.cmp(&points) {
                    Ordering::Greater => {
                        let decrease = current_reserved.saturating_sub(points);
                        value.reserve = total_reserved.saturating_sub(decrease);
                    }
                    Ordering::Less => {
                        let increase = points.saturating_sub(current_reserved);
                        value.reserve = total_reserved.saturating_add(increase);
                    }
                    Ordering::Equal => return Ok(()),
                }
                Ok(())
            })?;
            Ok(())
        })?;
        Ok(())
    }

    /// Hook invoked after a new reservation is created or mutated.
    ///
    /// Emits an `XpReserve` event with the XP key, reserve reason,
    /// and reserve points if [`Config::EmitEvents`] is `true`.
    /// - Calls the Listener [`XpReserveListener::reserve_updated`]
    fn on_reserve_update(
        key: &Self::XpKey,
        reason: &Self::ReserveReason,
        reserve_points: Self::Points,
    ) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpReserve {
                of: key.clone(),
                reason: *reason,
                xp: reserve_points,
            });
        }
        Self::Extension::reserve_updated(key, reason, reserve_points);
    }

    /// Hook invoked after reserved XP points are slashed.
    ///
    /// Emits an `XpReserveSlash` event with the XP key, reserve reason,
    /// and slashed points if [`Config::EmitEvents`] is `true`.
    /// - Calls the listener [`XpReserveListener::reserve_slashed`]
    fn on_reserve_slash(
        key: &Self::XpKey,
        reason: &Self::ReserveReason,
        slashed_points: Self::Points,
    ) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpReserveSlash {
                of: key.clone(),
                reason: *reason,
                xp: slashed_points,
            });
        }
        T::Extensions::reserve_slashed(key, reason, slashed_points);
    }
}

// ===============================================================================
// ``````````````````````````````````` XP LOCK ```````````````````````````````````
// ===============================================================================

/// Implementation of the `XpLock` trait for the XP pallet.
///
/// This provides the interface for issuing, managing, and burning XP locks, as well as querying lock state.
/// All methods are implemented in terms of the pallet's storage items and types.
///
impl<T: Config<I>, I: 'static> XpLock for Pallet<T, I> {
    /// The structure representing lock metadata (reason and locked XP amount).
    type Lock = IdXp<T::LockReason, T::Xp>;

    /// The lock reason identifier used to categorize locked XP points.
    type LockReason = T::LockReason;

    /// Checks if the given XP key has at least one active lock.
    ///
    /// This function verifies that the XP key has one or more active locks by
    /// checking if the locks vector is non-empty.
    ///
    /// ## Returns
    /// - `Ok(())` if the XP key has at least one active lock
    /// - `Err(DispatchError)` if no locks exist for the XP key
    fn has_lock(key: &Self::XpKey) -> DispatchResult {
        let Some(locks) = LockedXpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpLockNotFound.into());
        };
        if locks.len().is_zero() {
            return Err(Error::<T, I>::XpLockNotFound.into());
        }
        Ok(())
    }

    /// Checks if a lock exists for the given XP key and lock reason.
    ///
    /// ## Returns
    /// - `Ok(())` if the lock exists for the given key and reason
    /// - `Err(DispatchError)` if the lock does not exist
    fn lock_exists(key: &Self::XpKey, reason: &Self::LockReason) -> DispatchResult {
        let Some(locks) = LockedXpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpLockNotFound.into());
        };
        if !(locks.iter().any(|lock| lock.id == *reason)) {
            return Err(Error::<T, I>::XpLockNotFound.into());
        }
        Ok(())
    }

    /// Retrieves the XP points locked under the specified lock reason.
    ///
    /// This function returns the amount of XP points currently locked for a specific
    /// reason on the given XP key.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the locked XP points if found
    /// - `Err(DispatchError)` if the XP key or lock reason does not exist
    fn get_lock_xp(
        key: &Self::XpKey,
        reason: &Self::LockReason,
    ) -> Result<Self::Points, DispatchError> {
        let Some(locks) = LockedXpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpLockNotFound.into());
        };
        let Some(lock) = locks.iter().find(|lock| lock.id == *reason) else {
            return Err(Error::<T, I>::XpLockNotFound.into());
        };
        Ok(lock.points)
    }

    /// Retrieves the total XP points actively locked for the given key.
    ///
    /// This function returns the sum of all locked XP across all lock reasons
    /// for the specified XP key.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the total locked XP points if found
    /// - `Err(DispatchError)` if the XP key does not exist
    fn total_locked(key: &Self::XpKey) -> Result<Self::Points, DispatchError> {
        let Some(xp) = XpOf::<T, I>::get(key) else {
            return Err(Error::<T, I>::XpNotFound.into());
        };
        Ok(xp.lock)
    }

    /// Retrieves all active lock reasons associated with the XP key.
    ///
    /// This function returns a list of all lock reason identifiers currently
    /// active for the specified XP key.
    ///
    /// ## Returns
    /// - `Ok(Vec<Self::LockReason>)` containing all active lock reasons
    /// - Empty vector if no locks exist for the XP key
    fn get_all_locks(key: &Self::XpKey) -> Result<Vec<Self::LockReason>, DispatchError> {
        let all_locks = LockedXpOf::<T, I>::get(key)
            .map(|locks| locks.iter().map(|lock| lock.id).collect())
            .unwrap_or_default();
        Ok(all_locks)
    }

    /// Burns a lock and permanently removes the associated XP.
    ///
    /// This function removes both the lock entry and destroys the locked XP points.
    /// Used in scenarios like forfeiture, decay, or permanent commitment where
    /// the XP should be permanently removed from circulation.
    ///
    /// ## Returns
    /// - `Ok(())` if the lock was successfully burned
    /// - `Err(DispatchError)` for the respected error.
    fn burn_lock(key: &Self::XpKey, reason: &Self::LockReason) -> DispatchResult {
        let locked = Self::get_lock_xp(key, reason)?;
        LockedXpOf::<T, I>::mutate(key, |result| -> DispatchResult {
            let value = result.as_mut().ok_or(Error::<T, I>::XpLockNotFound)?;
            value.retain(|lock| lock.id != *reason);
            Ok(())
        })?;

        XpOf::<T, I>::mutate(key, |result| -> DispatchResult {
            let value = result.as_mut();

            debug_assert!(
                value.is_some(),
                "xp-key {key:?} lock of reason {reason:?} exists where as Xp Meta doesn't"
            );

            let value = value.ok_or(Error::<T, I>::XpNotFound)?;

            let total_locked = value.lock;
            // If proper XP management is not enforced, this may result in saturation and potentially cause
            // `xp.lock` (the total locked XP) to underflow. For example, unsafe use of `set_lock` or
            // missing pre-condition checks in the XP system can lead to this state.
            //
            // This creates "lock dust" (unrecoverable XP) that persists due to prior imprecise mutations.
            // Since each lock is burned using its stored `points` value (not derived from `total_locked`),
            // this dust is only cleaned up when *all* locks are eventually removed.
            if total_locked < locked {
                debug_assert!(
                    false,
                    "xp-key {key:?} lock of reason {reason:?} value {locked:?} is greater than xp's total lock value {total_locked:?}"
                );
                // If `total_locked < locked`, we explicitly reset `xp.lock` to zero to dispose residual dust
                // when the final lock is burned. This state is internal and not exposed to providers, so
                // external actors will not get affected by this.
                value.lock = Self::Points::zero();
                return Ok(());
            }
            value.lock = total_locked.saturating_sub(locked);
            Ok(())
        })?;
        Ok(())
    }

    /// Forcefully sets the locked XP for a specific lock reason.
    ///
    /// This function bypasses typical XP flow and permission checks, directly
    /// modifying lock state without enforcing invariants.
    ///
    /// Creates a new lock if none exists for the given reason, or updates an existing lock.
    ///
    /// Use with caution as this is intended for internal runtime operations such
    /// as migrations, resets, or exceptional administrative flows.
    ///
    /// ## Returns
    /// - `Ok(())` if the lock was successfully set
    /// - `Err(DispatchError)` if operation fails due to overflow or other constraints
    fn set_lock(
        key: &Self::XpKey,
        reason: &Self::LockReason,
        points: Self::Points,
    ) -> DispatchResult {
        // Creates a new lock if no lock exist for the given key and reason.
        if Self::lock_exists(key, reason).is_err() {
            // Permission and overflow checks are performed before creation to avoid inconsistent state.
            Self::can_lock_new(key, points)?;
            let lock = Self::Lock::new(*reason, points);

            LockedXpOf::<T, I>::mutate(key, |result| -> DispatchResult {
                let value = result.get_or_insert_with(|| {
                    BoundedVec::<Self::Lock, VariantCountOf<T::LockReason>>::default()
                });
                let result = value.try_push(lock);

                debug_assert!(
                    result.is_ok(),
                    "locks vector already bounded by reason, hence additional locks cannot be attempted itself,
                    inconsistency detected at set new lock of points {points:?} for xp-key {key:?} for reason {reason:?}"
                );

                result.map_err(|_| Error::<T, I>::TooManyLocks)?;

                Ok(())
            })?;

            XpOf::<T, I>::mutate(key, |result| -> DispatchResult {
                let value = result.as_mut();
                debug_assert!(
                    value.is_some(),
                    "xp-key {key:?} lock of reason {reason:?} newly created but Xp 
                    Meta not available to update high-level storage"
                );
                let value = value.ok_or(Error::<T, I>::XpNotFound)?;
                // May saturate. Any resulting lock dust will be cleaned up during lock
                // withdrawal, slashing, or burn operations when all lock points are
                // about to be removed.
                // Since its the provider, that sets the lock, it is not in context,
                // where XP points may come from, hence saturation is possible, but
                // recovered over time.
                value.lock = value.lock.saturating_add(points);

                Ok(())
            })?;
            return Ok(());
        }

        // Update an existing lock
        // Permission and overflow checks are performed before mutation to avoid inconsistent state.
        Self::can_lock_mutate(key, reason, points)?;
        LockedXpOf::<T, I>::mutate(key, |result| -> DispatchResult {
            let value = result.as_mut();
            debug_assert!(
                value.is_some(),
                "can mutate lock of xp-key {key:?} for reason {reason:?} but 
                cannot access the specific lock-meta",
            );
            let value = value.ok_or(Error::<T, I>::XpLockNotFound)?;
            // Convert WeakBoundedVec into a mutable slice to access its elements.
            let slice = &mut value[..];
            let lock = slice
                .iter_mut()
                .find(|lock| lock.id == *reason)
                .ok_or(Error::<T, I>::XpLockNotFound)?;
            let current_locked = lock.points;
            lock.points = points;

            XpOf::<T, I>::mutate(key, |result| -> DispatchResult {
                let value = result.as_mut();
                debug_assert!(
                    value.is_some(),
                    "xp-key {key:?} lock of reason {reason:?} recently mutated, but now Xp-meta 
                    not available to mutate"
                );
                let value = value.ok_or(Error::<T, I>::XpNotFound)?;

                let total_locked = value.lock;
                match current_locked.cmp(&points) {
                    Ordering::Greater => {
                        let decrease = current_locked.saturating_sub(points);
                        value.lock = total_locked.saturating_sub(decrease);
                    }
                    Ordering::Less => {
                        let increase = points.saturating_sub(current_locked);
                        value.lock = total_locked.saturating_add(increase);
                    }
                    Ordering::Equal => return Ok(()),
                }
                Ok(())
            })?;
            Ok(())
        })?;
        Ok(())
    }

    /// Hook invoked after a new XP lock is successfully created or mutated.
    ///
    /// Emits an `XpLock` event with the XP key, lock reason, and
    /// lock points if [`Config::EmitEvents`] is `true`.
    /// - Calls the Listener [`XpLockListener::lock_updated`]
    fn on_lock_update(key: &Self::XpKey, reason: &Self::LockReason, lock_points: Self::Points) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpLock {
                of: key.clone(),
                reason: *reason,
                xp: lock_points,
            });
        }
        Self::Extension::lock_updated(key, reason, lock_points);
    }

    /// Hook invoked after an XP lock is burned and permanently removed.
    ///
    /// Emits an `XpLockBurn` event with the XP key and lock reason
    /// if [`Config::EmitEvents`] is `true`.
    /// - Calls the Listener [`XpLockListener::lock_burned`]
    fn on_lock_burn(key: &Self::XpKey, reason: &Self::LockReason) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpLockBurn {
                of: key.clone(),
                reason: *reason,
            });
        }
        Self::Extension::lock_burned(key, reason);
    }

    /// Hook invoked after locked XP points are slashed.
    ///
    /// Emits an `XpLockSlash` event with the XP key, lock reason,
    /// and slashed points if [`Config::EmitEvents`] is `true`.
    /// - Calls the listener [`XpLockListener::lock_slashed`]
    fn on_lock_slash(key: &Self::XpKey, reason: &Self::LockReason, slashed_points: Self::Points) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpLockSlash {
                of: key.clone(),
                reason: *reason,
                xp: slashed_points,
            });
        }
        T::Extensions::lock_slashed(key, reason, slashed_points);
    }
}
// ===============================================================================
// ``````````````````````````````````` XP REAP ```````````````````````````````````
// ===============================================================================

/// Implementation of the `XpReap` trait for the XP pallet.
///
/// This provides the interface for finalizing (reaping) XP entries,
/// checking reaped status, and emitting reaping events. All methods
/// are implemented in terms of the pallet's storage items and types.
///
impl<T: Config<I>, I: 'static> XpReap for Pallet<T, I> {
    /// Reaps the given XP key, removing all associated data from storage.
    ///
    /// This irreversibly deletes the XP entry from [`XpOf`] and [`ReservedXpOf`],
    /// and marks the key in [`ReapedXp`] to prevent accidental recreation.
    ///
    /// Returns the total usable (liquid + reserved) XP points, which may be imprecise in
    /// edge cases involving overflow or ignored dust, since the system does not track
    /// total issuance.
    ///
    /// Reaping forcibly removes reserves regardless of their presence.
    ///
    /// ## Returns
    /// - `Ok(Points)` containing the total usable (liquid + reserved) XP points that were
    ///   reaped, which may be imprecise in edge cases involving overflow or ignored dust,
    ///   since the system does not track total issuance.
    /// - `Err(DispatchError)` if XP locks exist or the entry does not exist
    fn reap_xp(key: &Self::XpKey) -> Result<Self::Points, DispatchError> {
        // Also does early return while checking xp-key existance in the system
        let reapable = <Self as XpSystem>::get_usable_xp(key)?;
        // Shall not reap if locks are present, as it signifies
        // the XP is utilized by the runtime
        if <Self as XpLock>::has_lock(key).is_ok() {
            return Err(Error::<T, I>::XpLockExists.into());
        }
        XpOf::<T, I>::remove(key);
        ReservedXpOf::<T, I>::remove(key);
        ReapedXp::<T, I>::insert(key, ());
        Ok(reapable)
    }

    /// Checks if the given XP key has been reaped.
    ///
    /// Used as a guard against accidental recreation or mutation of finalized XP entries.
    ///
    /// ## Returns
    /// - `Ok(())` if the XP key has been reaped
    /// - `Err(DispatchError)` if the XP key has not been reaped
    fn is_reaped(key: &Self::XpKey) -> DispatchResult {
        if !ReapedXp::<T, I>::contains_key(key) {
            return Err(Error::<T, I>::XpNotReaped.into());
        }
        Ok(())
    }

    /// Hook invoked after an XP entry has been reaped.
    ///
    /// - Emits an `XpReap` event with the reaped XP key
    ///   if [`Config::EmitEvents`] is `true`.
    /// - Calls the Listener [`XpReapListener::xp_reaped`]
    fn on_xp_reap(key: &Self::XpKey) {
        if T::EmitEvents::get() {
            Self::deposit_event(Event::XpReap { id: key.clone() });
        }
        Self::Extension::xp_reaped(key);
    }
}

// ===============================================================================
// ````````````````````````````````` ACCUMULATOR `````````````````````````````````
// ===============================================================================

/// Implementation of the `DiscreteAccumulator` trait for the XP pallet.
///
/// This trait provides an abstraction for accumulator data structures that can be incremented or decremented
/// by discrete steps, while maintaining an internal state that can be revealed as a readable value.
///
/// The accumulator increases its value when enough fractional steps have been collected to reach the threshold.
/// Similarly, it decreases its value when enough steps are removed, handling underflow and overflow gracefully.
///
impl<T: Config<I>, I: 'static> DiscreteAccumulator for Pallet<T, I> {
    /// The value type being accumulated.
    type Value = T::Pulse;

    /// The step type representing fractional progress.
    type Step = T::Pulse;

    /// The accumulator structure holding the current value and step count.
    type Accumulator = Accumulator<T, I>;

    /// The stepper configuration, defining the threshold and per-step increment.
    type Stepper = Stepper<T, I>;

    /// Increments the accumulator by the stepper's per-count value.
    ///
    /// When the accumulated step reaches or exceeds the threshold, the value is increased by one
    /// and the step is reduced accordingly. Handles overflow gracefully using saturating arithmetic.
    fn increment(accum: &mut Self::Accumulator, stepper: &Self::Stepper) {
        accum.step = accum.step.saturating_add(stepper.per_count);
        while accum.step >= stepper.threshold {
            accum.value = accum.value.saturating_add(One::one());
            accum.step = accum.step.saturating_sub(stepper.threshold);
        }
    }

    /// Decrements the accumulator by the stepper's per-count value.
    ///
    /// If the current step is greater than or equal to the per-count, it simply subtracts per-count from the step.
    /// Otherwise, it calculates the deficit needed to maintain a non-negative step.
    ///
    /// If the `value` is > 0, subtract 1, and set `step` to deficit, else set `step` to 0.
    fn decrement(accum: &mut Self::Accumulator, stepper: &Self::Stepper) {
        if accum.step >= stepper.per_count {
            accum.step = accum.step.saturating_sub(stepper.per_count);
            return;
        }
        let sub_pos = stepper.per_count.saturating_sub(accum.step);
        let deficit = stepper.threshold.saturating_sub(sub_pos);
        if accum.value.is_zero() {
            accum.step = Zero::zero();
            return;
        }
        accum.value = accum.value.saturating_sub(One::one());
        accum.step = deficit;
    }

    /// Reveals the current accumulated value from the internal state.
    ///
    /// Returns the main value of the accumulator, ignoring the fractional step.
    fn reveal(accum: &Self::Accumulator) -> Self::Value {
        accum.value
    }
}

// ===============================================================================
// `````````````````````````````` XP ERROR HANDLER ```````````````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> XpErrorHandler for Pallet<T, I> {
    type Error = Error<T, I>;

    fn from_xp_error(e: XpError) -> Self::Error {
        match e {
            XpError::XpNotFound => Error::<T, I>::XpNotFound,
            XpError::XpReserveNotFound => Error::<T, I>::XpReserveNotFound,
            XpError::XpLockNotFound => Error::<T, I>::XpLockNotFound,
            XpError::InsufficientLiquidXp => Error::<T, I>::InsufficientLiquidXp,
            XpError::TooManyReserves => Error::<T, I>::TooManyReserves,
            XpError::TooManyLocks => Error::<T, I>::TooManyLocks,
            XpError::CannotLockZero => Error::<T, I>::CannotLockZero,
            XpError::CannotReserveZero => Error::<T, I>::CannotReserveZero,
            XpError::XpAlreadyReaped => Error::<T, I>::XpAlreadyReaped,
            XpError::XpNotDead => Error::<T, I>::XpNotDead,
            XpError::CannotReapLockedXp => Error::<T, I>::CannotReapLockedXp,
            XpError::InsufficientReserveXp => Error::<T, I>::InsufficientReserveXp,
            XpError::XpCapOverflowed => Error::<T, I>::XpCapOverflowed,
            XpError::XpCapUnderflowed => Error::<T, I>::XpCapUnderflowed,
            XpError::XpReserveCapOverflowed => Error::<T, I>::XpReserveCapOverflowed,
            XpError::XpReserveCapUnderflowed => Error::<T, I>::XpReserveCapUnderflowed,
            XpError::XpLockCapOverflowed => Error::<T, I>::XpLockCapOverflowed,
            XpError::XpLockCapUnderflowed => Error::<T, I>::XpLockCapUnderflowed,
        }
    }
}

// ===============================================================================
// `````````````````````````````````` UNIT TESTS `````````````````````````````````
// ===============================================================================

#[cfg(test)]
/// Unit tests for [`crate::xp`] trait implementations over [`Pallet`].
mod tests {

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ```````````````````````````````````` IMPORTS ``````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    // --- Local (module + crate) ---
    use crate::{mock::*, types::ForceGenesisConfig};

    // --- FRAME Suite ---
    use frame_suite::{accumulators::*, xp::*};

    // --- FRAME Support ---
    use frame_support::{
        assert_err, assert_ok,
        traits::{tokens::Precision, VariantCount, VariantCountOf},
    };
    use sp_runtime::BoundedVec;

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // `````````````````````````````````` XP SYSTEM ``````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn xp_exists_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_ok!(Pallet::xp_exists(&XP_ALPHA));
        });
    }

    #[test]
    fn xp_exists_fail_no_xp() {
        xp_test_ext().execute_with(|| {
            assert!(!XpOf::contains_key(XP_ALPHA));
        });
    }

    #[test]
    fn has_minimum_xp_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(1);
            System::set_block_number(2);
            System::set_block_number(3);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_ok!(Pallet::has_minimum_xp(&XP_ALPHA));
        });
    }

    #[test]
    fn has_minimum_xp_fail_low_min_time_stamp() {
        xp_test_ext().execute_with(|| {
            MinTimeStamp::set(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(1);
            assert_err!(Pallet::has_minimum_xp(&XP_ALPHA), Error::LowTimeStamp);
        });
    }

    #[test]
    fn get_xp_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(1);
            assert_err!(Pallet::get_xp(&XP_ALPHA), Error::XpNotFound);
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            assert_eq!(xp.free, InitXp::get());
            assert_eq!(xp.pulse.value, 0);
            assert_eq!(xp.reserve, 0);
            assert_eq!(xp.lock, 0);
            assert_eq!(xp.timestamp, 2);
        });
    }

    #[test]
    fn get_liquid_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let liquid = Pallet::get_liquid_xp(&XP_ALPHA).unwrap();
            assert_eq!(liquid, InitXp::get());
        });
    }

    #[test]
    fn get_liquid_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::get_liquid_xp(&XP_ALPHA), Error::XpNotFound);
        });
    }

    #[test]
    fn get_usable_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            ReservedXpOf::mutate(XP_ALPHA, |result| {
                let value = result.get_or_insert_with(|| {
                    BoundedVec::<ReserveId, VariantCountOf<Reason>>::default()
                });
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.reserve = value.reserve.saturating_add(DEFAULT_POINTS);
            });
            // Using get_xp as a helper function since its functionality has been validated in dedicated tests.
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let expected = xp.free.saturating_add(xp.reserve);
            let actual = Pallet::get_usable_xp(&XP_ALPHA).unwrap();
            assert_eq!(expected, actual);
        });
    }

    #[test]
    fn get_usable_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::get_usable_xp(&XP_ALPHA), Error::XpNotFound);
        });
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` XP OWNER ``````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn is_owner_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_ok!(Pallet::is_owner(&ALICE, &XP_ALPHA));
        });
    }

    #[test]
    fn is_owner_fail_not_owner() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::is_owner(&BOB, &XP_ALPHA), Error::InvalidXpOwner);
        });
    }

    #[test]
    fn xp_of_owner_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::new_xp(&ALICE, &XP_BETA);
            Pallet::new_xp(&ALICE, &XP_GAMMA);
            let actual = Pallet::xp_of_owner(&ALICE).unwrap();
            let expected = vec![XP_GAMMA, XP_ALPHA, XP_BETA];
            assert_eq!(actual, expected);
        });
    }

    #[test]
    fn transfer_owner_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(1);
            Pallet::transfer_owner(&ALICE, &XP_ALPHA, &BOB).unwrap();
            assert_err!(Pallet::is_owner(&ALICE, &XP_ALPHA), Error::InvalidXpOwner);
            assert_ok!(Pallet::is_owner(&BOB, &XP_ALPHA));
        });
    }

    #[test]
    fn xp_key_gen_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            Account::mutate(ALICE, |info| {
                info.nonce = 5;
            });
            let actual_gen_key = Pallet::xp_key_gen(&ALICE, &xp);
            assert!(actual_gen_key.is_ok());
            let actual_gen_key = actual_gen_key.unwrap();
            let expected_gen_key = 4150176476612258495;
            assert_eq!(actual_gen_key, expected_gen_key);
        });
    }

    #[test]
    fn xp_key_gen_deterministic_check() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            Account::mutate(ALICE, |info| {
                info.nonce = 3;
            });
            let gen_key_first = Pallet::xp_key_gen(&ALICE, &xp).unwrap();
            let gen_key_second = Pallet::xp_key_gen(&ALICE, &xp).unwrap();

            assert_eq!(gen_key_first, gen_key_second);
        });
    }

    #[test]
    fn xp_key_gen_collision_check() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp_alpha = Pallet::get_xp(&XP_ALPHA).unwrap();
            Account::mutate(ALICE, |info| {
                info.nonce = 3;
            });
            let gen_key_alpha = Pallet::xp_key_gen(&ALICE, &xp_alpha).unwrap();

            System::set_block_number(4);
            Pallet::new_xp(&BOB, &XP_BETA);
            let xp_beta = Pallet::get_xp(&XP_BETA).unwrap();
            Account::mutate(BOB, |info| {
                info.nonce = 1;
            });
            let gen_key_beta = Pallet::xp_key_gen(&ALICE, &xp_beta).unwrap();
            assert_ne!(xp_alpha, xp_beta);
            assert_ne!(System::account_nonce(ALICE), System::account_nonce(BOB));
            assert_ne!(gen_key_alpha, gen_key_beta);
        });
    }

    #[test]
    fn xp_key_gen_unique_across_owners() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::new_xp(&BOB, &XP_BETA);
            let xp_alpha = Pallet::get_xp(&XP_ALPHA).unwrap();
            let xp_beta = Pallet::get_xp(&XP_BETA).unwrap();
            Account::mutate(ALICE, |info| {
                info.nonce = 3;
            });
            Account::mutate(BOB, |info| {
                info.nonce = 3;
            });
            assert_eq!(xp_alpha, xp_beta);
            assert_eq!(System::account_nonce(ALICE), System::account_nonce(BOB));
            let gen_key_alice = Pallet::xp_key_gen(&ALICE, &xp_alpha).unwrap();
            let gen_key_bob = Pallet::xp_key_gen(&BOB, &xp_beta).unwrap();
            assert_ne!(gen_key_alice, gen_key_bob);
        });
    }

    #[test]
    fn xp_key_gen_unique_across_xp_struct() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp_1 = Pallet::get_xp(&XP_ALPHA).unwrap();
            Account::mutate(ALICE, |info| {
                info.nonce = 3;
            });
            System::set_block_number(4);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp_2 = Pallet::get_xp(&XP_ALPHA).unwrap();
            Account::mutate(ALICE, |info| {
                info.nonce = 3;
            });
            assert_ne!(xp_1, xp_2);
            assert_eq!(System::account_nonce(ALICE), 3);
            let gen_key_alice_1 = Pallet::xp_key_gen(&ALICE, &xp_1).unwrap();
            let gen_key_alice_2 = Pallet::xp_key_gen(&ALICE, &xp_2).unwrap();
            assert_ne!(gen_key_alice_1, gen_key_alice_2);
        });
    }

    #[test]
    fn xp_key_gen_unique_across_nonce() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            System::set_block_number(2);
            Account::mutate(ALICE, |info| {
                info.nonce = 3;
            });
            let gen_key_alice_1 = Pallet::xp_key_gen(&ALICE, &xp).unwrap();

            System::set_block_number(4);
            Account::mutate(ALICE, |info| {
                info.nonce = 5;
            });
            let gen_key_alice_2 = Pallet::xp_key_gen(&ALICE, &xp).unwrap();

            assert_ne!(gen_key_alice_1, gen_key_alice_2);
        });
    }

    #[test]
    fn on_xp_transfer_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(1);
            Pallet::on_xp_transfer(&XP_ALPHA, &BOB);
            System::assert_last_event(
                Event::XpOwner {
                    id: XP_ALPHA,
                    owner: BOB,
                }
                .into(),
            );
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // `````````````````````````````````` XP MUTATE ``````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn new_xp_success() {
        xp_test_ext().execute_with(|| {
            assert!(!XpOf::contains_key(XP_ALPHA));
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert!(XpOf::contains_key(XP_ALPHA));
            let xp = XpOf::get(XP_ALPHA).unwrap();
            assert_eq!(xp.free, 10);
            assert_eq!(xp.pulse.value, 0);
            assert_eq!(xp.reserve, 0);
            assert_eq!(xp.lock, 0);
            assert_eq!(xp.timestamp, 2);
            assert_eq!(XpOwners::get((ALICE, XP_ALPHA)), Some(()));
        });
    }

    #[test]
    fn earn_xp_success() {
        xp_test_ext().execute_with(|| {
            // Using new_xp as a helper function since its functionality has been validated in dedicated tests.
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp, 10);
            assert_eq!(pulse_xp, 0); // Default pulse is 0
            System::set_block_number(2);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //1
            System::set_block_number(3);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //2
            System::set_block_number(4);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //3
            System::set_block_number(5);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //4
            System::set_block_number(6);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //5
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp, 10);
            assert_eq!(pulse_xp, 1); // Increased by 1
            System::set_block_number(7);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap();
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp_bfr = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp_bfr, 20);
            assert_eq!(pulse_xp, 1);
            System::set_block_number(7);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap();
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp_aftr = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp_aftr, 30);
            assert_eq!(pulse_xp, 1);
            let actual = liquid_xp_aftr - liquid_xp_bfr;
            assert_eq!(actual, 10);
            System::assert_last_event(Event::XpEarn {
                 id: XP_ALPHA, 
                 xp: actual 
                }
                .into()
            );
        });
    }

    #[test]
    fn earn_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpNotFound
            )
        });
    }

    #[test]
    fn earn_xp_success_with_lock() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp, 10);
            assert_eq!(pulse_xp, 0); // Default pulse is 0
            System::set_block_number(2);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //1
            System::set_block_number(3);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //2
            System::set_block_number(4);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //3
            System::set_block_number(5);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //4
            System::set_block_number(6);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //5
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp, 10);
            assert_eq!(pulse_xp, 1); // Increased by 1
            System::set_block_number(7);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap();
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp, 20);
            assert_eq!(pulse_xp, 1);
            System::set_block_number(8);
            let idxp = LockId::new(STAKING, DEFAULT_POINTS);
            LockedXpOf::mutate(XP_ALPHA, |result| {
                let value = result
                    .get_or_insert_with(|| BoundedVec::<LockId, VariantCountOf<Reason>>::default());
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.lock = value.lock.saturating_add(DEFAULT_POINTS);
            });
            assert!(LockedXpOf::contains_key(XP_ALPHA));
            System::set_block_number(9);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //1
            System::set_block_number(10);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //2\
            System::set_block_number(11);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //3
            System::set_block_number(12);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //4
            System::set_block_number(13);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap(); //5
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp, 70);
            assert_eq!(pulse_xp, 2); // Increased to 2 due to lock exist
            System::set_block_number(14);
            Pallet::earn_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap();
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_xp = xp.free;
            let pulse_xp = xp.pulse.value;
            assert_eq!(liquid_xp, 90);
            assert_eq!(pulse_xp, 2);
        });
    }

    #[test]
    fn set_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(2);
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            assert_eq!(liquid_before, InitXp::get());
            System::set_block_number(3);
            Pallet::set_xp(&XP_ALPHA, DEFAULT_POINTS).unwrap();
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            assert_eq!(liquid_after, DEFAULT_POINTS);
        });
    }

    #[test]
    fn set_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::set_xp(&XP_ALPHA, DEFAULT_POINTS), Error::XpNotFound);
        });
    }

    #[test]
    fn on_xp_earn_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::on_xp_earn(&XP_ALPHA, DEFAULT_POINTS);
            System::assert_last_event(
                Event::XpEarn {
                    id: XP_ALPHA,
                    xp: DEFAULT_POINTS,
                }
                .into(),
            );
        });
    }

    #[test]
    fn on_xp_update_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::on_xp_update(&XP_ALPHA, DEFAULT_POINTS);
            System::assert_last_event(
                Event::Xp {
                    id: XP_ALPHA,
                    xp: DEFAULT_POINTS,
                }
                .into(),
            );
        });
    }

    #[test]
    fn slash_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            System::set_block_number(2);
            let slash_points = 5;
            assert_ok!(Pallet::slash_xp(&XP_ALPHA, slash_points));
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let liquid_expected = liquid_before.saturating_sub(slash_points);

            assert_eq!(liquid_after, liquid_expected);
            System::assert_last_event(
                Event::XpSlash {
                    id: XP_ALPHA,
                    xp: liquid_after,
                }
                .into(),
            );
        });
    }

    #[test]
    fn slash_xp_success_burn() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            assert_eq!(liquid_before, 10);
            System::set_block_number(2);
            // slash points > available liquid
            let slash_points = 20;
            assert_ok!(Pallet::slash_xp(&XP_ALPHA, slash_points));
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let liquid_expected = 0;

            assert_eq!(liquid_after, liquid_expected);
        });
    }

    #[test]
    fn slash_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::slash_xp(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn reset_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            let burn_points = Pallet::reset_xp(&XP_ALPHA).unwrap();
            let xp = XpOf::get(XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            assert_eq!(liquid_before, burn_points);
            assert_eq!(liquid_after, 0);
        });
    }

    #[test]
    fn reset_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::reset_xp(&XP_ALPHA), Error::XpNotFound);
        });
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // `````````````````````````````````` XP RESERVE `````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn reserve_exists_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            ReservedXpOf::mutate(XP_ALPHA, |result| {
                let value = result.get_or_insert_with(|| {
                    BoundedVec::<ReserveId, VariantCountOf<Reason>>::default()
                });
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.reserve = value.reserve.saturating_add(DEFAULT_POINTS);
            });
            assert_ok!(Pallet::reserve_exists(&XP_ALPHA, &STAKING));
        });
    }

    #[test]
    fn reserve_exists_fail() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::reserve_exists(&XP_ALPHA, &STAKING),
                Error::XpReserveNotFound
            );
        });
    }

    #[test]
    fn has_reserve_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            ReservedXpOf::mutate(XP_ALPHA, |result| {
                let value = result.get_or_insert_with(|| {
                    BoundedVec::<ReserveId, VariantCountOf<Reason>>::default()
                });
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.reserve = value.reserve.saturating_add(DEFAULT_POINTS);
            });
            assert_ok!(Pallet::has_reserve(&XP_ALPHA));
        });
    }

    #[test]
    fn has_reserve_fail_no_reserve() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::has_reserve(&XP_ALPHA), Error::XpReserveNotFound);
        });
    }

    #[test]
    fn has_reserve_fail_uninitialized_key() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::has_reserve(&XP_ALPHA), Error::XpReserveNotFound);
        });
    }

    #[test]
    fn maximum_reserves_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let max_reserves = Pallet::maximum_reserves();
            let expected = Reason::VARIANT_COUNT as usize;
            assert_eq!(max_reserves, expected);
        });
    }

    #[test]
    fn get_reserve_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            ReservedXpOf::mutate(XP_ALPHA, |result| {
                let value = result.get_or_insert_with(|| {
                    BoundedVec::<ReserveId, VariantCountOf<Reason>>::default()
                });
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.reserve = value.reserve.saturating_add(DEFAULT_POINTS);
            });
            let return_points = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(return_points, DEFAULT_POINTS);
        });
    }

    #[test]
    fn get_reserve_xp_fail_no_reserve() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::get_reserve_xp(&XP_ALPHA, &STAKING),
                Error::XpReserveNotFound
            );
        });
    }

    #[test]
    fn set_reserve_success_new() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            // Using has_reserve as a helper function since its functionality has been validated in dedicated tests.
            assert_err!(Pallet::has_reserve(&XP_ALPHA), Error::XpReserveNotFound);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::has_reserve(&XP_ALPHA));
            // Using get_reserve_xp as a helper function since its functionality has been validated in dedicated tests.
            let get_reserve_xp = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(get_reserve_xp, DEFAULT_POINTS);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let xp_reserved_points = xp.reserve;
            assert_eq!(DEFAULT_POINTS, xp_reserved_points);
        });
    }

    #[test]
    fn set_reserve_success_mutate_existing_xp() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let before_mutation = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(before_mutation, DEFAULT_POINTS);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let xp_reserved_points = xp.reserve;
            assert_eq!(DEFAULT_POINTS, xp_reserved_points);
            // increase
            let new_reserve_points = 25;
            Pallet::set_reserve(&XP_ALPHA, &STAKING, new_reserve_points).unwrap();
            let after_mutation = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(after_mutation, new_reserve_points);

            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let xp_reserved_points = xp.reserve;
            assert_eq!(new_reserve_points, xp_reserved_points);

            // decrease
            let new_reserve_points = 15;
            Pallet::set_reserve(&XP_ALPHA, &STAKING, new_reserve_points).unwrap();
            let after_mutation = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(after_mutation, new_reserve_points);

            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let xp_reserved_points = xp.reserve;
            assert_eq!(new_reserve_points, xp_reserved_points);
        });
    }

    #[test]
    fn set_reserve_fail_mutate_existing_xp_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            assert_err!(
                Pallet::set_reserve(&XP_ALPHA, &REASON_TREASURY, SATURATED_MAX),
                Error::XpReserveCapOverflowed
            );
        });
    }

    #[test]
    fn set_reserve_fail_new_reserve_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, SATURATED_MAX).unwrap();
            assert_err!(
                Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS),
                Error::XpReserveCapOverflowed
            )
        });
    }

    /// This scenario cannot be tested via the public API because the maximum number of reserves
    /// is enforced by the number of variants in the `Reason` enum (using `VariantCountOf`).
    /// Attempting to add more reserves than allowed is impossible, as each reason can only be used once,
    /// and reusing a reason will simply update the existing lock instead of creating a new one.
    /// Therefore, exceeding the reserve limit cannot be simulated in a test.
    #[test]
    fn set_reserve_fail_too_many_reserves() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::has_reserve(&XP_ALPHA), Error::XpReserveNotFound);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            // Mutates the existing reserve instead of returning Err(Error::TooManyReserves)
            Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
        });
    }

    #[test]
    fn set_reserve_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpNotFound
            )
        })
    }

    #[test]
    fn total_reserved_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            // Using set_reserve as a helper function since its functionality has been validated in dedicated tests.
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            let actual = Pallet::total_reserved(&XP_ALPHA).unwrap();
            let expected = DEFAULT_POINTS + DEFAULT_POINTS;
            assert_eq!(expected, actual);
        })
    }

    #[test]
    fn total_reserved_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::total_reserved(&XP_ALPHA), Error::XpNotFound);
        })
    }

    #[test]
    fn get_all_reserves_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            let actual = Pallet::get_all_reserves(&XP_ALPHA).unwrap();
            let expected = vec![STAKING, GOVERNANCE, REASON_TREASURY];
            assert_eq!(expected, actual);
        });
    }

    #[test]
    fn on_reserve_update_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(2);
            Pallet::on_reserve_update(&XP_ALPHA, &STAKING, DEFAULT_POINTS);
            System::assert_last_event(
                Event::XpReserve {
                    of: XP_ALPHA,
                    reason: STAKING,
                    xp: DEFAULT_POINTS,
                }
                .into(),
            );
        });
    }

    #[test]
    fn can_reserve_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            let reserve_points = 3;
            assert_ok!(Pallet::can_reserve_xp(&XP_ALPHA, reserve_points));
        });
    }

    #[test]
    fn can_reserve_xp_fail_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, SATURATED_MAX).unwrap();
            let reserve_points = 10;
            assert_err!(
                Pallet::can_reserve_xp(&XP_ALPHA, reserve_points),
                Error::XpReserveCapOverflowed
            );
        });
    }

    #[test]
    fn can_reserve_xp_fail_insufficient_liquid_xp() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let reserve_points = 20;
            assert_err!(
                Pallet::can_reserve_xp(&XP_ALPHA, reserve_points),
                Error::InsufficientLiquidXp
            );
        });
    }

    #[test]
    fn can_reserve_xp_fail_point_value_zero() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::can_reserve_xp(&XP_ALPHA, INVALID_POINTS),
                Error::CannotReserveZero
            );
        });
    }

    #[test]
    fn can_reserve_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::can_reserve_xp(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn can_reserve_mutate_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::can_reserve_mutate(
                &XP_ALPHA,
                &STAKING,
                DEFAULT_POINTS
            ));
        });
    }

    #[test]
    fn can_reserve_mutate_reserve_not_exist() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::can_reserve_mutate(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpReserveNotFound
            );
        });
    }

    #[test]
    fn can_reserve_mutate_fail_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            assert_err!(
                Pallet::can_reserve_mutate(&XP_ALPHA, &STAKING, SATURATED_MAX),
                Error::XpReserveCapOverflowed
            );
        });
    }

    #[test]
    fn can_reserve_new_fail_max_reserve() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_reserve(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();

            assert_err!(
                Pallet::can_reserve_new(&XP_ALPHA, DEFAULT_POINTS),
                Error::TooManyReserves
            );
        });
    }

    #[test]
    fn can_reserve_new_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();

            assert_ok!(Pallet::can_reserve_new(&XP_ALPHA, DEFAULT_POINTS));
        });
    }

    #[test]
    fn can_reserve_new_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::can_reserve_new(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn can_reserve_new_fail_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, SATURATED_MAX).unwrap();
            assert_err!(
                Pallet::can_reserve_new(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpReserveCapOverflowed
            );
        });
    }

    #[test]
    fn reserve_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            let reserve_before = xp.reserve;
            // Using reserve_exists as a helper function since its functionality has been validated in dedicated tests.
            assert_err!(
                Pallet::reserve_exists(&XP_ALPHA, &STAKING),
                Error::XpReserveNotFound
            );
            let reserve_points = 5;
            assert_ok!(Pallet::reserve_xp(&XP_ALPHA, &STAKING, reserve_points));
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let reserve_after = xp.reserve;
            let liquid_expected = liquid_before.saturating_sub(reserve_points);
            let reserve_expected = reserve_before.saturating_add(reserve_points);
            assert_ok!(Pallet::reserve_exists(&XP_ALPHA, &STAKING));
            assert_eq!(liquid_after, liquid_expected);
            assert_eq!(reserve_after, reserve_expected)
        });
    }

    #[test]
    fn reserve_xp_success_mutate() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&ALICE, &STAKING, DEFAULT_POINTS).unwrap();
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            let reserve_before = xp.reserve;
            assert_ok!(Pallet::reserve_exists(&XP_ALPHA, &STAKING));
            let reserve_points = 5;
            assert_ok!(Pallet::reserve_xp(&XP_ALPHA, &STAKING, reserve_points));
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let reserve_after = xp.reserve;
            let liquid_expected = liquid_before.saturating_sub(reserve_points);
            let reserve_expected = reserve_before.saturating_add(reserve_points);
            assert_eq!(liquid_after, liquid_expected);
            assert_eq!(reserve_after, reserve_expected)
        });
    }

    #[test]
    fn reserve_xp_fail_underflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let available_liquid = xp.free;
            assert_eq!(available_liquid, 10);
            // reserve point > available liquid
            let reserve_points = 25;
            assert_err!(
                Pallet::reserve_xp(&XP_ALPHA, &STAKING, reserve_points),
                Error::InsufficientLiquidXp
            );
        });
    }

    #[test]
    fn reserve_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::reserve_xp(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn reserve_xp_fail_mutate_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &GOVERNANCE, SATURATED_MAX).unwrap();
            assert_err!(
                Pallet::reserve_xp(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS),
                Error::XpReserveCapOverflowed
            );
        });
    }

    #[test]
    fn withdraw_reserve_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            let reserve_before = xp.reserve;
            assert_ok!(Pallet::reserve_exists(&XP_ALPHA, &STAKING));
            assert_ok!(Pallet::withdraw_reserve(&XP_ALPHA, &STAKING));
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let reserve_after = xp.reserve;
            let liquid_expected = liquid_before.saturating_add(reserve_before);
            let reserve_expected = liquid_before.saturating_sub(DEFAULT_POINTS);
            assert_eq!(liquid_after, liquid_expected);
            assert_eq!(reserve_after, reserve_expected);
        });
    }

    #[test]
    fn withdraw_reserve_fail_no_reserve_exist() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::withdraw_reserve(&XP_ALPHA, &STAKING),
                Error::XpReserveNotFound
            )
        });
    }

    #[test]
    fn withdraw_reserve_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::withdraw_reserve(&XP_ALPHA, &STAKING),
                Error::XpNotFound
            )
        });
    }

    #[test]
    fn slash_reserve_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let reserve_xp_before = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            let slash_points = 5;
            assert_ok!(Pallet::slash_reserve(&XP_ALPHA, &STAKING, slash_points));
            let reserve_xp_after = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            let reserve_xp_expected = reserve_xp_before.saturating_sub(slash_points);

            assert_eq!(reserve_xp_expected, reserve_xp_after);
        });
    }

    #[test]
    fn slash_reserve_success_burn() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let reserve_xp_before = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_ok!(Pallet::reserve_exists(&XP_ALPHA, &STAKING));
            let slash_points = 20;
            let burn_points = Pallet::slash_reserve(&XP_ALPHA, &STAKING, slash_points).unwrap();

            assert_err!(
                Pallet::lock_exists(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
            let reserve_xp_after = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();

            assert_eq!(reserve_xp_after, 0);
            assert_eq!(reserve_xp_before, burn_points);
        });
    }

    #[test]
    fn withdraw_reserve_partial_success_exact() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let reserve_before = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(reserve_before, DEFAULT_POINTS);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let free_before = xp.free;
            assert_eq!(free_before, DEFAULT_POINTS);
            let partial_withdraw = 6;
            Pallet::withdraw_reserve_partial(
                &XP_ALPHA,
                &STAKING,
                partial_withdraw,
                Precision::Exact,
            )
            .unwrap();
            let reserve_after = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            let expected_reserve = reserve_before.saturating_sub(partial_withdraw);
            assert_eq!(reserve_after, expected_reserve);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let free_after = xp.free;
            let expected_free = free_before.saturating_add(partial_withdraw);
            assert_eq!(free_after, expected_free);
        });
    }

    #[test]
    fn withdraw_reserve_partial_success_besteffort() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let reserve_before = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(reserve_before, DEFAULT_POINTS);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let free_before = xp.free;
            assert_eq!(free_before, DEFAULT_POINTS);
            let partial_withdraw = 11;
            Pallet::withdraw_reserve_partial(
                &XP_ALPHA,
                &STAKING,
                partial_withdraw,
                Precision::BestEffort,
            )
            .unwrap();
            let reserve_after = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            let expected_reserve = reserve_before.saturating_sub(partial_withdraw);
            assert_eq!(reserve_after, expected_reserve);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let free_after = xp.free;
            let expected_free = 20;
            assert_eq!(free_after, expected_free);
        });
    }

    #[test]
    fn withdraw_reserve_partial_success_with_zero() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::withdraw_reserve_partial(
                &XP_ALPHA,
                &STAKING,
                INVALID_POINTS,
                Precision::Exact
            ));
        });
    }

    #[test]
    fn withdraw_reserve_partial_fail_exact() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let reserve_before = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(reserve_before, DEFAULT_POINTS);
            let partial_withdraw = 11;
            assert_err!(
                Pallet::withdraw_reserve_partial(
                    &XP_ALPHA,
                    &STAKING,
                    partial_withdraw,
                    Precision::Exact
                ),
                Error::InsufficientReserveXp
            )
        });
    }

    #[test]
    fn withdraw_reserve_partial_fail_no_reserve() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::withdraw_reserve_partial(
                    &XP_ALPHA,
                    &STAKING,
                    DEFAULT_POINTS,
                    Precision::Exact
                ),
                Error::XpReserveNotFound
            )
        });
    }

    #[test]
    fn withdraw_reserve_partial_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::withdraw_reserve_partial(
                    &XP_ALPHA,
                    &STAKING,
                    DEFAULT_POINTS,
                    Precision::Exact
                ),
                Error::XpNotFound
            )
        });
    }

    #[test]
    fn slash_reserve_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::slash_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpNotFound
            )
        });
    }

    #[test]
    fn slash_reserve_fail_no_reserve_exist() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::slash_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpReserveNotFound
            )
        });
    }

    #[test]
    fn reset_reserve_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_reserve(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let reserve_xp_before = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_ok!(Pallet::reserve_exists(&XP_ALPHA, &STAKING));
            let burn_points = Pallet::reset_reserve(&XP_ALPHA, &STAKING).unwrap();

            assert_err!(
                Pallet::lock_exists(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
            let reserve_xp_after = Pallet::get_reserve_xp(&XP_ALPHA, &STAKING).unwrap();

            assert_eq!(reserve_xp_after, 0);
            assert_eq!(reserve_xp_before, burn_points);
        });
    }

    #[test]
    fn reset_reserve_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::reset_reserve(&XP_ALPHA, &STAKING),
                Error::XpNotFound
            )
        });
    }

    #[test]
    fn reset_reserve_fail_no_reserve_exist() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::reset_reserve(&XP_ALPHA, &STAKING),
                Error::XpReserveNotFound
            )
        });
    }

    // ===============================================================================
    // ``````````````````````````````````` XP LOCK ```````````````````````````````````
    // ===============================================================================

    #[test]
    fn has_lock_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = LockId::new(STAKING, DEFAULT_POINTS);
            LockedXpOf::mutate(XP_ALPHA, |result| {
                let value = result
                    .get_or_insert_with(|| BoundedVec::<LockId, VariantCountOf<Reason>>::default());
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.lock = value.lock.saturating_add(DEFAULT_POINTS);
            });
            assert_ok!(Pallet::has_lock(&XP_ALPHA));
        });
    }

    #[test]
    fn has_lock_fail() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::has_lock(&XP_ALPHA), Error::XpLockNotFound);
        });
    }

    #[test]
    fn has_lock_fail_uninitialized_key() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::has_lock(&XP_ALPHA), Error::XpLockNotFound);
        });
    }

    #[test]
    fn get_lock_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = LockId::new(STAKING, DEFAULT_POINTS);
            LockedXpOf::mutate(XP_ALPHA, |result| {
                let value = result
                    .get_or_insert_with(|| BoundedVec::<LockId, VariantCountOf<Reason>>::default());
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.lock = value.lock.saturating_add(DEFAULT_POINTS);
            });
            let get_lock_xp = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(get_lock_xp, DEFAULT_POINTS);
        });
    }

    #[test]
    fn get_lock_xp_fail_no_lock() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::get_lock_xp(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
        });
    }

    #[test]
    fn set_lock_success_new() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            // Using has_lock as a helper function since its functionality has been validated in dedicated tests.
            assert_err!(Pallet::has_lock(&XP_ALPHA), Error::XpLockNotFound);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::has_lock(&XP_ALPHA));
            // Using get_lock_xp as a helper function since its functionality has been validated in dedicated tests.
            let get_lock_xp = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(get_lock_xp, DEFAULT_POINTS);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let xp_locked_points = xp.lock;
            assert_eq!(DEFAULT_POINTS, xp_locked_points);
        });
    }

    #[test]
    fn set_lock_success_mutate_existing_xp() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let before_mutation = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(before_mutation, DEFAULT_POINTS);
            // increase
            let new_lock_points = 25;
            Pallet::set_lock(&XP_ALPHA, &STAKING, new_lock_points).unwrap();
            let after_mutation = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(after_mutation, new_lock_points);
            // decrease
            let new_lock_points = 15;
            Pallet::set_lock(&XP_ALPHA, &STAKING, new_lock_points).unwrap();
            let after_mutation = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_eq!(after_mutation, new_lock_points);
        });
    }

    #[test]
    fn set_lock_fail_mutate_existing_xp_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            assert_err!(
                Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, SATURATED_MAX),
                Error::XpLockCapOverflowed
            );
        });
    }

    #[test]
    fn set_lock_fail_new_lock_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, SATURATED_MAX).unwrap();
            assert_err!(
                Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS),
                Error::XpLockCapOverflowed
            )
        });
    }

    #[test]
    fn set_lock_fail_points_value_zero() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::has_lock(&XP_ALPHA), Error::XpLockNotFound);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::has_lock(&XP_ALPHA));
            assert_err!(
                Pallet::set_lock(&XP_ALPHA, &STAKING, INVALID_POINTS),
                Error::CannotLockZero
            );
        });
    }

    /// This scenario cannot be tested via the public API because the maximum number of locks
    /// is enforced by the number of variants in the `Reason` enum (using `VariantCountOf`).
    /// Attempting to add more locks than allowed is impossible, as each reason can only be used once,
    /// and reusing a reason will simply update the existing lock instead of creating a new one.
    /// Therefore, exceeding the lock limit cannot be simulated in a test.
    #[test]
    fn set_lock_fail_too_many_locks() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::has_lock(&XP_ALPHA), Error::XpLockNotFound);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
        });
    }

    #[test]
    fn set_lock_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn lock_exists_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            // Using set_lock as a helper function since its functionality has been validated in dedicated tests.
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::lock_exists(&XP_ALPHA, &STAKING));
        });
    }

    #[test]
    fn lock_exists_fail_no_locks() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::lock_exists(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
        });
    }

    #[test]
    fn maximum_locks_success() {
        xp_test_ext().execute_with(|| {
            let max_locks: usize = Pallet::maximum_locks();
            let expected = Reason::VARIANT_COUNT as usize;
            assert_eq!(max_locks, expected);
        });
    }

    #[test]
    fn total_locked_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            let actual_locked = Pallet::total_locked(&XP_ALPHA).unwrap();
            let expected_locked = DEFAULT_POINTS + DEFAULT_POINTS;
            assert_eq!(expected_locked, actual_locked);
        });
    }

    #[test]
    fn total_locked_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::total_locked(&XP_ALPHA), Error::XpNotFound);
        })
    }

    #[test]
    fn get_all_locks_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            let actual = Pallet::get_all_locks(&XP_ALPHA).unwrap();
            let expected = vec![Reason::Staking, Reason::Governance, Reason::Treasury];
            assert_eq!(actual, expected);
        });
    }

    #[test]
    fn burn_lock_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(2);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            // Using lock_exists as a helper function since its functionality has been validated in dedicated tests.
            assert_ok!(Pallet::lock_exists(&XP_ALPHA, &STAKING));
            assert_ok!(Pallet::burn_lock(&XP_ALPHA, &STAKING));
            assert_err!(
                Pallet::lock_exists(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
        });
    }

    /// This scenario cannot be tested via the public API because the "lock dust" (underflow)
    /// condition requires creating an inconsistent internal state, where the XP's `lock` field
    /// is less than the points of the lock being burned. Since all fields are private and the
    /// public API always keeps the state consistent, this edge case cannot be simulated in a test.
    #[test]
    fn burn_lock_underflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            let lock_xp = Pallet::get_lock_xp(&XP_ALPHA, &REASON_TREASURY).unwrap();
            assert_eq!(lock_xp, DEFAULT_POINTS);
            Pallet::burn_lock(&XP_ALPHA, &REASON_TREASURY).unwrap();
            // Burns an entire lock id of a given key
            assert_err!(
                Pallet::get_lock_xp(&XP_ALPHA, &REASON_TREASURY),
                Error::XpLockNotFound
            );
        });
    }

    #[test]
    fn burn_lock_fail_no_valid_lock_id() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::burn_lock(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            )
        });
    }

    #[test]
    fn burn_lock_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::burn_lock(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            )
        });
    }

    #[test]
    fn on_lock_update_success() {
        xp_test_ext().execute_and_prove(|| {
            System::set_block_number(2);
            Pallet::on_lock_update(&XP_ALPHA, &STAKING, DEFAULT_POINTS);
            System::assert_last_event(
                Event::XpLock {
                    of: XP_ALPHA,
                    reason: STAKING,
                    xp: DEFAULT_POINTS,
                }
                .into(),
            );
        });
    }

    #[test]
    fn on_lock_burn_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(1);
            Pallet::on_lock_burn(&XP_ALPHA, &STAKING);
            System::assert_last_event(
                Event::XpLockBurn {
                    of: XP_ALPHA,
                    reason: STAKING,
                }
                .into(),
            );
        });
    }

    #[test]
    fn can_lock_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let lock_points = 3;
            assert_ok!(Pallet::can_lock_xp(&XP_ALPHA, lock_points));
        });
    }

    #[test]
    fn can_lock_xp_fail_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, SATURATED_MAX).unwrap();
            let lock_points = 3;
            assert_err!(
                Pallet::can_lock_xp(&XP_ALPHA, lock_points),
                Error::XpLockCapOverflowed
            );
        });
    }

    #[test]
    fn can_lock_xp_fail_insufficient_liquid_xp() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let lock_points = 20;
            assert_err!(
                Pallet::can_lock_xp(&XP_ALPHA, lock_points),
                Error::InsufficientLiquidXp
            );
        });
    }

    #[test]
    fn can_lock_xp_fail_point_value_zero() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);

            assert_err!(
                Pallet::can_lock_xp(&XP_ALPHA, INVALID_POINTS),
                Error::CannotLockZero
            );
        });
    }

    #[test]
    fn can_lock_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::can_lock_xp(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn can_lock_mutate_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::can_lock_mutate(&XP_ALPHA, &STAKING, DEFAULT_POINTS));
        });
    }

    #[test]
    fn can_lock_mutate_lock_not_exist() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::can_lock_mutate(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpLockNotFound
            );
        });
    }

    #[test]
    fn can_lock_mutate_fail_point_value_zero() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            assert_err!(
                Pallet::can_lock_mutate(&XP_ALPHA, &STAKING, INVALID_POINTS),
                Error::CannotLockZero
            );
        });
    }

    #[test]
    fn can_lock_mutate_fail_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            assert_err!(
                Pallet::can_lock_mutate(&XP_ALPHA, &STAKING, SATURATED_MAX),
                Error::XpLockCapOverflowed
            );
        });
    }

    #[test]
    fn can_lock_new_fail_max_lock() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &REASON_TREASURY, DEFAULT_POINTS).unwrap();
            Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS).unwrap();
            assert_err!(
                Pallet::can_lock_new(&XP_ALPHA, DEFAULT_POINTS),
                Error::TooManyLocks
            );
        });
    }

    #[test]
    fn can_lock_new_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();

            assert_ok!(Pallet::can_lock_new(&XP_ALPHA, DEFAULT_POINTS));
        });
    }

    #[test]
    fn can_lock_new_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::can_lock_new(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn can_lock_new_fail_with_zero() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::can_lock_new(&XP_ALPHA, INVALID_POINTS),
                Error::CannotLockZero,
            );
        });
    }

    #[test]
    fn can_lock_new_fail_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, SATURATED_MAX).unwrap();
            assert_err!(
                Pallet::can_lock_new(&XP_ALPHA, DEFAULT_POINTS),
                Error::XpLockCapOverflowed
            );
        });
    }

    #[test]
    fn lock_xp_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            let lock_before = xp.lock;
            assert_err!(
                Pallet::lock_exists(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
            let lock_points = 5;
            assert_ok!(Pallet::lock_xp(&XP_ALPHA, &STAKING, lock_points));
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let lock_after = xp.lock;
            let liquid_expected = liquid_before.saturating_sub(lock_points);
            let lock_expected = lock_before.saturating_add(lock_points);
            assert_ok!(Pallet::lock_exists(&XP_ALPHA, &STAKING));
            assert_eq!(liquid_after, liquid_expected);
            assert_eq!(lock_after, lock_expected)
        });
    }

    #[test]
    fn lock_xp_success_mutate() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&ALICE, &STAKING, DEFAULT_POINTS).unwrap();
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            let lock_before = xp.lock;
            assert_ok!(Pallet::lock_exists(&XP_ALPHA, &STAKING));
            let lock_points = 5;
            assert_ok!(Pallet::lock_xp(&XP_ALPHA, &STAKING, lock_points));
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let lock_after = xp.lock;
            let liquid_expected = liquid_before.saturating_sub(lock_points);
            let lock_expected = lock_before.saturating_add(lock_points);
            assert_eq!(liquid_after, liquid_expected);
            assert_eq!(lock_after, lock_expected);
        });
    }

    #[test]
    fn lock_xp_fail_underflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let available_liquid = xp.free;
            assert_eq!(available_liquid, 10);
            // lock points > available liquid
            let lock_points = 25;
            assert_err!(
                Pallet::lock_xp(&XP_ALPHA, &STAKING, lock_points),
                Error::InsufficientLiquidXp
            );
        });
    }

    #[test]
    fn lock_xp_fail_mutate_overflow() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &GOVERNANCE, SATURATED_MAX).unwrap();
            assert_err!(
                Pallet::lock_xp(&XP_ALPHA, &GOVERNANCE, DEFAULT_POINTS),
                Error::XpLockCapOverflowed
            );
        });
    }

    #[test]
    fn lock_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::lock_xp(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpNotFound
            );
        });
    }

    #[test]
    fn lock_xp_fail_points_value_zero() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::lock_xp(&XP_ALPHA, &STAKING, INVALID_POINTS),
                Error::CannotLockZero
            );
        });
    }

    #[test]
    fn withdraw_lock_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_before = xp.free;
            Pallet::set_lock(&ALICE, &STAKING, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::lock_exists(&XP_ALPHA, &STAKING));
            assert_ok!(Pallet::withdraw_lock(&ALICE, &STAKING));
            let xp = Pallet::get_xp(&XP_ALPHA).unwrap();
            let liquid_after = xp.free;
            let liquid_expected = liquid_before.saturating_add(DEFAULT_POINTS);

            assert_err!(
                Pallet::lock_exists(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
            assert_eq!(liquid_expected, liquid_after);
        });
    }

    #[test]
    fn withdraw_lock_fail_no_lock_exist() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::withdraw_lock(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            )
        });
    }

    #[test]
    fn withdraw_lock_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::withdraw_lock(&XP_ALPHA, &STAKING),
                Error::XpNotFound
            )
        });
    }

    #[test]
    fn slash_lock_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let lock_xp_before = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            let slash_points = 5;
            assert_ok!(Pallet::slash_lock(&XP_ALPHA, &STAKING, slash_points));
            let lock_xp_after = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            let lock_xp_expected = lock_xp_before.saturating_sub(slash_points);

            assert_eq!(lock_xp_expected, lock_xp_after);
        });
    }

    #[test]
    fn slash_lock_success_burn() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::set_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS).unwrap();
            let lock_xp_before = Pallet::get_lock_xp(&XP_ALPHA, &STAKING).unwrap();
            assert_ok!(Pallet::lock_exists(&XP_ALPHA, &STAKING));
            let slash_points = 20;
            let burn_points = Pallet::slash_lock(&XP_ALPHA, &STAKING, slash_points).unwrap();

            assert_eq!(lock_xp_before, burn_points);
            assert_err!(
                Pallet::lock_exists(&XP_ALPHA, &STAKING),
                Error::XpLockNotFound
            );
        });
    }

    #[test]
    fn slash_lock_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(
                Pallet::slash_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpNotFound
            )
        });
    }

    #[test]
    fn slash_lock_fail_no_lock_exist() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::slash_lock(&XP_ALPHA, &STAKING, DEFAULT_POINTS),
                Error::XpLockNotFound
            )
        });
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` XP REAP ```````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn reap_xp_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(2);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            ReservedXpOf::mutate(XP_ALPHA, |result| {
                let value = result.get_or_insert_with(|| {
                    BoundedVec::<ReserveId, VariantCountOf<Reason>>::default()
                });
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.reserve = value.reserve.saturating_add(DEFAULT_POINTS);
            });
            assert!(ReservedXpOf::contains_key(XP_ALPHA));
            System::set_block_number(3);
            // Using get_usable_xp as a helper function since its functionality has
            // been validated in dedicated tests.
            let usable_xp = Pallet::get_usable_xp(&XP_ALPHA).unwrap();
            let reap_points = Pallet::reap_xp(&XP_ALPHA).unwrap();
            assert!(!ReservedXpOf::contains_key(XP_ALPHA));
            assert_eq!(usable_xp, reap_points);
        });
    }

    #[test]
    fn reap_xp_fail_lock_exists() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            LockedXpOf::mutate(XP_ALPHA, |result| {
                let value = result
                    .get_or_insert_with(|| BoundedVec::<LockId, VariantCountOf<Reason>>::default());
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.lock = value.lock.saturating_add(DEFAULT_POINTS);
            });
            assert!(LockedXpOf::contains_key(XP_ALPHA));
            assert_err!(Pallet::reap_xp(&XP_ALPHA), Error::XpLockExists);
        });
    }

    #[test]
    fn reap_xp_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            // Using xp_exists as a helper function since its functionality
            // has been validated in dedicated tests.
            assert_err!(Pallet::xp_exists(&XP_ALPHA), Error::XpNotFound);
            assert_err!(Pallet::reap_xp(&XP_ALPHA), Error::XpNotFound);
        });
    }

    #[test]
    fn is_reaped_success() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            // Using reap_xp as a helper function since its functionality has
            // been validated in dedicated tests.
            Pallet::reap_xp(&XP_ALPHA).unwrap();
            assert_ok!(Pallet::is_reaped(&XP_ALPHA));
        });
    }

    #[test]
    fn is_reaped_fail() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::is_reaped(&XP_ALPHA), Error::XpNotReaped);
        });
    }

    #[test]
    fn on_xp_reap_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::on_xp_reap(&XP_ALPHA);
            System::assert_last_event(Event::XpReap { id: XP_ALPHA }.into());
        });
    }

    // ReapSupport

    #[test]
    fn can_reap_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(4);
            System::set_block_number(6);
            System::set_block_number(8);
            System::set_block_number(10);
            Pallet::force_genesis_config(
                RuntimeOrigin::root(),
                ForceGenesisConfig::MinTimeStamp(10),
            )
            .unwrap();
            System::set_block_number(12);
            assert_ok!(Pallet::can_reap(&XP_ALPHA));
        });
    }

    #[test]
    fn can_reap_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::can_reap(&XP_ALPHA), Error::XpNotFound);
        });
    }

    #[test]
    fn can_reap_fail_already_reaped() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::reap_xp(&XP_ALPHA).unwrap();
            assert_err!(Pallet::can_reap(&XP_ALPHA), Error::XpAlreadyReaped,);
        });
    }

    #[test]
    fn can_reap_fail_not_dead() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::can_reap(&XP_ALPHA), Error::XpNotDead,);
        });
    }

    #[test]
    fn can_reap_fail_lock_exists() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            LockedXpOf::mutate(XP_ALPHA, |result| {
                let value = result
                    .get_or_insert_with(|| BoundedVec::<LockId, VariantCountOf<Reason>>::default());
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.lock = value.lock.saturating_add(DEFAULT_POINTS);
            });
            assert!(LockedXpOf::contains_key(XP_ALPHA));
            System::set_block_number(6);
            System::set_block_number(10);
            System::set_block_number(12);
            Pallet::force_genesis_config(
                RuntimeOrigin::root(),
                ForceGenesisConfig::MinTimeStamp(10),
            )
            .unwrap();
            assert_err!(Pallet::can_reap(&XP_ALPHA), Error::CannotReapLockedXp,);
        });
    }

    #[test]
    fn try_reap_success() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            System::set_block_number(4);
            System::set_block_number(6);
            System::set_block_number(8);
            System::set_block_number(10);
            Pallet::force_genesis_config(
                RuntimeOrigin::root(),
                ForceGenesisConfig::MinTimeStamp(10),
            )
            .unwrap();
            System::set_block_number(12);
            assert_ok!(Pallet::try_reap(&XP_ALPHA));
            assert_ok!(Pallet::is_reaped(&XP_ALPHA));
        });
    }

    #[test]
    fn try_reap_fail_uninitialized_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::try_reap(&XP_ALPHA), Error::XpNotFound);
        });
    }

    #[test]
    fn try_reap_fail_already_reaped() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::reap_xp(&XP_ALPHA).unwrap();
            assert_err!(Pallet::try_reap(&XP_ALPHA), Error::XpAlreadyReaped,);
        });
    }

    #[test]
    fn try_reap_fail_not_dead() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(Pallet::try_reap(&XP_ALPHA), Error::XpNotDead,);
        });
    }

    #[test]
    fn try_reap_fail_lock_exists() {
        xp_test_ext().execute_with(|| {
            System::set_block_number(2);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            let idxp = ReserveId::new(STAKING, DEFAULT_POINTS);
            LockedXpOf::mutate(XP_ALPHA, |result| {
                let value = result
                    .get_or_insert_with(|| BoundedVec::<LockId, VariantCountOf<Reason>>::default());
                value.try_push(idxp).unwrap();
            });
            XpOf::mutate(XP_ALPHA, |result| {
                let value = result.as_mut().unwrap();
                value.lock = value.lock.saturating_add(DEFAULT_POINTS);
            });
            assert!(LockedXpOf::contains_key(XP_ALPHA));
            System::set_block_number(6);
            System::set_block_number(10);
            System::set_block_number(12);
            Pallet::force_genesis_config(
                RuntimeOrigin::root(),
                ForceGenesisConfig::MinTimeStamp(10),
            )
            .unwrap();
            assert_err!(Pallet::try_reap(&XP_ALPHA), Error::CannotReapLockedXp,);
        });
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` BEGIN XP ``````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn begin_xp_success_new_xp() {
        xp_test_ext().execute_with(|| {
            assert_err!(Pallet::xp_exists(&XP_ALPHA), Error::XpNotFound);
            Pallet::begin_xp(&ALICE, &XP_ALPHA, DEFAULT_POINTS).unwrap();
            assert_ok!(Pallet::xp_exists(&XP_ALPHA));
        });
    }

    #[test]
    fn begin_xp_success_earn_xp() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_ok!(Pallet::begin_xp(&ALICE, &XP_ALPHA, DEFAULT_POINTS));
        });
    }

    #[test]
    fn begin_xp_fail_reaped() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::reap_xp(&XP_ALPHA).unwrap();
            assert_err!(Pallet::xp_exists(&XP_ALPHA), Error::XpNotFound);
            assert_err!(
                Pallet::begin_xp(&ALICE, &XP_ALPHA, DEFAULT_POINTS),
                Error::XpAlreadyReaped
            );
            assert_err!(Pallet::xp_exists(&XP_ALPHA), Error::XpNotFound);
        });
    }

    #[test]
    fn begin_xp_fail_already_reaped() {
        xp_test_ext().execute_with(|| {
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            Pallet::reap_xp(&XP_ALPHA).unwrap();
            assert_err!(Pallet::xp_exists(&XP_ALPHA), Error::XpNotFound);
            Pallet::new_xp(&ALICE, &XP_ALPHA);
            assert_err!(
                Pallet::begin_xp(&ALICE, &XP_ALPHA, DEFAULT_POINTS),
                Error::XpAlreadyReaped
            );
        });
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ````````````````````````````` DISCRETE ACCUMULATOR ````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn increment_basic_success() {
        xp_test_ext().execute_with(|| {
            let mut accum = Accumulator::default();
            let stepper = Stepper::new(1000u32, 250u32).unwrap(); // 0.25 fraction
            Pallet::increment(&mut accum, &stepper);
            assert_eq!(accum.value, 0);
            assert_eq!(accum.step, 250);
            Pallet::increment(&mut accum, &stepper);
            assert_eq!(accum.value, 0);
            assert_eq!(accum.step, 500);
            Pallet::increment(&mut accum, &stepper);
            assert_eq!(accum.value, 0);
            assert_eq!(accum.step, 750);
            Pallet::increment(&mut accum, &stepper);
            assert_eq!(accum.value, 1);
            assert_eq!(accum.step, 0);
        });
    }

    #[test]
    fn increment_overflow_success() {
        xp_test_ext().execute_with(|| {
            let mut accum = Accumulator::default();
            let stepper = Stepper::new(1000u32, 350u32).unwrap();
            Pallet::increment(&mut accum, &stepper);
            assert_eq!(accum.value, 0);
            assert_eq!(accum.step, 350);
            Pallet::increment(&mut accum, &stepper);
            assert_eq!(accum.value, 0);
            assert_eq!(accum.step, 700);

            Pallet::increment(&mut accum, &stepper);
            assert_eq!(accum.value, 1);
            assert_eq!(accum.step, 50);
        });
    }

    #[test]
    fn decrement_basic_success() {
        xp_test_ext().execute_with(|| {
            let mut accum = Accumulator {
                value: 2,
                step: 300,
            };
            let stepper = Stepper::new(1000u32, 200u32).unwrap();
            Pallet::decrement(&mut accum, &stepper);
            assert_eq!(accum.value, 2);
            assert_eq!(accum.step, 100);
        });
    }

    #[test]
    fn decrement_underflow_success() {
        xp_test_ext().execute_with(|| {
            let mut accum = Accumulator { value: 2, step: 0 };
            let stepper = Stepper::new(1000u32, 200u32).unwrap(); // 0.2 fraction
            Pallet::decrement(&mut accum, &stepper);
            assert_eq!(accum.value, 1);
            assert_eq!(accum.step, 800);
        });
    }

    #[test]
    fn new_frac_fail() {
        xp_test_ext().execute_with(|| {
            assert!(Stepper::new(100u32, 150u32).is_none());
        });
    }
}