pallet-commitment 0.1.2

A FRAME pallet for reusable, abstract bonding primitives with structured, indexed, and pooled value allocations.
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
// 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

// ===============================================================================
// ``````````````````````````````` COMMITMENT TYPES ``````````````````````````````
// ===============================================================================

//! **Core types and aliases for the Commitment system.**
//!
//! This module defines the primary structures and type aliases used by
//! [`pallet_commitment`](crate). These types are publicly exposed and used across
//! the pallet's APIs for representing Commitment-related data.
//!
//! Trait implementations provided by this crate's [`crate::Pallet`] can use these types
//! via trait-bound equality constraints to ensure type alignment with this pallet's
//! concrete implementations if necessary.
//!
//! ## Invariants & Access
//!
//! All structures in this module encapsulate their fields as private to enforce
//! invariants during creation, mutation, and access. As a result, interaction with
//! these types is performed exclusively through inherent methods, which provide
//! both internal mutation capabilities and safe external (read/query) access.
//!
//! ## Example
//!
//! ```ignore
//! mod pallet {
//!     use pallet_commitment::types::IndexInfo;
//!
//!     pub trait Config<I: 'static>: frame_system::Config {
//!         type CommitmentAdapter: CommitIndex<Index = IndexInfo<Self, I>>;
//!     }
//! }
//! ```

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

// --- Local crate imports ---
use crate::{balance::ProductType, Config, Error};

// --- Core ---
use core::{fmt::Debug, marker::PhantomData};

// --- Scale-codec crates ---
use codec::DecodeWithMemTracking;
use scale_info::{prelude::vec, TypeInfo};

// --- Derive Macros ---
use derive_more::Constructor;

// --- FRAME Suite ---
use frame_suite::{assets::*, misc::PositionIndex, plugins::ModelContext};

// --- FRAME Support ---
use frame_support::{
    dispatch::DispatchResult,
    ensure,
    traits::{
        fungible::{Inspect, InspectFreeze},
        tokens::Precision,
        VariantCountOf,
    },
};

// --- FRAME System ---
use frame_system::pallet;

// --- Substrate primitives ---
use sp_core::{Decode, Encode, Get, MaxEncodedLen};
use sp_runtime::{
    traits::{CheckedAdd, Zero},
    BoundedVec, DispatchError, RuntimeDebug, Vec, WeakBoundedVec,
};
use sp_std::collections::btree_set::BTreeSet;

// ===============================================================================
// ``````````````````````````````````` ALIASES ```````````````````````````````````
// ===============================================================================

/// The **primary digest type** used to uniquely identify a commitment entity.
///
/// This type is reused across direct, index, and pool commitments.
pub type Digest<T> = <T as pallet::Config>::AccountId;

/// Represents the **unique identifier** for a direct digest.
///
/// A direct digest is neither an index nor a pool (i.e. not an indirect digest).
pub type DirectDigest<T> = Digest<T>;

/// Represents the **unique identifier** for an index.
pub type IndexDigest<T> = Digest<T>;

/// Represents the **unique identifier** for a pool.
pub type PoolDigest<T> = Digest<T>;

/// Represents the **unique identifier** for an entry within an index.
pub type EntryDigest<T> = Digest<T>;

/// Represents the **unique identifier** for a slot within a pool.
pub type SlotDigest<T> = Digest<T>;

/// Represents the **source for generating a digest**,
/// typically the runtime-caller's `AccountId` that seeds it.
pub type DigestSource<T> = <T as pallet::Config>::AccountId;

/// Represents the **owner of an asset or commitment**.  
pub type Proprietor<T> = <T as pallet::Config>::AccountId;

/// The fungible **balance type** for assets handled by the pallet.
///
/// Derived from the pallet's [`Config::Asset`] type and associated with the [`Proprietor`].
pub type AssetOf<T, I = ()> = <<T as Config<I>>::Asset as Inspect<Proprietor<T>>>::Balance;

/// Represents a **lazy-evaluated balance** for commitments.  
///
/// Doesn't specialize for commit-variants [`Config::Position`] as its implemented at
/// higher level for commits, digests, indexes, pools, etc individually.
pub type LazyBalanceOf<T, I = ()> = VirtualBalance<T, I>;

/// Represents a **single commit instance** created by a commit operation.
///
/// This is a thin wrapper over [`VirtualReceipt`], capturing a receipt of the
/// deposit at the time of commitment-similar to a bill that is later required
/// during withdrawal resolution.
///
/// A commitment may accumulate multiple commit instances over time. Each
/// instance is immutable, with aggregation and evaluation performed at
/// higher levels.
pub type CommitInstance<T, I = ()> = VirtualReceipt<T, I>;

/// Combined identifier representing the **reason for freezing or locking a balance**.
///
/// Typically derived from the runtime's composite freeze-reason enum associated
/// with [`Config::Asset`]. It is used to distinguish between different contexts
/// in which balances are held, such as commitments, freezes, or other locking
/// mechanisms.
pub type CommitReason<T, I = ()> = <<T as Config<I>>::Asset as InspectFreeze<Proprietor<T>>>::Id;

/// Alias to the pallet-defined balance execution context.
///
/// This represents the **type-level environment** configured by the runtime,
/// providing all bounds, extensions, and error definitions required to
/// materialize a lazy balance [`plugin`](frame_suite::plugins) family model.
pub type BalanceContext<T, I = ()> = <T as Config<I>>::BalanceContext;

/// Concrete [`plugin`](frame_suite::plugins)-model/family context derived
/// from [`BalanceContext`].
///
/// This resolves the **plugin execution context**, supplying runtime-specific
/// parameters and dependencies required by balance operations.
pub type BalanceModelContext<T, I = ()> = <BalanceContext<T, I> as ModelContext>::Context;

/// A generic [`virtual`](frame_suite::virtuals) structure. It acts as the
/// core building block for all lazy balance-related virtual types.
pub type LazyVirtual<T, A, R, Ti, Ad, I = ()> =
    ProductType<T, I, BalanceModelContext<T, I>, A, R, Ti, Ad>;

/// Virtual representation of a live lazy-balance.
///
/// Backed by the lazy balance model, meaning storage layouts are interpreted
/// dynamically by the caller rather than the implementor.
pub type VirtualBalance<T, I = ()> =
    LazyVirtual<T, BalanceAsset, BalanceRational, BalanceTime, BalanceAddon, I>;

/// Virtual representation of a balance snapshot.
///
/// Captures balance state at a specific point in time. Used for historical
/// views and proportional calculations.
pub type VirtualSnapShot<T, I = ()> =
    LazyVirtual<T, SnapShotAsset, SnapShotRational, SnapShotTime, SnapShotAddon, I>;

/// Virtual representation of a receipt (claim).
///
/// Represents a deferred claim over balance value in the lazy model:
/// - created on deposit
/// - resolved on withdrawal
///
/// Its value is computed dynamically based on global balance state.
pub type VirtualReceipt<T, I = ()> =
    LazyVirtual<T, ReceiptAsset, ReceiptRational, ReceiptTime, ReceiptAddon, I>;

// ===============================================================================
// ``````````````````````````` DIGEST BALANCES VECTOR ````````````````````````````
// ===============================================================================

/// Stores balance information for each variant of a digest.
///
/// A digest may have multiple semantic variants (e.g. `Affirmative`, `Contrary`, etc),
/// each maintaining its own balance. This structure tracks the corresponding
/// [`LazyBalanceOf`] for every variant.
///
/// Internally, it is backed by a [`BoundedVec`] whose length is fixed to the
/// number of semantic variants defined by [`Config::Position`] via the
/// `VariantCount` bound. This guarantees a **single, stable slot per variant**.
///
/// In some scenarios, a higher-indexed variant may be initialized before its
/// preceding variants. In such cases, the earlier slots are filled with a default
/// lazy balance to preserve positional invariants. While eagerly initializing all
/// slots would also be invariant-safe, it could increase storage usage when many
/// digests exist or when commitments do not utilize all variants.
///
/// To keep storage usage minimal, it is expected that the default variant
/// (`[`Default`]` for [`Config::Position`]) occupies index `0`, as defined by
/// [`PositionIndex`].
#[derive(
    Encode,
    Decode,
    Clone,
    RuntimeDebug,
    PartialEq,
    Eq,
    MaxEncodedLen,
    TypeInfo,
    DecodeWithMemTracking,
)]
#[scale_info(skip_type_params(T, I))]
pub struct DigestInfo<T: Config<I>, I: 'static = ()>(
    BoundedVec<LazyBalanceOf<T, I>, VariantCountOf<T::Position>>,
);

// ===============================================================================
// ``````````````````` DIGEST BALANCES VECTOR INHERENT METHODS ```````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> DigestInfo<T, I> {
    /// Returns the actively funded lazy balances of commitment digests along with
    /// their corresponding semantic positions (commit variants).
    ///
    /// Returns `DispatchError` if lookup or decoding fails.
    pub fn balances(&self) -> Result<Vec<(T::Position, LazyBalanceOf<T, I>)>, DispatchError> {
        let bound = &self.0;
        let mut collect = Vec::new();
        for (i, balance) in bound.iter().enumerate() {
            if *balance == Default::default() {
                continue;
            }
            let position = <T::Position as PositionIndex>::position_of(i);
            debug_assert!(
                position.is_some(),
                "commit-variant invalid position found for index {:?}, 
                an example default of the position type for debugging is {:?}",
                i,
                T::Position::default()
            );
            let position = position.ok_or(Error::<T, I>::InvalidCommitVariantIndex)?;
            collect.push((position, balance.clone()));
        }
        Ok(collect)
    }

    pub(crate) fn mut_balance(
        &mut self,
        variant: &T::Position,
    ) -> Option<&mut LazyBalanceOf<T, I>> {
        // Since we store variant balances as a vector, we need to deterministically
        // determine an index associated with the given variant
        let idx = variant.index();
        self.0.get_mut(idx)
    }

    pub fn get_balance(&self, variant: &T::Position) -> Option<&LazyBalanceOf<T, I>> {
        let idx = variant.index();
        self.0.get(idx)
    }

    pub fn reveal(&self) -> BoundedVec<LazyBalanceOf<T, I>, VariantCountOf<T::Position>> {
        self.0.clone()
    }

    pub(crate) fn init_balance(&mut self, variant: &T::Position) -> Result<(), DispatchError> {
        let idx = variant.index();
        // If the variant does not exist, create default variant balances up to the requested index
        let vec = &mut self.0;
        for i in 0..=idx {
            if let None = vec.get(i) {
                // Push default variant balances for missing variants
                let result = vec.try_push(Default::default());
                debug_assert!(
                    result.is_ok(),
                    "default commit-variants push results bad, where pushed 
                    index {:?} is lesser than or equal to expected variant (position) 
                    {:?} whoose index is {:?}",
                    i,
                    variant,
                    idx
                );
                result.map_err(|_| Error::<T, I>::VariantsExhausted)?;
            }
        }
        return Ok(());
    }
}

// ===============================================================================
// ``````````````````````````````` COMMITS VECTOR ````````````````````````````````
// ===============================================================================

/// Represents a collection of individual commit instances of a proprietor
/// for a specific digest (direct/index/pool) and commitment reason.
///
/// The association with a single **digest** and **reason** is not structurally
/// enforced at this level; instead, it is guaranteed by higher-level structures
/// (typically [`CommitInfo`]).
///
/// Each commit is stored as a [`CommitInstance`] within a [`WeakBoundedVec`],
/// bounding the number of commits per `(digest, reason)` pair to
/// [`Config::MaxCommits`].
#[derive(Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo, DecodeWithMemTracking)]
#[scale_info(skip_type_params(T, I))]
pub struct Commits<T: Config<I>, I: 'static = ()>(
    WeakBoundedVec<CommitInstance<T, I>, T::MaxCommits>,
);

// ===============================================================================
// ``````````````````````` COMMITS VECTOR INHERENT METHODS ```````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> Commits<T, I> {
    /// Initializes a new collection of commits with a single [`CommitInstance`],
    /// typically derived from [`LazyBalance`] deposit operations.
    ///
    /// This establishes the initial commit, after which additional commits
    /// may be appended via [`Commits::add_commit`].
    pub(crate) fn new(instance: CommitInstance<T, I>) -> Result<Self, DispatchError> {
        let max = T::MaxCommits::get();
        ensure!(!max.is_zero(), Error::<T, I>::ZeroMaxCommits);
        let vec = vec![instance];
        let commits = WeakBoundedVec::<CommitInstance<T, I>, T::MaxCommits>::try_from(vec);
        debug_assert!(
            commits.is_ok(),
            "single commit-instance vec to weak-vec of 
            max-commit {} is non-zero failed but shouldn't be",
            T::MaxCommits::get()
        );
        let commits = commits.map_err(|_| Error::<T, I>::CommitConstructionFailed)?;
        return Ok(Commits(commits));
    }

    /// Adds a new commitment instance to the existing
    /// commits collection.
    ///
    /// Returns `DispatchError` if the bounded vector capacity
    /// is exhausted.
    pub(crate) fn add_commit(
        &mut self,
        instance: CommitInstance<T, I>,
    ) -> Result<(), DispatchError> {
        debug_assert!(
            !self.0.is_empty(),
            "empty commits constructed without a single 
            commit-instance, attempting to add a new-instance {:?}",
            instance
        );
        ensure!(!self.0.is_empty(), Error::<T, I>::EmptyCommitsNotAllowed);
        let vec = &mut self.0;
        vec.try_push(instance)
            .map_err(|_| Error::<T, I>::MaxCommitsReached)?;
        Ok(())
    }

    pub fn commits(&self) -> WeakBoundedVec<CommitInstance<T, I>, T::MaxCommits> {
        debug_assert!(
            !self.0.is_empty(),
            "empty commits constructed without 
            a single commit-instance"
        );
        // no need to ensure for empty commits since this is a query function
        // which can return empty vector without Result<T, DispatchError>
        // ensure!(!self.0.is_empty(), Error::<T, I>::EmptyCommitsNotAllowed);
        self.0.clone()
    }
}

// ===============================================================================
// ``````````````````````````` SINGLE COMMIT META-DATA ```````````````````````````
// ===============================================================================

/// Represents a commitment associated with a specific **digest** and reason.
///
/// This structure tracks commitments at the lowest level. The referenced
/// `digest` is intentionally unclassified and may correspond to a direct,
/// index, or pool digest, as those are higher-level abstractions built over
/// the same commitment model.
///
/// Each [`CommitInfo`] aggregates multiple [`CommitInstance`] values produced
/// over time for the same `(digest, reason)` pair, representing successive
/// commitments raised by the proprietor.
#[derive(
    Encode,
    Decode,
    Clone,
    RuntimeDebug,
    MaxEncodedLen,
    TypeInfo,
    PartialEq,
    Eq,
    DecodeWithMemTracking,
)]
#[scale_info(skip_type_params(T, I))]
pub struct CommitInfo<T: Config<I>, I: 'static = ()> {
    /// The target digest this commitment is associated with.
    ///
    /// The digest is intentionally unclassified and may refer to a
    /// direct, index, or pool digest.
    digest: Digest<T>,

    /// Collection of commit instances ([`CommitInstance`])
    /// associated with this `digest`.
    ///
    /// This collection is internally mutated via [`Commits::add_commit`]
    /// whenever new commit instances are appended.
    commits: Commits<T, I>,

    /// The semantic disposition (variant) of the commitment
    /// (e.g. `Affirmative`, `Contrary`, etc).
    ///
    /// This is semantically meaningful only for direct digests. For index
    /// and pool digests, this field acts as a structural placeholder, as
    /// those abstractions manage their own variant information through
    /// entries and slots respectively.
    variant: T::Position,
}

// ===============================================================================
// `````````````````` SINGLE COMMIT META-DATA INHERENT METHODS ```````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> CommitInfo<T, I> {
    /// Creates a new [`CommitInfo`] with an initial commit instance.
    ///
    /// This constructor initializes the internal [`Commits`] collection
    /// in a controlled manner and establishes the initial commitment
    /// state for the given digest and reason.
    pub(crate) fn new(
        digest: Digest<T>,
        instance: CommitInstance<T, I>,
        variant: T::Position,
    ) -> Result<Self, DispatchError> {
        let commits = Commits::<T, I>::new(instance)?;
        let try_position = <T::Position as PositionIndex>::position_of(
            <T::Position as PositionIndex>::index(&variant),
        );
        debug_assert!(
            try_position.is_some(),
            "cannot equalize new-commit's given variant {:?} and its derived 
            positional index (not consistent) when creating new commit-info for 
            proprietor towards non-classified-digest {:?}",
            variant,
            digest
        );
        let position = try_position.ok_or(Error::<T, I>::InvalidCommitVariantIndex)?;
        debug_assert!(
            position == variant,
            "new-commit's given variant {:?} and its derived
            positional index (not consistent) variant is not same, 
            found {:?} when creating new commit-info for 
            proprietor towards non-classified-digest {:?}",
            variant,
            position,
            digest
        );
        ensure!(
            position == variant,
            Error::<T, I>::InvalidCommitVariantIndex
        );
        Ok(Self {
            digest,
            commits,
            variant,
        })
    }

    /// Returns the individual commit instances of the proprietor.
    #[inline]
    pub fn commits(&self) -> WeakBoundedVec<CommitInstance<T, I>, T::MaxCommits> {
        Commits::<T, I>::commits(&self.commits)
    }

    /// Returns the digest proprietor committed to.
    pub fn digest(&self) -> Digest<T> {
        self.digest.clone()
    }

    /// Returns the digest's variant proprietor committed to.
    pub fn variant(&self) -> T::Position {
        self.variant.clone()
    }

    /// Adds a new commitment instance to the existing commits
    /// collection of the proprietor's commit-info for a digest.
    ///
    /// Returns `DispatchError` if the bounded vector capacity
    /// is exhausted.
    #[inline]
    pub(crate) fn add_commit(
        &mut self,
        instance: CommitInstance<T, I>,
    ) -> Result<(), DispatchError> {
        self.commits.add_commit(instance)
    }
}

// ===============================================================================
// ````````````````````````` INDEX SINGLE-ENTRY META-DATA ````````````````````````
// ===============================================================================

/// Represents a single entry within an index.
///
/// Each entry maps a direct digest to a non-zero share allocation and a
/// semantic variant. This allows index commitments to be proportionally
/// distributed across multiple underlying digests.
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking)]
#[scale_info(skip_type_params(T, I))]
pub struct EntryInfo<T: Config<I>, I: 'static = ()> {
    /// The direct digest identifying this entry.
    digest: EntryDigest<T>,

    /// Number of shares (must be non-zero) associated with this entry.
    shares: T::Shares,

    /// Semantic variant/disposition of this entry (e.g. `Affirmative`, `Contrary`, etc).
    ///
    /// Commitments placed through this entry are credited to the corresponding
    /// variant balance of the underlying direct digest.
    variant: T::Position,
}

// ===============================================================================
// ````````````````````` INDEX SINGLE-ENTRY INHERENT METHODS `````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> EntryInfo<T, I> {
    /// Creates a new [`EntryInfo`] for an index.
    ///
    /// Validates that the provided shares are non-zero and that the variant
    /// is semantically valid.
    ///
    /// Returns `DispatchError` if validation fails.
    pub fn new(
        digest: EntryDigest<T>,
        shares: T::Shares,
        variant: T::Position,
    ) -> Result<Self, DispatchError> {
        ensure!(!shares.is_zero(), Error::<T, I>::ShareCannotBeZero);
        let try_position = <T::Position as PositionIndex>::position_of(
            <T::Position as PositionIndex>::index(&variant),
        );
        debug_assert!(
            try_position.is_some(),
            "cannot equalize new-commit's given variant {:?} and its derived 
            positional index (not consistent) when creating new entry-info for 
            entry-digest {:?} of shares {:?}",
            variant,
            digest,
            shares
        );
        let position = try_position.ok_or(Error::<T, I>::InvalidCommitVariantIndex)?;
        debug_assert!(
            position == variant,
            "new-commit's given variant {:?} and its derived
            positional index (not consistent) variant is not same, 
            found {:?} when creating new entry-info for entry-digest 
            {:?} of shares {:?}",
            variant,
            position,
            digest,
            shares
        );
        ensure!(
            position == variant,
            Error::<T, I>::InvalidCommitVariantIndex
        );
        Ok(Self {
            digest,
            shares,
            variant,
        })
    }

    /// Return the share value of this entry.
    ///
    /// `DispatchError` if inconsistency detected.
    pub fn shares(&self) -> T::Shares {
        self.shares
    }

    /// Returns the direct digest associated with this entry.
    pub fn digest(&self) -> Digest<T> {
        self.digest.clone()
    }

    /// Returns the variant associated with this entry's direct digest.
    pub fn variant(&self) -> T::Position {
        self.variant.clone()
    }
}

impl<T: Config<I>, I: 'static> Clone for EntryInfo<T, I> {
    fn clone(&self) -> Self {
        Self {
            digest: self.digest.clone(),
            shares: self.shares,
            variant: self.variant.clone(),
        }
    }
}

// ===============================================================================
// ```````````````````````````` INDEX ENTRIES VECTOR `````````````````````````````
// ===============================================================================

/// Represents a collection of entries within an index.
///
/// Backed by a [`WeakBoundedVec`] to enforce an upper bound on the number of
/// entries (via [`Config::MaxIndexEntries`]) while maintaining efficient,
/// bounded storage.
///
/// This serves as the low-level container for all [`EntryInfo`] items that
/// constitute an index.
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking)]
#[scale_info(skip_type_params(T, I))]
pub struct Entries<T: Config<I>, I: 'static = ()>(
    WeakBoundedVec<EntryInfo<T, I>, T::MaxIndexEntries>,
);

// ===============================================================================
// ```````````````````` INDEX ENTRIES VECTOR INHERENT METHODS ````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> Entries<T, I> {
    /// Creates a new [`Entries`] collection for an index from a vector of
    /// validated [`EntryInfo`] items.
    ///
    /// Returns `DispatchError` if any inconsistencies detected.
    pub fn new(entries: Vec<EntryInfo<T, I>>) -> Result<Self, DispatchError> {
        let max = T::MaxIndexEntries::get();
        ensure!(!max.is_zero(), Error::<T, I>::TriedCreatingHaltedIndexes);
        ensure!(!entries.is_empty(), Error::<T, I>::EmptyEntriesNotAllowed);
        let mut seen = BTreeSet::new();
        for entry in &entries {
            ensure!(
                seen.insert(entry.digest.clone()),
                Error::<T, I>::DuplicateEntry
            );
        }
        let entries = WeakBoundedVec::<EntryInfo<T, I>, T::MaxIndexEntries>::try_from(entries)
            .map_err(|_| Error::<T, I>::MaxEntriesReached)?;
        return Ok(Entries(entries));
    }

    /// Returns all [`EntryInfo`] items contained in this list as a owned vector.
    pub fn entries(&self) -> Vec<EntryInfo<T, I>> {
        let bounded = &self.0;
        let mut collect = Vec::new();
        for entry in bounded {
            collect.push(entry.clone())
        }
        debug_assert!(
            !collect.is_empty(),
            "empty entries-list initiated which 
            should not be for indexes"
        );
        collect
    }

    /// Adds a new [`EntryInfo`] to the list of entries.
    ///
    /// Returns `DispatchError` if vector bound exhausted
    /// or duplicate found.
    pub fn add_entry(&mut self, entry: EntryInfo<T, I>) -> Result<(), DispatchError> {
        debug_assert!(
            !self.0.is_empty(),
            "empty entries constructed without a single 
            commit-instance, attempting to add a new-entry",
        );
        ensure!(!self.0.is_empty(), Error::<T, I>::EmptyEntriesNotAllowed);
        let vec = &mut self.0;
        vec.try_push(entry)
            .map_err(|_| Error::<T, I>::MaxEntriesReached)?;
        let mut seen = BTreeSet::new();
        for entry in vec {
            ensure!(
                seen.insert(entry.digest.clone()),
                Error::<T, I>::DuplicateEntry
            );
        }
        Ok(())
    }

    /// Removes an existing [`EntryInfo`] from the entries-list.
    ///
    /// Returns `DispatchError` if entry of digest not found.
    pub fn remove_entry(&mut self, entry: &EntryDigest<T>) -> Result<(), DispatchError> {
        debug_assert!(
            !self.0.is_empty(),
            "empty entries constructed without a single 
            commit-instance, attempting to remove an existing-entry {:?}",
            entry
        );
        ensure!(
            (!self.0.is_empty() && self.0.len() > 1),
            Error::<T, I>::EmptyEntriesNotAllowed
        );
        debug_assert!(
            self.0.len() > 1,
            "attempting to remove an existing-entry {:?}, which 
            will result in zero-length entries",
            entry
        );
        let mut entry_idx = None;
        for (i, entry_of) in self.0.iter().enumerate() {
            if entry_of.digest == *entry {
                entry_idx = Some(i);
                break;
            }
        }

        match entry_idx {
            Some(idx) => {
                self.0.remove(idx);
            }
            None => {
                return Err(Error::<T, I>::EntryOfIndexNotFound)?;
            }
        }
        Ok(())
    }
}

// ===============================================================================
// ``````````````````````````````` INDEX META-DATA ```````````````````````````````
// ===============================================================================

/// Represents an index containing multiple entries.
///
/// An `IndexInfo` tracks the overall capital, total balance, and the entries themselves.
///
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking)]
#[scale_info(skip_type_params(T, I))]
pub struct IndexInfo<T: Config<I>, I: 'static = ()> {
    /// Total asset depositted to this index
    ///
    /// This does not qualify as real-time value of the index,
    /// since entries are finite digests that should be queried
    /// for such cases.
    principal: AssetOf<T, I>,

    /// Total shares/capital across all entries in this index
    capital: T::Shares,

    /// The collection of entries making up this index
    entries: Entries<T, I>,
}

// ===============================================================================
// ``````````````````````` INDEX META-DATA INHERENT METHODS ``````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> IndexInfo<T, I> {
    /// Creates a new [`IndexInfo`] from a collection of entries.
    ///
    /// This function calculates the total capital by summing the shares
    /// of all entries. It retains only entries of non-zero shares.
    ///
    /// Returns `DispatchError` if any of invariant fails
    /// - Total Capital cannot be zero
    /// - Entries should not be empty
    pub(crate) fn new(entries: &mut Entries<T, I>) -> Result<Self, DispatchError> {
        debug_assert!(!entries.0.is_empty(), "entries is constructed empty");
        ensure!(!entries.0.is_empty(), Error::<T, I>::EmptyEntriesNotAllowed);
        let mut total_capital = T::Shares::zero();
        for entry in &entries.0 {
            let shares = entry.shares;
            debug_assert!(
                !shares.is_zero(),
                "entry for digest {:?} of variant {:?} share is constructed zero",
                entry.digest,
                entry.variant
            );
            ensure!(!shares.is_zero(), Error::<T, I>::ShareCannotBeZero);
            total_capital = total_capital
                .checked_add(&shares)
                .ok_or(Error::<T, I>::CapitalOverflowed)?;
        }
        debug_assert!(
            !total_capital.is_zero(),
            "total capital is zero while its entry shares isn't"
        );
        ensure!(!total_capital.is_zero(), Error::<T, I>::CapitalCannotBeZero);
        Ok(Self {
            principal: AssetOf::<T, I>::zero(),
            capital: total_capital,
            entries: entries.clone(),
        })
    }

    /// Returns the index's capital - total shares.
    pub fn capital(&self) -> T::Shares {
        let value = self.capital;
        debug_assert!(!value.is_zero(), "index capital is constructed zero");
        value
    }

    /// Returns the index's principal, i.e. the total amount
    /// deposited by proprietors.
    pub fn principal(&self) -> AssetOf<T, I> {
        self.principal
    }

    /// Returns the index's entries vector list.
    #[inline]
    pub fn entries(&self) -> Vec<EntryInfo<T, I>> {
        Entries::<T, I>::entries(&self.entries)
    }

    /// Reveal the actual entries [`Entries`]
    pub fn reveal_entries(&self) -> Entries<T, I> {
        self.entries.clone()
    }

    /// Checks if an entry of digest exists in the index.
    pub fn entry_exists(&self, entry: &EntryDigest<T>) -> DispatchResult {
        let entries = &self.entries;
        debug_assert!(!entries.0.is_empty(), "entries is constructed empty");
        ensure!(!entries.0.is_empty(), Error::<T, I>::EmptyEntriesNotAllowed);
        let mut idx = None;
        // Locate the target slot.
        for (i, entry_of) in entries.0.iter().enumerate() {
            if entry_of.digest == *entry {
                idx = Some(i);
            }
        }

        // If no matching slot exists, nothing to remove.
        if let Some(_) = idx {
            return Ok(());
        };

        Err(Error::<T, I>::EntryOfIndexNotFound.into())
    }

    /// Sets the index principal to the provided value, replacing the existing balance.
    pub(crate) fn set_balance(&mut self, principal: AssetOf<T, I>) {
        self.principal = principal
    }
}

// ===============================================================================
// ```````````````````````````` SINGLE SLOT META-DATA ````````````````````````````
// ===============================================================================

/// Represents a slot within a pool, derived from an index entry.
///
/// A `SlotInfo` tracks the underlying digest, the allocated shares, the
/// slot's single [`CommitInstance`] (a collective receipt)
/// and the variant/disposition. It is primarily used when creating or
/// managing pools derived from index entries.
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking)]
#[scale_info(skip_type_params(T, I))]
pub struct SlotInfo<T: Config<I>, I: 'static = ()> {
    /// Unique identifier for the slot
    digest: SlotDigest<T>,

    /// Shares allocated to this slot
    shares: T::Shares,

    /// Commit-Instance associated with this slot
    ///
    /// Since pools collectively manages funds, slots also
    /// inherit such behaviour. Hence it acts similar to a proprietor
    /// holding a deposit receipt from digest for their commitment.
    commit: CommitInstance<T, I>,

    /// Disposition of this slot (e.g., Affirmative, Contrary, Awaiting)
    variant: T::Position,
}

// ===============================================================================
// ``````````````````````` SINGLE SLOT META-DATA INHERENTS ```````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> SlotInfo<T, I> {
    /// Returns the pool's slot's total shares.
    pub fn shares(&self) -> T::Shares {
        self.shares
    }

    /// Returns the pool's slot's commit-instance
    /// (as a pseudo-proprietor).
    pub fn commit(&self) -> CommitInstance<T, I> {
        self.commit.clone()
    }

    /// Returns the pool's slot's digest.
    pub fn digest(&self) -> SlotDigest<T> {
        self.digest.clone()
    }

    /// Returns the pool's slot's variant.
    pub fn variant(&self) -> T::Position {
        self.variant.clone()
    }

    /// Updates the [`CommitInstance`] associated with this slot.
    ///
    /// This method **replaces the existing commit instance** with the provided one.
    /// It does not perform any validation, aggregation, or merging of commits,
    /// the caller is responsible for ensuring correctness and consistency.
    ///
    /// ## Parameters
    /// - `commit`: The new [`CommitInstance`] to associate with this slot.
    ///
    /// ## Invariants
    /// - This operation assumes the slot is already initialized.
    /// - The provided commit should be semantically valid for this slot's
    ///   digest, shares, and variant.
    ///
    /// ## Note
    /// This is an internal mutation helper and is not intended to enforce
    /// higher-level commitment rules.
    fn set_slot_commit(&mut self, commit: CommitInstance<T, I>) {
        self.commit = commit
    }
}

// ===============================================================================
// ```````````````````````` ENTRY-TO-SLOT SAFE CONVERSION ````````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> From<EntryInfo<T, I>> for SlotInfo<T, I> {
    /// Converts an `EntryInfo` into a `SlotInfo`.
    ///
    /// This is used when creating a pool from an index, as each index entry
    /// corresponds to a pool slot. The deposit-receipt is initialized to empty
    /// as slot doesn't hold a commit currently.
    ///
    /// ## Returns
    /// A `SlotInfo` with the same digest, shares, and variant.
    fn from(entry: EntryInfo<T, I>) -> Self {
        Self {
            digest: entry.digest,
            shares: entry.shares,
            commit: Default::default(),
            variant: entry.variant,
        }
    }
}

// ===============================================================================
// ````````````````````````````````` SLOTS VECTOR ````````````````````````````````
// ===============================================================================

/// Represents a collection of slots within a pool.
///
/// `Slots` is essentially a bounded vector of [`SlotInfo`] instances, enforcing
/// a maximum number of slots defined by `MaxIndexEntries`.
///
/// This type ensures that pools derived from indexes cannot exceed the maximum
/// allowed number of slots.
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]
#[scale_info(skip_type_params(T, I))]
pub struct Slots<T: Config<I>, I: 'static = ()>(WeakBoundedVec<SlotInfo<T, I>, T::MaxIndexEntries>);

// ===============================================================================
// ```````````````````````` SLOTS VECTOR INHERENT METHODS ````````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> Slots<T, I> {
    /// Returns the pools's individual slots as a vector.
    pub fn slots(&self) -> Vec<SlotInfo<T, I>> {
        let bounded = &self.0;
        let mut collect = Vec::new();
        for slot in bounded {
            collect.push(slot.clone())
        }
        debug_assert!(
            !collect.is_empty(),
            "empty slots initiated which should not be for pools"
        );
        collect
    }

    /// Adds a new [`EntryInfo`] to the list of slots, since slots can only
    /// be derived from entry.
    ///
    /// Returns `DispatchError` if vector bound exhausted or duplicate found.
    fn add_slot(&mut self, entry: EntryInfo<T, I>) -> Result<(), DispatchError> {
        debug_assert!(
            !self.0.is_empty(),
            "empty slots constructed without a single 
            slot, attempting to add a new-slot via entry",
        );
        ensure!(!self.0.is_empty(), Error::<T, I>::EmptySlotsNotAllowed);
        let vec = &mut self.0;
        vec.try_push(entry.into())
            .map_err(|_| Error::<T, I>::MaxSlotsReached)?;
        let mut seen = BTreeSet::new();
        for slot in vec {
            ensure!(
                seen.insert(slot.digest.clone()),
                Error::<T, I>::DuplicateSlot,
            );
        }
        Ok(())
    }

    /// Removes an existing [`SlotInfo`] from the slots-list.
    ///
    /// Returns `DispatchError` if slot of digest not found.
    fn remove_slot(&mut self, slot: &SlotDigest<T>) -> Result<(), DispatchError> {
        debug_assert!(
            !self.0.is_empty(),
            "empty slots constructed without a single 
            slot, attempting to remove an existing-slot {:?}",
            slot,
        );
        ensure!(
            (!self.0.is_empty() && self.0.len() > 1),
            Error::<T, I>::EmptySlotsNotAllowed
        );
        debug_assert!(
            self.0.len() > 1,
            "attempting to remove an existing-slot {:?}, which 
            will result in zero-length slots",
            slot
        );
        let mut slot_idx = None;
        for (i, slot_of) in self.0.iter().enumerate() {
            if slot_of.digest == *slot {
                slot_idx = Some(i);
                break;
            }
        }

        match slot_idx {
            Some(idx) => {
                self.0.remove(idx);
            }
            None => {
                return Err(Error::<T, I>::SlotOfPoolNotFound)?;
            }
        }
        Ok(())
    }

    /// Updates the commit instance of a slot identified by the given `digest`.
    ///
    /// This function performs a linear search over the internal slots collection
    /// to locate a slot whose `digest` matches the provided `digest`.
    ///
    /// - If a matching slot is found:
    ///     - Its associated [`CommitInstance`] is **replaced** with the provided `commit`.
    /// - If no matching slot exists:
    ///     - Returns [`Error::SlotOfPoolNotFound`].
    fn set_slot_commit(
        &mut self,
        digest: &SlotDigest<T>,
        commit: CommitInstance<T, I>,
    ) -> Result<(), DispatchError> {
        debug_assert!(
            !self.0.is_empty(),
            "empty slots constructed without a single 
            slot {:?}",
            self,
        );

        let mut slot_idx = None;
        for (i, slot_of) in self.0.iter().enumerate() {
            if slot_of.digest == *digest {
                slot_idx = Some(i);
                break;
            }
        }

        match slot_idx {
            Some(idx) => {
                let slot_of = self
                    .0
                    .get_mut(idx)
                    .ok_or(Error::<T, I>::SlotOfPoolNotFound)?;
                slot_of.set_slot_commit(commit);
            }
            None => {
                return Err(Error::<T, I>::SlotOfPoolNotFound)?;
            }
        }
        Ok(())
    }
}

// ===============================================================================
// `````````````````````` SLOT-TO-ENTRY FALLIBLE CONVERSION ``````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> TryFrom<Entries<T, I>> for Slots<T, I> {
    type Error = DispatchError;

    /// Converts a collection of `Entries` into `Slots`.
    ///
    /// Each [`EntryInfo`] is converted into a [`SlotInfo`] using the `From<EntryInfo>` implementation.
    ///
    /// ## Returns
    /// - `Ok(Slots)` if the conversion succeeds within the maximum allowed slots.
    /// - `Err(DispatchError)` if the resulting collection exceeds `MaxIndexEntries`.
    fn try_from(entries: Entries<T, I>) -> Result<Self, Self::Error> {
        let raw_vec: Vec<SlotInfo<T, I>> =
            entries.0.into_iter().map(|entry| entry.into()).collect();

        let entries = WeakBoundedVec::try_from(raw_vec)
            .map(Slots)
            .map_err(|_| Error::<T, I>::MaxSlotsReached.into());
        debug_assert!(
            entries.is_ok(),
            "both entries and slots have same upper weak-bound
            but slots cannot be tried from entries"
        );
        entries
    }
}

// ===============================================================================
// ```````````````````````````````` POOL META-DATA ```````````````````````````````
// ===============================================================================

/// Represents a managed pool derived from an index.
///
/// `PoolInfo` aggregates capital, commission, and the collection of slots,
/// each of which represents a portion of the pool linked to underlying entries.
/// Unlike indexes, pools are mutable and can have their slot balances adjusted dynamically.
///
/// Pools are created from an [`IndexInfo`] (or [`Entries`]), allowing the
/// shares of each entry to be translated into slots within the pool.
///
/// Pool's slot shares/variants can then be adjusted over time, while the
/// pool's commission and structure remain consistent.
///
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking)]
#[scale_info(skip_type_params(T, I))]
pub struct PoolInfo<T: Config<I>, I: 'static = ()> {
    /// Real-time balance of the pool.
    ///
    /// Stored as [`LazyBalanceOf`] which allows efficient updates and tracking
    /// proprietor depositted balances internally within itself at higher level.
    balance_of: LazyBalanceOf<T, I>,

    /// Total capital of the pool.
    ///
    /// Computed as the sum of all shares in the pool's slots.
    /// Represents the total weight or stake across all slots.
    capital: T::Shares,

    /// Commission rate charged by the pool manager.
    ///
    /// The manager earns this percentage of rewards or profits
    /// generated by the pool.
    commission: T::Commission,

    /// Collection of slots representing the underlying assets
    /// or commitments.
    ///
    /// Each slot corresponds to an entry from the index that formed
    /// this pool. Slots track individual shares, its deposit receipt,
    /// and disposition [`Disposition`](frame_suite::Disposition).
    slots: Slots<T, I>,
}

// ===============================================================================
// ``````````````````````` POOL META-DATA INHERENT METHODS ```````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> PoolInfo<T, I> {
    /// Creates a new pool from a list of index entries and a commission rate.
    ///
    /// - Converts the [`Entries`] into [`Slots`].
    /// - Calculates the total capital by summing all entry shares.
    /// - Initializes the pool balance to zero.
    ///
    /// ## Returns
    /// - `Ok(PoolInfo)` if successful.
    /// - `Err(DispatchError)` otherwise.
    pub(crate) fn new(
        index_entries: Entries<T, I>,
        commission: T::Commission,
    ) -> Result<Self, DispatchError> {
        let total_capital = index_entries
            .0
            .iter()
            .try_fold(T::Shares::zero(), |acc, slot| {
                acc.checked_add(&slot.shares)
                    .ok_or(Error::<T, I>::CapitalOverflowed)
            })?;

        let slots = index_entries.try_into()?;

        Ok(Self {
            balance_of: Default::default(),
            capital: total_capital,
            commission,
            slots,
        })
    }

    /// Returns the pool's lazy balance.
    pub fn balance(&self) -> LazyBalanceOf<T, I> {
        self.balance_of.clone()
    }

    /// Set the pool balance usually only after release.
    pub(crate) fn set_balance(&mut self, balance: LazyBalanceOf<T, I>) {
        self.balance_of = balance;
    }

    /// Returns the pool's total capital i.e., total shares of all slots.
    pub fn capital(&self) -> T::Shares {
        let value = self.capital;
        debug_assert!(!value.is_zero(), "index capital is constructed zero");
        value
    }

    /// Returns the pool's commission i.e., manager's share while resolving the pool's commit.
    pub fn commission(&self) -> T::Commission {
        self.commission
    }

    /// Returns the pools's individual slots as a vector.
    pub fn slots(&self) -> Vec<SlotInfo<T, I>> {
        self.slots.slots()
    }

    /// Resets the pools's top-level lazy balance.
    ///
    /// This lazy balance acts like a pseudo-direct-digest
    /// for proprietors structurally for pool-commitments.
    pub(crate) fn balance_reset(&mut self) {
        self.balance_of = Default::default();
        for slot in &mut self.slots.0 {
            slot.commit = Default::default();
        }
    }

    /// Replaces the commit instance of the slot identified by `digest`
    /// by delegating to the underlying `slots`.
    #[inline]
    pub(crate) fn set_slot_commit(
        &mut self,
        digest: &SlotDigest<T>,
        commit: CommitInstance<T, I>,
    ) -> Result<(), DispatchError> {
        self.slots.set_slot_commit(digest, commit)
    }

    /// Adds a new [`EntryInfo`] to the list of pool's slots,
    /// as slots [`SlotInfo`] can only be derived from an entry.
    ///
    /// Unlike indexes which are immutable, pools are mutable hence requires
    /// slot management via higher-structures.
    ///
    /// Returns `DispatchError` otherwise.
    pub(crate) fn add_slot(&mut self, entry: EntryInfo<T, I>) -> DispatchResult {
        self.slots.add_slot(entry)?;
        let total_capital = self
            .slots
            .0
            .iter()
            .try_fold(T::Shares::zero(), |acc, slot| {
                acc.checked_add(&slot.shares)
                    .ok_or(Error::<T, I>::CapitalOverflowed)
            })?;
        self.capital = total_capital;
        Ok(())
    }

    /// Removes an existing slot from the pool.
    ///
    /// Unlike indexes which are immutable, pools are mutable hence requires
    /// slot management via higher-structures.
    ///
    /// Returns `DispatchError` otherwise.
    pub(crate) fn remove_slot(&mut self, slot: &SlotDigest<T>) -> DispatchResult {
        self.slots.remove_slot(slot)?;
        ensure!(
            !self.slots.0.is_empty(),
            Error::<T, I>::EmptySlotsNotAllowed
        );
        let total_capital = self
            .slots
            .0
            .iter()
            .try_fold(T::Shares::zero(), |acc, slot| {
                acc.checked_add(&slot.shares)
                    .ok_or(Error::<T, I>::CapitalOverflowed)
            })?;
        self.capital = total_capital;
        Ok(())
    }

    /// Checks if a slot of digest exists in the pool.
    pub fn slot_exists(&self, slot: &SlotDigest<T>) -> DispatchResult {
        let slots = &self.slots;
        debug_assert!(!slots.0.is_empty(), "slots are constructed empty");
        let mut idx = None;
        // Locate the target slot.
        for (i, slot_of) in slots.0.iter().enumerate() {
            if slot_of.digest == *slot {
                idx = Some(i);
            }
        }

        // If no matching slot exists, nothing to remove.
        if let Some(_) = idx {
            return Ok(());
        };

        Err(Error::<T, I>::SlotOfPoolNotFound.into())
    }
}

// ===============================================================================
// ````````````````````````` KEY-GENERATION SEED STRUCTS `````````````````````````
// ===============================================================================

/// A composite structure combining a commit reason with an index.
///
/// This struct is primarily used as a **key generation seed** for creating
/// unique digests associated with an index under a specific reason. By combining
/// both the `reason` and the [`IndexInfo`] itself, the resulting hash is unique
/// and deterministic for the given combination.
///
/// Used in functions like `gen_index_digest` to ensure that the same index under
/// the same reason always produces the same digest, while different reasons or
/// different index contents yield different digests.
#[derive(
    Encode,
    Decode,
    RuntimeDebug,
    MaxEncodedLen,
    TypeInfo,
    Constructor,
    PartialEq,
    Eq,
    DecodeWithMemTracking,
)]
#[scale_info(skip_type_params(T, I))]
pub struct IndexOfReason<T: Config<I>, I: 'static = ()> {
    /// The reason or context under which this index is associated.
    pub reason: CommitReason<T, I>,

    /// The index information being combined with the reason for key generation.
    pub index: IndexInfo<T, I>,
}

/// A composite structure combining a commit reason with a pool.
///
/// This struct is used as a **key generation seed** for creating unique digests
/// associated with a pool under a specific reason. By combining the `reason` and
/// the [`PoolInfo`], the digest is deterministic and unique for the pool's
/// composition and context.
///
/// Primarily utilized in functions like `gen_pool_digest`, allowing consistent
/// and collision-resistant digest generation for pools derived from an index.
#[derive(
    Encode,
    Decode,
    RuntimeDebug,
    MaxEncodedLen,
    TypeInfo,
    Constructor,
    PartialEq,
    Eq,
    DecodeWithMemTracking,
)]
#[scale_info(skip_type_params(T, I))]
pub struct PoolOfReason<T: Config<I>, I: 'static = ()> {
    /// The reason or context under which this pool is associated.
    pub reason: CommitReason<T, I>,

    /// The pool information being combined with the reason for key generation.
    pub pool: PoolInfo<T, I>,
}

// ===============================================================================
// ``````````````````````` IMBALANCE CARRIER (ASSET-DELTA) ```````````````````````
// ===============================================================================

/// Represents a net change (delta) in assets for a particular operation.
///
/// This struct is used to track **both deposits and withdrawals** in a single structure,
/// which is particularly useful when working with unbalanced fungible traits.
///
/// Since the pallet manually mints and burns assets to maintain equilibrium,
/// both `deposit` and `withdraw` fields are necessary.
///
/// ## Usage
/// - **Withdrawal operations**: Used to record the assets that need to be withdrawn
/// from a pool or digest.
/// - **Deposit/Recovery**: Tracks any leftover assets that must be deposited back to
/// maintain total system balance.
/// - **Equilibrium maintenance**: Helps reconcile unbalanced operations by explicitly
/// separating minting and burning.
#[derive(
    Encode,
    Decode,
    MaxEncodedLen,
    RuntimeDebug,
    TypeInfo,
    PartialEq,
    Clone,
    Constructor,
    Eq,
    DecodeWithMemTracking,
    Copy,
)]
#[scale_info(skip_type_params(T, I))]
pub(crate) struct AssetDelta<T: Config<I>, I: 'static = ()> {
    /// The amount of assets to be taken (decreased or burned) to the system or account.
    pub deposit: AssetOf<T, I>,
    /// The amount of assets to be given (increased or minted) to the system or account.
    pub withdraw: AssetOf<T, I>,
}

// ===============================================================================
// ```````````````````````````` EXTRINSIC PARAMETERS `````````````````````````````
// ===============================================================================

/// Choose a valid digest model for [`ChooseDigest::digest_model`] safe construction.
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking, Clone, Debug, Copy)]
pub enum ChooseDigest {
    Direct,
    Index,
    Pool,
}

impl ChooseDigest {
    pub fn digest_model<T: Config<I>, I: 'static>(&self, digest: Digest<T>) -> DigestVariant<T, I> {
        match self {
            ChooseDigest::Direct => DigestVariant::Direct(digest),
            ChooseDigest::Index => DigestVariant::Index(digest),
            ChooseDigest::Pool => DigestVariant::Pool(digest),
        }
    }
}

/// Represents a generic digest variant in the commitment system.
///
/// Note: Usage of PhantomData variant in runtime will result in `panic!`
/// in debug-builds. Use [`ChooseDigest::digest_model`] for safe constructions.
///
/// This enum distinguishes between the different types of digests that
/// can exist in the pallet. It allows functions and events to operate
/// generically over digests without losing context about their source or type.
///
/// ### Usage:
/// - Used in events like `CommitPlaced`, `DigestInfo`, etc., to convey
///   which type of digest is being referred to.
/// - Enables trait and function implementations to handle multiple digest types
///   in a type-safe and g||eneric way.
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking)]
#[scale_info(skip_type_params(T, I))]
pub enum DigestVariant<T: Config<I>, I: 'static = ()> {
    /// A digest that refers directly to a commitment.
    Direct(Digest<T>),
    /// A digest that represents an index of multiple entries.
    Index(Digest<T>),
    /// A digest that represents a managed pool of slots.
    Pool(Digest<T>),
    /// Phantom variant to ensure the instance parameter `I` is used.
    /// This variant is never constructed.
    #[codec(skip)]
    __Ignore(PhantomData<I>),
}

/// Wrapper type for [`Precision`] used in extrinsics.
///
/// This enum defines how precisely a funding operation should be executed,
/// particularly in scenarios where exact amounts may not be achievable due
/// to rounding, liquidity, or distribution constraints.
///
/// ## Variants
/// - `Exact`: Requires the operation to be executed with exact precision.
///   Fails if the exact value cannot be honored.
/// - `BestEffort`: Allows approximate execution, where the system will
///   attempt to fulfill the request as closely as possible.
///
/// ## Notes
/// - This type exists to decouple the extrinsic API from the internal
///   [`Precision`] type.
/// - It is converted into [`Precision`] internally before execution.
#[derive(
    Encode,
    Decode,
    DecodeWithMemTracking,
    RuntimeDebug,
    Clone,
    PartialEq,
    Eq,
    MaxEncodedLen,
    TypeInfo,
)]
pub enum PrecisionWrapper {
    Exact,
    BestEffort,
}

impl From<PrecisionWrapper> for Precision {
    fn from(value: PrecisionWrapper) -> Self {
        match value {
            PrecisionWrapper::Exact => Precision::Exact,
            PrecisionWrapper::BestEffort => Precision::BestEffort,
        }
    }
}

// ===============================================================================
// ````````````````````````````````` DERIVE IMPLS ````````````````````````````````
// ===============================================================================

impl<T: Config<I>, I: 'static> Default for DigestInfo<T, I> {
    /// Creates an empty `DigestInfo` with no variant balances.
    /// Variant slots are initialized lazily and filled safely on demand.
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<T: Config<I>, I: 'static> PartialEq for Commits<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T: Config<I>, I: 'static> Eq for Commits<T, I> {}

impl<T: Config<I>, I: 'static> PartialEq for EntryInfo<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.digest == other.digest && self.shares == other.shares && self.variant == other.variant
    }
}

impl<T: Config<I>, I: 'static> Eq for EntryInfo<T, I> {}

impl<T: Config<I>, I: 'static> core::fmt::Debug for EntryInfo<T, I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("EntryInfo")
            .field("digest", &self.digest)
            .field("shares", &self.shares)
            .field("variant", &self.variant)
            .finish()
    }
}

impl<T: Config<I>, I: 'static> PartialEq for Entries<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T: Config<I>, I: 'static> Eq for Entries<T, I> {}

impl<T: Config<I>, I: 'static> core::fmt::Debug for Entries<T, I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("Entries").field(&self.0).finish()
    }
}

impl<T: Config<I>, I: 'static> Clone for Entries<T, I> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T: Config<I>, I: 'static> core::fmt::Debug for IndexInfo<T, I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("IndexInfo")
            .field("principal", &self.principal)
            .field("capital", &self.capital)
            .field("entries", &self.entries)
            .finish()
    }
}

impl<T: Config<I>, I: 'static> PartialEq for IndexInfo<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.principal == other.principal
            && self.capital == other.capital
            && self.entries == other.entries
    }
}

impl<T: Config<I>, I: 'static> Eq for IndexInfo<T, I> {}

impl<T: Config<I>, I: 'static> Clone for IndexInfo<T, I> {
    fn clone(&self) -> Self {
        Self {
            principal: self.principal,
            capital: self.capital,
            entries: self.entries.clone(),
        }
    }
}

impl<T: Config<I>, I: 'static> PartialEq for SlotInfo<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.digest == other.digest
            && self.shares == other.shares
            && self.commit == other.commit
            && self.variant == other.variant
    }
}

impl<T: Config<I>, I: 'static> Eq for SlotInfo<T, I> {}

impl<T: Config<I>, I: 'static> core::fmt::Debug for SlotInfo<T, I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("SlotInfo")
            .field("digest", &self.digest)
            .field("shares", &self.shares)
            .field("commit", &self.commit)
            .field("variant", &self.variant)
            .finish()
    }
}

impl<T: Config<I>, I: 'static> Clone for SlotInfo<T, I> {
    fn clone(&self) -> Self {
        Self {
            digest: self.digest.clone(),
            shares: self.shares,
            commit: self.commit.clone(),
            variant: self.variant.clone(),
        }
    }
}

impl<T: Config<I>, I: 'static> PartialEq for Slots<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T: Config<I>, I: 'static> core::fmt::Debug for Slots<T, I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("Slots").field(&self.0.as_slice()).finish()
    }
}

impl<T: Config<I>, I: 'static> Eq for Slots<T, I> {}

impl<T: Config<I>, I: 'static> Clone for Slots<T, I> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T: Config<I>, I: 'static> PartialEq for PoolInfo<T, I> {
    fn eq(&self, other: &Self) -> bool {
        self.balance_of == other.balance_of
            && self.capital == other.capital
            && self.commission == other.commission
            && self.slots == other.slots
    }
}

impl<T: Config<I>, I: 'static> Eq for PoolInfo<T, I> {}

impl<T: Config<I>, I: 'static> Clone for PoolInfo<T, I> {
    fn clone(&self) -> Self {
        Self {
            balance_of: self.balance_of.clone(),
            capital: self.capital,
            commission: self.commission,
            slots: self.slots.clone(),
        }
    }
}

impl<T: Config<I>, I: 'static> core::fmt::Debug for PoolInfo<T, I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PoolInfo")
            .field("balance_of", &self.balance_of)
            .field("capital", &self.capital)
            .field("commission", &self.commission)
            .field("slots", &self.slots)
            .finish()
    }
}

impl<T: Config<I>, I: 'static> Clone for IndexOfReason<T, I> {
    fn clone(&self) -> Self {
        Self {
            reason: self.reason,
            index: self.index.clone(),
        }
    }
}

impl<T: Config<I>, I: 'static> Clone for PoolOfReason<T, I> {
    fn clone(&self) -> Self {
        Self {
            reason: self.reason,
            pool: self.pool.clone(),
        }
    }
}

impl<T: Config<I>, I: 'static> Clone for DigestVariant<T, I> {
    fn clone(&self) -> Self {
        match self {
            DigestVariant::Direct(d) => DigestVariant::Direct(d.clone()),
            DigestVariant::Index(d) => DigestVariant::Index(d.clone()),
            DigestVariant::Pool(d) => DigestVariant::Pool(d.clone()),
            DigestVariant::__Ignore(_) => {
                debug_assert!(false, "digest variant phantom variant accessed");
                DigestVariant::__Ignore(PhantomData)
            }
        }
    }
}

impl<T: Config<I>, I: 'static> PartialEq for DigestVariant<T, I> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (DigestVariant::Direct(a), DigestVariant::Direct(b)) => a == b,
            (DigestVariant::Index(a), DigestVariant::Index(b)) => a == b,
            (DigestVariant::Pool(a), DigestVariant::Pool(b)) => a == b,
            (DigestVariant::__Ignore(_), DigestVariant::__Ignore(_)) => {
                debug_assert!(false, "digest variant phantom variant accessed");
                true
            }
            (DigestVariant::__Ignore(_), _) => {
                debug_assert!(false, "digest variant phantom variant accessed");
                false
            }
            (_, DigestVariant::__Ignore(_)) => {
                debug_assert!(false, "digest variant phantom variant accessed");
                false
            }
            _ => false,
        }
    }
}

impl<T: Config<I>, I: 'static> Eq for DigestVariant<T, I> {}

impl<T: Config<I>, I: 'static> Debug for DigestVariant<T, I> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            DigestVariant::Direct(d) => write!(f, "Direct({:?})", d),
            DigestVariant::Index(d) => write!(f, "Index({:?})", d),
            DigestVariant::Pool(d) => write!(f, "Pool({:?})", d),
            DigestVariant::__Ignore(_) => {
                debug_assert!(false, "digest variant phantom variant accessed");
                write!(f, "Invalid Digest Variant")
            }
        }
    }
}

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

#[cfg(test)]
mod tests {

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

    // --- Local crate imports ---
    use crate::{
        balance::{balance_total, mint},
        mock::*,
    };

    // --- FRAME Suite ---
    use frame_suite::{
        commitment::*,
        misc::{Directive, PositionIndex},
    };

    // --- FRAME Support ---
    use frame_support::{
        assert_err, assert_ok,
        traits::tokens::{Fortitude, Precision},
    };

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` DIGEST INFO ```````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn digest_info_balances() {
        commit_test_ext().execute_with(|| {
            set_default_user_balance_and_standard_hold(ALICE).unwrap();
            set_default_user_balance_and_standard_hold(ALAN).unwrap();
            set_default_user_balance_and_standard_hold(BOB).unwrap();

            let alice_position = Position::default();
            Pallet::place_commit(
                &ALICE,
                &ESCROW,
                &CONTRACT_FREELANCE,
                STANDARD_COMMIT,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let alan_position = Position::position_of(1).unwrap();
            Pallet::place_commit_of_variant(
                &ALAN,
                &ESCROW,
                &CONTRACT_FREELANCE,
                LARGE_COMMIT,
                &alan_position,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let bob_position = Position::position_of(2).unwrap();
            Pallet::place_commit_of_variant(
                &BOB,
                &GOVERNANCE,
                &PROPOSAL_TREASURY_SPEND,
                LARGE_COMMIT,
                &bob_position,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let digest_info = DigestMap::get((ESCROW, CONTRACT_FREELANCE)).unwrap();
            let balances = digest_info.balances().unwrap();
            // ALICE balances at index 0 (Position, LazyBalanceOf)
            let alice_balances = balances.get(0).unwrap();
            assert_eq!(alice_balances.0, alice_position);
            let alice_bal = digest_info.get_balance(&alice_position).unwrap();
            assert_eq!(alice_balances.1, *alice_bal);
            // ALAN balances at index 1 (Position, LazyBalanceOf)
            let alan_balances = balances.get(1).unwrap();
            assert_eq!(alan_balances.0, alan_position);
            let alan_bal = digest_info.get_balance(&alan_position).unwrap();
            assert_eq!(alan_balances.1, *alan_bal);

            // BOB's digest info
            let digest_info = DigestMap::get((GOVERNANCE, PROPOSAL_TREASURY_SPEND)).unwrap();
            let balances = digest_info.balances().unwrap();
            // BOB's balances at index 0 (Position, LazyBalanceOf)
            let bob_balances = balances.get(0).unwrap();
            assert_eq!(bob_balances.0, bob_position);
            let bob_bal = digest_info.get_balance(&bob_position).unwrap();
            assert_eq!(bob_balances.1, *bob_bal);
        })
    }

    #[test]
    fn digest_info_get_balance() {
        commit_test_ext().execute_with(|| {
            set_default_user_balance_and_standard_hold(ALICE).unwrap();

            let alice_position = Position::default();
            Pallet::place_commit(
                &ALICE,
                &ESCROW,
                &CONTRACT_FREELANCE,
                STANDARD_COMMIT,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let digest_info = DigestMap::get((ESCROW, CONTRACT_FREELANCE)).unwrap();
            let alice_balance = digest_info.get_balance(&alice_position).unwrap();

            let alice_bal_total =
                balance_total(alice_balance, &alice_position, &CONTRACT_FREELANCE).unwrap();
            assert_eq!(alice_bal_total, STANDARD_COMMIT);
        })
    }

    #[test]
    fn digest_info_mut_balance() {
        commit_test_ext().execute_with(|| {
            set_default_user_balance_and_standard_hold(ALICE).unwrap();

            let alice_position = Position::default();
            Pallet::place_commit(
                &ALICE,
                &ESCROW,
                &CONTRACT_FREELANCE,
                STANDARD_COMMIT,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let mut digest_info = DigestMap::get((ESCROW, CONTRACT_FREELANCE)).unwrap();
            let alice_mut_balance = digest_info.mut_balance(&alice_position).unwrap();

            let mint_val = 125;
            mint(
                alice_mut_balance,
                &alice_position,
                &CONTRACT_FREELANCE,
                &mint_val,
                &Directive::new(Precision::Exact, Fortitude::Force),
            )
            .unwrap();
            let alice_bal_total =
                balance_total(alice_mut_balance, &alice_position, &CONTRACT_FREELANCE).unwrap();
            assert_ne!(alice_bal_total, STANDARD_COMMIT);

            assert_eq!(alice_bal_total, STANDARD_COMMIT + mint_val);
        })
    }

    #[test]
    fn digest_info_reveal() {
        commit_test_ext().execute_with(|| {
            set_default_user_balance_and_standard_hold(ALICE).unwrap();
            set_default_user_balance_and_standard_hold(ALAN).unwrap();
            set_default_user_balance_and_standard_hold(BOB).unwrap();

            let alice_position = Position::default();
            Pallet::place_commit(
                &ALICE,
                &ESCROW,
                &CONTRACT_FREELANCE,
                STANDARD_COMMIT,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let alan_position = Position::position_of(1).unwrap();
            Pallet::place_commit_of_variant(
                &ALAN,
                &ESCROW,
                &CONTRACT_FREELANCE,
                LARGE_COMMIT,
                &alan_position,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let bob_position = Position::position_of(2).unwrap();
            Pallet::place_commit_of_variant(
                &BOB,
                &GOVERNANCE,
                &PROPOSAL_TREASURY_SPEND,
                LARGE_COMMIT,
                &bob_position,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let digest_info = DigestMap::get((ESCROW, CONTRACT_FREELANCE)).unwrap();
            let reveal_balances = digest_info.reveal();

            assert_eq!(reveal_balances.len(), 2);

            let alice_total_bal =
                balance_total(&reveal_balances[0], &alice_position, &CONTRACT_FREELANCE).unwrap();
            assert_eq!(alice_total_bal, STANDARD_COMMIT,);

            let alan_total_bal =
                balance_total(&reveal_balances[1], &alan_position, &CONTRACT_FREELANCE).unwrap();
            assert_eq!(alan_total_bal, LARGE_COMMIT,);

            let digest_info = DigestMap::get((GOVERNANCE, PROPOSAL_TREASURY_SPEND)).unwrap();
            let reveal_balances = digest_info.reveal();

            assert_eq!(reveal_balances.len(), 3);
            assert_eq!(
                balance_total(&reveal_balances[0], &bob_position, &PROPOSAL_TREASURY_SPEND),
                Ok(0)
            );
            assert_eq!(
                balance_total(&reveal_balances[1], &bob_position, &PROPOSAL_TREASURY_SPEND),
                Ok(0)
            );

            let bob_total_bal =
                balance_total(&reveal_balances[2], &bob_position, &PROPOSAL_TREASURY_SPEND)
                    .unwrap();
            assert_eq!(bob_total_bal, LARGE_COMMIT,);
        })
    }

    #[test]
    fn digest_info_init_balance() {
        commit_test_ext().execute_with(|| {
            let mut digest_info = DigestInfo::default();

            let pos0 = Position::position_of(0).unwrap();
            let pos1 = Position::position_of(1).unwrap();
            let pos2 = Position::position_of(2).unwrap();

            // before init -> nothing exists
            assert!(digest_info.get_balance(&pos0).is_none());
            assert!(digest_info.get_balance(&pos1).is_none());
            assert!(digest_info.get_balance(&pos2).is_none());

            assert_ok!(digest_info.init_balance(&pos1));

            // after init -> all slots up to index must exist
            assert!(digest_info.get_balance(&pos0).is_some());
            assert!(digest_info.get_balance(&pos1).is_some());
            assert!(digest_info.get_balance(&pos2).is_none());

            assert_eq!(digest_info.reveal().len(), 2);

            assert_ok!(digest_info.init_balance(&pos2));
            assert!(digest_info.get_balance(&pos2).is_some());

            assert_eq!(digest_info.reveal().len(), 3);
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` COMMITS ```````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn commits_new_success() {
        commit_test_ext().execute_with(|| {
            let commit_ins = CommitInstance::default();

            let commits = Commits::new(commit_ins.clone()).unwrap();
            assert_eq!(commits.0.len(), 1);

            let init_commit = commits.0.get(0).unwrap();
            assert_eq!(init_commit.clone(), commit_ins);
        })
    }

    #[test]
    fn commits_success() {
        commit_test_ext().execute_with(|| {
            let derive_bal_a = CommitInstance::default();
            let mut commits = Commits::new(derive_bal_a.clone()).unwrap();

            let commits_vec = commits.commits();
            assert_eq!(commits_vec, vec![derive_bal_a.clone()]);

            let derive_bal_b = CommitInstance::default();
            let derive_bal_c = CommitInstance::default();
            commits.add_commit(derive_bal_b.clone()).unwrap();
            commits.add_commit(derive_bal_c.clone()).unwrap();

            let commits_vec = commits.commits();
            assert_eq!(commits_vec, vec![derive_bal_a, derive_bal_b, derive_bal_c]);
        })
    }

    #[test]
    fn add_commit_success() {
        commit_test_ext().execute_with(|| {
            let derive_bal_a = CommitInstance::default();
            let mut commits = Commits::new(derive_bal_a.clone()).unwrap();

            let commits_vec = commits.commits();
            assert_eq!(commits_vec, vec![derive_bal_a.clone()]);

            let derive_bal_b = CommitInstance::default();
            let derive_bal_c = CommitInstance::default();
            commits.add_commit(derive_bal_b.clone()).unwrap();
            commits.add_commit(derive_bal_c.clone()).unwrap();

            let commits_vec = commits.commits();
            assert_eq!(commits_vec, vec![derive_bal_a, derive_bal_b, derive_bal_c]);

            let derive_bal_d = CommitInstance::default();
            assert_err!(commits.add_commit(derive_bal_d), Error::MaxCommitsReached);
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` COMMIT INFO ```````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn commit_info_new_success() {
        commit_test_ext().execute_with(|| {
            let instance = CommitInstance::default();
            let variant = Position::position_of(0).unwrap();
            let commit_info = CommitInfo::new(VALIDATOR_ALPHA, instance.clone(), variant).unwrap();

            assert_eq!(commit_info.commits().len(), 1);
            assert_eq!(commit_info.commits(), vec![instance]);
            assert_eq!(commit_info.digest(), VALIDATOR_ALPHA);
            assert_eq!(commit_info.variant(), variant);
        })
    }

    #[test]
    fn commit_info_add_commit_success() {
        commit_test_ext().execute_with(|| {
            let instance_a = CommitInstance::default();
            let variant = Position::position_of(0).unwrap();
            let mut commit_info =
                CommitInfo::new(VALIDATOR_ALPHA, instance_a.clone(), variant).unwrap();

            assert_eq!(commit_info.commits().len(), 1);
            assert_eq!(commit_info.commits(), vec![instance_a.clone()]);

            let instance_b = CommitInstance::default();
            let instance_c = CommitInstance::default();
            commit_info.add_commit(instance_b.clone()).unwrap();
            commit_info.add_commit(instance_c.clone()).unwrap();

            assert_eq!(commit_info.commits().len(), 3);
            assert_eq!(
                commit_info.commits(),
                vec![instance_a, instance_b, instance_c]
            );
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` ENTRY INFO ```````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn entry_info_eq_true() {
        commit_test_ext().execute_with(|| {
            let variant = Position::position_of(0).unwrap();
            let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
            let entry_info_b = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

            assert!(entry_info_a.eq(&entry_info_b));
        })
    }

    #[test]
    fn entry_info_eq_false() {
        commit_test_ext().execute_with(|| {
            let variant = Position::position_of(0).unwrap();
            let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
            let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 100, variant).unwrap();

            assert!(!entry_info_a.eq(&entry_info_b));
        })
    }

    #[test]
    fn entry_info_new_success() {
        commit_test_ext().execute_with(|| {
            let variant = Position::position_of(0).unwrap();
            let entry_info = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

            assert_eq!(entry_info.digest(), VALIDATOR_ALPHA);
            assert_eq!(entry_info.shares, 100);
            assert_eq!(entry_info.variant(), variant);
        })
    }

    #[test]
    fn entry_info_new_err_share_cannot_be_zero() {
        let variant = Position::position_of(0).unwrap();
        assert_err!(
            EntryInfo::new(VALIDATOR_ALPHA, 0, variant),
            Error::ShareCannotBeZero
        );
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````````` ENTRIES ```````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn entries_eq_true() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let entries_a = Entries::new(vec![entry_info_a]).unwrap();
        let entries_b = Entries::new(vec![entry_info_b]).unwrap();

        assert!(entries_a.eq(&entries_b));
    }

    #[test]
    fn entries_eq_false() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let entries_a = Entries::new(vec![entry_info_a]).unwrap();
        let entries_b = Entries::new(vec![entry_info_b]).unwrap();

        assert!(!entries_a.eq(&entries_b));
    }

    #[test]
    fn entries_new_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();

        assert_eq!(entries.0.get(0), Some(&entry_info_a));
        assert_eq!(entries.0.get(1), Some(&entry_info_b));
        assert_eq!(entries.0.get(2), Some(&entry_info_c));
        assert_eq!(entries.0.get(3), None);
    }

    #[test]
    fn entries_new_err_duplicate_entry() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let _entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_b.clone(),
        ]);

        assert!(entries.is_err());
        assert_err!(entries, Error::DuplicateEntry);
    }

    #[test]
    fn entries_new_err_max_entries_reached() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();
        let entry_info_d = EntryInfo::new(VALIDATOR_DELTA, 125, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
            entry_info_d.clone(),
        ]);

        assert!(entries.is_err());
        assert_err!(entries, Error::MaxEntriesReached);
    }

    #[test]
    fn entries_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();

        let actual_entries = entries.entries();
        let expected_entries = vec![entry_info_a, entry_info_b, entry_info_c];
        assert_eq!(actual_entries, expected_entries);
    }

    #[test]
    fn add_entry_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone()]).unwrap();

        let actual_entries = entries.entries();
        let expected_entries = vec![entry_info_a.clone()];
        assert_eq!(actual_entries, expected_entries);

        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        entries.add_entry(entry_info_b.clone()).unwrap();

        let actual_entries = entries.entries();
        let expected_entries = vec![entry_info_a.clone(), entry_info_b.clone()];
        assert_eq!(actual_entries, expected_entries);

        entries.add_entry(entry_info_c.clone()).unwrap();

        let actual_entries = entries.entries();
        let expected_entries = vec![entry_info_a, entry_info_b, entry_info_c];
        assert_eq!(actual_entries, expected_entries);
    }

    #[test]
    fn add_entry_err_duplicate_entry() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone()]).unwrap();

        assert_err!(entries.add_entry(entry_info_a), Error::DuplicateEntry);
    }

    #[test]
    fn add_entry_err_max_entries_reached() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let mut entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();

        let entry_info_d = EntryInfo::new(VALIDATOR_DELTA, 125, variant).unwrap();

        assert_err!(entries.add_entry(entry_info_d), Error::MaxEntriesReached);
    }

    #[test]
    fn remove_entry_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let mut entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();

        let actual_entries = entries.entries();
        let expected_entries = vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ];
        assert_eq!(actual_entries, expected_entries);

        entries.remove_entry(&VALIDATOR_ALPHA).unwrap();

        let actual_entries = entries.entries();
        let expected_entries = vec![entry_info_b.clone(), entry_info_c.clone()];
        assert_eq!(actual_entries, expected_entries);

        entries.remove_entry(&VALIDATOR_GAMMA).unwrap();

        let actual_entries = entries.entries();
        let expected_entries = vec![entry_info_b.clone()];
        assert_eq!(actual_entries, expected_entries);
    }

    #[test]
    fn remove_entry_err_entry_of_index_not_found() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        assert_err!(
            entries.remove_entry(&VALIDATOR_GAMMA),
            Error::EntryOfIndexNotFound
        );
    }

    #[test]
    fn remove_entry_err_empty_entries_not_allowed() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone()]).unwrap();

        assert_err!(
            entries.remove_entry(&VALIDATOR_ALPHA),
            Error::EmptyEntriesNotAllowed
        );
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // `````````````````````````````````` INDEX INFO `````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn index_info_eq_true() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let mut entries_a = Entries::new(vec![entry_info_a]).unwrap();
        let mut entries_b = Entries::new(vec![entry_info_b]).unwrap();

        let index_info_a = IndexInfo::new(&mut entries_a).unwrap();
        let index_info_b = IndexInfo::new(&mut entries_b).unwrap();

        assert!(index_info_a.eq(&index_info_b));
    }

    #[test]
    fn index_info_eq_false() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let mut entries_a = Entries::new(vec![entry_info_a]).unwrap();
        let mut entries_b = Entries::new(vec![entry_info_b]).unwrap();

        let index_info_a = IndexInfo::new(&mut entries_a).unwrap();
        let index_info_b = IndexInfo::new(&mut entries_b).unwrap();

        assert!(!index_info_a.eq(&index_info_b));
    }

    #[test]
    fn index_info_new_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();
        let index_info = IndexInfo::new(&mut entries).unwrap();

        assert_eq!(index_info.capital(), 150);
        assert_eq!(index_info.principal(), 0);
        assert_eq!(index_info.entries(), vec![entry_info_a, entry_info_b]);
    }

    #[test]
    fn index_info_new_err_capital_overflowed() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, MAX_SHARES, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();
        let index_info = IndexInfo::new(&mut entries);
        assert!(index_info.is_err());
        assert_err!(index_info, Error::CapitalOverflowed);
    }

    #[test]
    fn index_info_reveal_entries() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();
        let index_info = IndexInfo::new(&mut entries).unwrap();

        let reveal_entries = index_info.reveal_entries();
        assert_eq!(reveal_entries, entries);
    }

    #[test]
    fn entry_exists_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();
        let index_info = IndexInfo::new(&mut entries).unwrap();

        assert_ok!(index_info.entry_exists(&VALIDATOR_ALPHA));
        assert_ok!(index_info.entry_exists(&VALIDATOR_BETA));
    }

    #[test]
    fn entry_exists_err_entry_index_not_found() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let mut entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();
        let index_info = IndexInfo::new(&mut entries).unwrap();

        assert_err!(
            index_info.entry_exists(&VALIDATOR_GAMMA),
            Error::EntryOfIndexNotFound
        );
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // `````````````````````````````````` SLOT INFO ``````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn slot_info_eq_true() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();

        assert!(slot_info_a.eq(&slot_info_b));
    }

    #[test]
    fn slot_info_eq_false() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();

        assert!(!slot_info_a.eq(&slot_info_b));
    }

    #[test]
    fn slot_info_from_entry_success() {
        let variant = Position::position_of(0).unwrap();

        let entry = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let slot_info: SlotInfo = entry.clone().into();

        assert_eq!(slot_info.digest(), VALIDATOR_ALPHA);
        assert_eq!(slot_info.shares(), 100);
        assert_eq!(slot_info.variant(), variant);

        let default_commit = CommitInstance::default();
        assert_eq!(slot_info.commit(), default_commit);
    }

    #[test]
    fn slot_info_set_slot_commit() {
        commit_test_ext().execute_with(|| {
            set_default_user_balance_and_standard_hold(ALICE).unwrap();
            let variant = Position::position_of(0).unwrap();
            let entry = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
            let mut slot_info: SlotInfo = entry.clone().into();

            let default_commit = CommitInstance::default();
            assert_eq!(slot_info.commit(), default_commit);

            let alice_position = Position::position_of(1).unwrap();
            Pallet::place_commit_of_variant(
                &ALICE,
                &GOVERNANCE,
                &PROPOSAL_TREASURY_SPEND,
                LARGE_COMMIT,
                &alice_position,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let commit_info = CommitMap::get((ALICE, GOVERNANCE)).unwrap();
            let new_instance = commit_info.commits.0.get(0).unwrap();

            slot_info.set_slot_commit(new_instance.clone());
            assert_ne!(slot_info.commit(), default_commit);
            assert_eq!(slot_info.commit(), new_instance.clone());
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ```````````````````````````````````` SLOTS ````````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn slots_eq_true() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let entries_a = Entries::new(vec![entry_info_a]).unwrap();
        let entries_b = Entries::new(vec![entry_info_b]).unwrap();

        let slots_a = Slots::try_from(entries_a).unwrap();
        let slots_b = Slots::try_from(entries_b).unwrap();

        assert!(slots_a.eq(&slots_b));
    }

    #[test]
    fn slots_eq_false() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let entries_a = Entries::new(vec![entry_info_a]).unwrap();
        let entries_b = Entries::new(vec![entry_info_b]).unwrap();

        let slots_a = Slots::try_from(entries_a).unwrap();
        let slots_b = Slots::try_from(entries_b).unwrap();

        assert!(!slots_a.eq(&slots_b));
    }

    #[test]
    fn slots_success() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();

        let slots = Slots::try_from(entries).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();
        let slot_info_c: SlotInfo = entry_info_c.into();

        let actual_slots = slots.slots();
        let expected_slots = vec![slot_info_a, slot_info_b, slot_info_c];
        assert_eq!(actual_slots, expected_slots);
    }

    #[test]
    fn add_slot_success() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let mut slots = Slots::try_from(entries).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();

        let actual_slots = slots.slots();
        let expected_slots = vec![slot_info_a.clone(), slot_info_b.clone()];
        assert_eq!(actual_slots, expected_slots);

        slots.add_slot(entry_info_c.clone()).unwrap();

        let slot_info_c: SlotInfo = entry_info_c.into();

        let actual_slots = slots.slots();
        let expected_slots = vec![slot_info_a, slot_info_b, slot_info_c];
        assert_eq!(actual_slots, expected_slots);
    }

    #[test]
    fn add_slot_err_max_slots_reached() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();
        let entry_info_d = EntryInfo::new(VALIDATOR_DELTA, 125, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let mut slots = Slots::try_from(entries).unwrap();

        slots.add_slot(entry_info_c.clone()).unwrap();

        assert_err!(slots.add_slot(entry_info_d), Error::MaxSlotsReached);
    }

    #[test]
    fn add_slot_err_duplicate_slot() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let _entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let mut slots = Slots::try_from(entries).unwrap();

        assert_err!(slots.add_slot(entry_info_b), Error::DuplicateSlot);
    }

    #[test]
    fn remove_slot_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();
        let mut slots = Slots::try_from(entries).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();
        let slot_info_c: SlotInfo = entry_info_c.into();

        let actual_slots = slots.slots();
        let expected_slots = vec![
            slot_info_a.clone(),
            slot_info_b.clone(),
            slot_info_c.clone(),
        ];
        assert_eq!(actual_slots, expected_slots);

        slots.remove_slot(&VALIDATOR_ALPHA).unwrap();

        let actual_slots = slots.slots();
        let expected_slots = vec![slot_info_b.clone(), slot_info_c.clone()];
        assert_eq!(actual_slots, expected_slots);

        slots.remove_slot(&VALIDATOR_GAMMA).unwrap();

        let actual_slots = slots.slots();
        let expected_slots = vec![slot_info_b.clone()];
        assert_eq!(actual_slots, expected_slots);
    }

    #[test]
    fn remove_slot_err_slot_of_pool_not_found() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let mut slots = Slots::try_from(entries).unwrap();

        assert_err!(
            slots.remove_slot(&VALIDATOR_GAMMA),
            Error::SlotOfPoolNotFound
        );
    }

    #[test]
    fn remove_slot_err_empty_slots_not_allowed() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone()]).unwrap();

        let mut slots = Slots::try_from(entries).unwrap();

        assert_err!(
            slots.remove_slot(&VALIDATOR_ALPHA),
            Error::EmptySlotsNotAllowed
        );
    }

    #[test]
    fn set_slot_commit_success() {
        commit_test_ext().execute_with(|| {
            set_default_user_balance_and_standard_hold(ALICE).unwrap();
            let alice_position = Position::position_of(1).unwrap();
            Pallet::place_commit_of_variant(
                &ALICE,
                &GOVERNANCE,
                &PROPOSAL_TREASURY_SPEND,
                LARGE_COMMIT,
                &alice_position,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let commit_info = CommitMap::get((ALICE, GOVERNANCE)).unwrap();
            let new_instance = commit_info.commits.0.get(0).unwrap();

            let variant = Position::position_of(0).unwrap();

            let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
            let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
            let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 75, variant).unwrap();

            let entries = Entries::new(vec![
                entry_info_a.clone(),
                entry_info_b.clone(),
                entry_info_c.clone(),
            ])
            .unwrap();

            let mut slots = Slots::try_from(entries).unwrap();
            let slot_info_a: SlotInfo = entry_info_a.into();
            let slot_info_b: SlotInfo = entry_info_b.into();
            let slot_info_c: SlotInfo = entry_info_c.into();

            let actual_slots = slots.slots();
            let expected_slots = vec![
                slot_info_a.clone(),
                slot_info_b.clone(),
                slot_info_c.clone(),
            ];
            assert_eq!(actual_slots, expected_slots);

            slots
                .set_slot_commit(&VALIDATOR_BETA, new_instance.clone())
                .unwrap();

            let actual_slots = slots.slots();
            let new_slot_b = &actual_slots[1];
            assert_ne!(new_slot_b.clone(), slot_info_b.clone());
            let expected_slots = vec![slot_info_a.clone(), new_slot_b.clone(), slot_info_c.clone()];
            assert_eq!(actual_slots, expected_slots);
        })
    }

    #[test]
    fn set_slot_commit_err_slot_of_pool_not_found() {
        commit_test_ext().execute_with(|| {
            set_default_user_balance_and_standard_hold(ALICE).unwrap();
            let alice_position = Position::position_of(1).unwrap();
            Pallet::place_commit_of_variant(
                &ALICE,
                &GOVERNANCE,
                &PROPOSAL_TREASURY_SPEND,
                LARGE_COMMIT,
                &alice_position,
                &Directive::new(Precision::BestEffort, Fortitude::Force),
            )
            .unwrap();

            let commit_info = CommitMap::get((ALICE, GOVERNANCE)).unwrap();
            let new_instance = commit_info.commits.0.get(0).unwrap();

            let variant = Position::position_of(0).unwrap();

            let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
            let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

            let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

            let mut slots = Slots::try_from(entries).unwrap();
            let slot_info_a: SlotInfo = entry_info_a.into();
            let slot_info_b: SlotInfo = entry_info_b.into();

            let actual_slots = slots.slots();
            let expected_slots = vec![slot_info_a.clone(), slot_info_b.clone()];
            assert_eq!(actual_slots, expected_slots);

            let result = slots.set_slot_commit(&VALIDATOR_GAMMA, new_instance.clone());
            assert_err!(result, Error::SlotOfPoolNotFound);
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ```````````````````````````````````` POOL INFO ````````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn pool_info_eq_true() {
        let variant = Position::position_of(0).unwrap();

        let entry_info = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entries = Entries::new(vec![entry_info]).unwrap();

        let pool_info_a = PoolInfo::new(entries.clone(), COMMISSION_ZERO).unwrap();
        let pool_info_b = PoolInfo::new(entries, COMMISSION_ZERO).unwrap();

        assert!(pool_info_a.eq(&pool_info_b));
    }

    #[test]
    fn pool_info_eq_false() {
        let variant = Position::position_of(0).unwrap();
        let entry_info = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entries = Entries::new(vec![entry_info]).unwrap();

        let pool_info_a = PoolInfo::new(entries.clone(), COMMISSION_ZERO).unwrap();
        let pool_info_b = PoolInfo::new(entries, COMMISSION_STANDARD).unwrap();

        assert!(!pool_info_a.eq(&pool_info_b));
    }

    #[test]
    fn pool_info_new_success() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let pool = PoolInfo::new(entries, COMMISSION_STANDARD).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();

        assert_eq!(pool.balance_of, LazyBalance::default());
        assert_eq!(pool.capital(), 150);
        assert_eq!(pool.commission, COMMISSION_STANDARD);
        assert_eq!(pool.slots().len(), 2);
        assert_eq!(pool.slots(), vec![slot_info_a, slot_info_b]);
    }

    #[test]
    fn pool_info_new_err_capital_overflowed() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, MAX_SHARES, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let pool = PoolInfo::new(entries, COMMISSION_STANDARD);
        assert!(pool.is_err());
        assert_err!(pool, Error::CapitalOverflowed);
    }

    #[test]
    fn pool_info_slots_success() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 50, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 150, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();

        let pool = PoolInfo::new(entries, COMMISSION_STANDARD).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();
        let slot_info_c: SlotInfo = entry_info_c.into();

        let actual_slots = pool.slots();
        let expected_slots = vec![slot_info_a, slot_info_b, slot_info_c];
        assert_eq!(actual_slots, expected_slots);
    }

    #[test]
    fn pool_info_balance_reset_success() {
        let variant = Position::position_of(0).unwrap();
        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 200, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a, entry_info_b]).unwrap();
        let mut pool = PoolInfo::new(entries, COMMISSION_ZERO).unwrap();

        pool.balance_reset();

        assert_eq!(pool.balance_of, Default::default());

        for slot in pool.slots() {
            assert_eq!(slot.commit(), Default::default());
        }
    }

    #[test]
    fn pool_info_add_slot_success() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 100, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let mut pool = PoolInfo::new(entries, COMMISSION_ZERO).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();

        assert_eq!(pool.capital(), 200);
        assert_eq!(pool.slots().len(), 2);

        let actual_slots = pool.slots();
        let expected_slots = vec![slot_info_a.clone(), slot_info_b.clone()];
        assert_eq!(actual_slots, expected_slots);

        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 50, variant).unwrap();
        assert_ok!(pool.add_slot(entry_info_c.clone()));
        let slot_info_c: SlotInfo = entry_info_c.into();

        assert_eq!(pool.capital(), 250);
        assert_eq!(pool.slots().len(), 3);
        let actual_slots = pool.slots();
        let expected_slots = vec![slot_info_a.clone(), slot_info_b.clone(), slot_info_c];
        assert_eq!(actual_slots, expected_slots);
    }

    #[test]
    fn pool_info_add_slot_err_capital_overflowed() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 100, variant).unwrap();

        let entries = Entries::new(vec![entry_info_a.clone(), entry_info_b.clone()]).unwrap();

        let mut pool = PoolInfo::new(entries, COMMISSION_ZERO).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();

        assert_eq!(pool.capital(), 200);
        assert_eq!(pool.slots().len(), 2);

        let actual_slots = pool.slots();
        let expected_slots = vec![slot_info_a.clone(), slot_info_b.clone()];
        assert_eq!(actual_slots, expected_slots);

        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, MAX_SHARES, variant).unwrap();
        assert_err!(pool.add_slot(entry_info_c), Error::CapitalOverflowed);
    }

    #[test]
    fn pool_info_remove_slot_success() {
        let variant = Position::position_of(0).unwrap();

        let entry_info_a = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entry_info_b = EntryInfo::new(VALIDATOR_BETA, 100, variant).unwrap();
        let entry_info_c = EntryInfo::new(VALIDATOR_GAMMA, 50, variant).unwrap();

        let entries = Entries::new(vec![
            entry_info_a.clone(),
            entry_info_b.clone(),
            entry_info_c.clone(),
        ])
        .unwrap();

        let mut pool = PoolInfo::new(entries, COMMISSION_ZERO).unwrap();
        let slot_info_a: SlotInfo = entry_info_a.into();
        let slot_info_b: SlotInfo = entry_info_b.into();
        let slot_info_c: SlotInfo = entry_info_c.into();

        assert_eq!(pool.capital(), 250);
        assert_eq!(pool.slots().len(), 3);

        let actual_slots = pool.slots();
        let expected_slots = vec![
            slot_info_a.clone(),
            slot_info_b.clone(),
            slot_info_c.clone(),
        ];
        assert_eq!(actual_slots, expected_slots);

        pool.remove_slot(&VALIDATOR_ALPHA).unwrap();
        let actual_slots = pool.slots();
        let expected_slots = vec![slot_info_b.clone(), slot_info_c.clone()];
        assert_eq!(actual_slots, expected_slots);

        assert_eq!(pool.capital(), 150);
        assert_eq!(pool.slots().len(), 2);

        pool.remove_slot(&VALIDATOR_GAMMA).unwrap();
        let actual_slots = pool.slots();
        let expected_slots = vec![slot_info_b.clone()];
        assert_eq!(actual_slots, expected_slots);

        assert_eq!(pool.capital(), 100);
        assert_eq!(pool.slots().len(), 1);
    }

    #[test]
    fn pool_info_slot_exists_success() {
        let variant = Position::position_of(0).unwrap();

        let entry_info = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entries = Entries::new(vec![entry_info]).unwrap();

        let pool = PoolInfo::new(entries, COMMISSION_ZERO).unwrap();

        assert_ok!(pool.slot_exists(&VALIDATOR_ALPHA));
    }

    #[test]
    fn pool_info_slot_exists_err_not_found() {
        let variant = Position::position_of(0).unwrap();

        let entry_info = EntryInfo::new(VALIDATOR_ALPHA, 100, variant).unwrap();
        let entries = Entries::new(vec![entry_info]).unwrap();

        let pool = PoolInfo::new(entries, COMMISSION_ZERO).unwrap();

        assert_err!(pool.slot_exists(&VALIDATOR_BETA), Error::SlotOfPoolNotFound);
    }
}