pallet-chain-manager 0.1.1

A session-driven orchestration pallet coordinating validator selection, participation, and settlement using offchain workers and pluggable models
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
// 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

// ===============================================================================
// `````````````````````````````` BLOCKCHAIN ACTORS ``````````````````````````````
// ===============================================================================

//! Provides the **core runtime logic for managing blockchain actors**
//! (authors/validators) across their full lifecycle.
//!
//! - **Election orchestration** (via [`ElectAuthors`])
//! - **Affidavit submission and validation** (via [`ElectionAffidavits`])
//! - **Contribution tracking** through session-scoped points (via
//!   [`AuthorPoints`], although swappable via [`Config::PointsAdapter`])
//! - **Reward scheduling** based on participation (via [`RewardAuthors`])
//! - **Penalty scheduling** for misbehavior (via [`PenalizeAuthors`])
//!
//! The module acts as a **bridge layer** between generic trait abstractions and
//! pallet-specific storage, timing, and role-management systems.
//!
//! ## Design Overview
//!
//! - **Session-driven lifecycle**:
//!   All operations (affidavits, elections, points, rewards, penalties)
//!   are scoped to sessions and aligned with deterministic session timing.
//!
//! - **Time-gated execution**:
//!   Affidavit submission and election processing are strictly bounded by
//!   windows derived from session start and configurable percentages.
//!
//! - **Separation of concerns**:
//!   - This module coordinates *when* and *what* to execute.
//!   - External adapters/plugins define *how* logic is executed:
//!     - Election logic: [`Config::ElectionAdapter`]
//!     - Reward logic: [`Config::RewardModel`], [`Config::InflationModel`]
//!     - Penalty logic: [`Config::PenaltyModel`]
//!
//! - **Deterministic and auditable**:
//!   All operations avoid side effects and remain reproducible across nodes.
//!
//! - **Deferred execution model**:
//!   Rewards and penalties are **scheduled**, not immediately finalized,
//!   allowing downstream systems to aggregate, adjust, or revert them.

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

// --- Local crate imports ---
use crate::{
    types::*, AffidavitKeys, AllowAffidavits, AuthorAffidavits,
    BlockPointsStore, Config, CurrentSession, Error, Event, Internals, Pallet,
};

// --- FRAME Suite ---
use frame_suite::{blockchain::*, elections::*, roles::*};

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

// --- Substrate primitives ---
use sp_core::Get;
use sp_runtime::{
    traits::{One, Saturating},
    DispatchError, DispatchResult, Vec, WeakBoundedVec,
};

// ===============================================================================
// ```````````````````````````````` ELECT AUTHORS ````````````````````````````````
// ===============================================================================

/// Implementation of the [`ElectAuthors`] trait for the pallet internal type
/// (not exposable).
///
/// This implementation bridges the generic [`ElectAuthors`] abstraction
/// with the pallet's internal affidavit and role-management infrastructure,
/// coordinating **candidate selection**, **time-gated election execution**,
/// and **result revelation** for upcoming sessions.
///
/// ## Design Notes
/// - Elections are **session-scoped** and always target the *upcoming* session.
/// - Only authors who have successfully submitted affidavits are eligible.
/// - All election logic is **time-gated** and derived from session timing,
///   affidavit windows, and election offsets.
/// - This layer is **deterministic**; it does not perform probabilistic or
///   stateful election logic.
///
/// ## Implementation Notes
/// - This implementation does **not** execute the election algorithm itself.
/// - All ranking, scoring, and selection logic is delegated to the configured
///   [`ElectionManager`] via the pallet's [`Config::ElectionAdapter`].
///
/// - This layer is responsible only for:
///   - Validating election timing
///   - Preparing candidate inputs
///   - Revealing results from the election manager
impl<T: Config> ElectAuthors<AuthorOf<T>, ElectionVia<T>> for Internals<T> {
    /// Type representing the prepared election candidates.
    ///
    /// Typically a vector of author's ID and their corresponding election weights.
    type Candidates = ElectionParams<T>;

    /// Type representing the final elected author set.
    ///
    /// Typically a vector of author IDs.
    type Elected = ElectionElects<T>;

    /// Prepares election candidates via the configured election manager.
    ///
    /// - Acts as a thin delegation layer to [`ElectionManager::prepare`].
    /// - Any failure here prevents election execution.
    /// - Typically runs the election algorithm and stores the election result.
    /// - Inconsistencies return explicit errors.
    fn prepare_authors(candidates: Self::Candidates) -> DispatchResult {
        T::ElectionAdapter::prepare(candidates)?;
        Ok(())
    }

    /// Checks whether the election can be processed at the current block.
    ///
    /// ## Parameters
    /// - `runner`: Optional executor of the election (runtime or author-driven).
    ///   This is **not validated here**, but is assumed to be the entity
    ///   responsible for executing the election, as permitted by the caller.
    ///
    /// ## Validation
    /// - Ensures the affidavit window is valid (`start < end`).
    /// - Ensures the current block is within the affidavit window.
    /// - Ensures the election window has started.
    /// - Ensures the election has not yet ended (bounded by affidavit end).
    ///
    /// Violations return explicit, user-facing errors.
    fn can_process_election(_runner: &Option<AuthorOf<T>>) -> DispatchResult {
        // Compute affidavit submission window
        let aff_window = Pallet::<T>::compute_affidavit_window()?;
        let start_affidavit = aff_window.start;
        let end_affidavit = aff_window.end;

        // Validate affidavit window configuration
        let invariant = start_affidavit < end_affidavit;
        debug_assert!(
            invariant,
            "Affidavit submission period is invalid, starts at block {:?} and ends at {:?}",
            start_affidavit, end_affidavit
        );
        ensure!(invariant, Error::<T>::InvalidAffidavitPeriod);

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

        // Ensure affidavit window has begun
        ensure!(
            start_affidavit <= current_block,
            Error::<T>::NotAffidavitPeriod
        );

        // Compute election start within affidavit window
        let election_window = Pallet::<T>::compute_election_window()?;
        let start_election = election_window.start;

        // Ensure election has started
        ensure!(
            start_election <= current_block,
            Error::<T>::NotElectionPeriod
        );

        // Ensure election has not ended
        ensure!(
            current_block <= end_affidavit,
            Error::<T>::ElectionPeriodEnded
        );

        Ok(())
    }

    /// Prepares the final list of candidates for election.
    ///
    /// ## Overview
    /// - Iterates all affidavits submitted for the upcoming session.
    /// - Extracts and normalizes each author's election weights.
    /// - Produces a deterministic candidate list for the election manager.
    ///
    /// ## Notes
    /// - Only affidavit-submitting authors are included.
    /// - This function performs **no ranking or filtering**.
    /// - Ordering guarantees are provided by downstream election logic.
    fn prepare_candidates() -> Result<Self::Candidates, DispatchError> {
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());

        // Iterate affidavits for the upcoming session
        let iter = AuthorAffidavits::<T>::iter_prefix((for_session,));

        let mut candidates = Self::Candidates::default();

        for (author, (_, weights)) in iter {
            let mut election_weights = ElectionVia::<T>::default();

            for weight in weights.iter().cloned() {
                election_weights.extend(core::iter::once(weight));
            }

            candidates.extend(core::iter::once((author, election_weights)));
        }
        Ok(candidates)
    }

    /// Reveals the elected authors from the underlying election manager.
    ///
    /// Acts as a thin delegation layer to [`ElectionManager::reveal`].
    ///
    /// ## Failure Semantics
    /// This may return `None` if:
    /// - The election was never executed
    /// - Preparation failed
    /// - Minimum candidate constraints were not met
    ///
    /// ## Caller Responsibility
    /// Callers **must** handle the `None` case gracefully,
    /// typically by retaining the previously elected author set.
    #[inline]
    fn reveal() -> Option<Self::Elected> {
        T::ElectionAdapter::reveal()
    }

    /// Hook invoked after a successful election preparation.
    ///
    /// Emits a [`Event::ElectedInstance`] event if [`Config::EmitEvents`] is `true`.
    fn on_elect_success(runner: &Option<AuthorOf<T>>) {
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let current_block = frame_system::Pallet::<T>::block_number();
        let Some(runner) = runner else {
            debug_assert!(
                false,
                "authors elected for session {:?} at 
                block {:?} but election runner unavailable",
                for_session, current_block
            );
            return;
        };

        #[cfg(not(any(feature = "dev", feature = "runtime-benchmarks")))]
        {
            if T::EmitEvents::get() {
                Pallet::<T>::deposit_event(Event::<T>::ElectedInstance {
                    session: for_session,
                    runner: runner.clone(),
                });
            }
        }

        #[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
        {
            if T::EmitEvents::get() {
                let Some(elects) = Self::reveal() else {
                    debug_assert!(
                        false,
                        "authors elected for session {:?} at 
                        block {:?} by election runner {:?}, 
                        but reveal unavailable",
                        runner, for_session, current_block
                    );
                    return;
                };
                Pallet::<T>::deposit_event(Event::<T>::ElectedInstance {
                    session: for_session,
                    runner: runner.clone(),
                    elects,
                });
            }
        }
    }

    /// Hook invoked when an election attempt fails.
    ///
    /// Emits a [`Event::ElectionAttemptFailed`] event if [`Config::EmitEvents`] is `true`.
    fn on_elect_fail(runner: &Option<AuthorOf<T>>, error: DispatchError) {
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let Some(runner) = runner else {
            let current_block = frame_system::Pallet::<T>::block_number();
            debug_assert!(
                false,
                "authors elected for session {:?} at 
                block {:?} but election runner unavailable",
                for_session, current_block
            );
            return;
        };
        if T::EmitEvents::get() {
            Pallet::<T>::deposit_event(Event::<T>::ElectionAttemptFailed {
                session: for_session,
                runner: runner.clone(),
                error,
            });
        }
    }
}

// ===============================================================================
// ```````````````````````````````` AUTHOR POINTS ````````````````````````````````
// ===============================================================================

/// Implementation of the [`AuthorPoints`] trait for the pallet.
///
/// This implementation provides a **session-scoped accounting layer**
/// for tracking and querying abstract points accumulated by authors
/// during active validation.
///
/// Points represent **good behaviour signals**, specifically
/// **block production contributions**, and serve as inputs to downstream
/// reward and incentive mechanisms.
/// They are *not* assets themselves and carry no immediate economic value.
///
/// ## Design Notes
/// - Points are **scoped per session** and never aggregated across sessions.
/// - Accumulation is **monotonic** within a session.
/// - Each point corresponds to a **unit of block production activity**.
/// - Points are intentionally retained after session end for:
///   - Auditability
///   - Historical analysis
///   - Deterministic reward calculation
/// - This layer is **deterministic and side-effect minimal**.
///
/// ## Implementation Notes
/// - This implementation does not perform reward distribution.
/// - Economic interpretation of points is delegated to [`RewardAuthors`].
/// - Clearing of points is intentionally unsupported at this layer.
impl<T: Config> AuthorPoints<AuthorOf<T>, T::Points> for Pallet<T> {
    /// Returns the total accumulated points for an author
    /// in the **current session**.
    ///
    /// ## Semantics
    /// - Points are accumulated incrementally during the session.
    /// - Each point reflects a **block production contribution**.
    /// - Calling this function **mid-session** returns a partial total.
    /// - Calling this function at **session end** yields the final value
    ///   used for reward calculation.
    ///
    /// ## Errors
    /// - Returns `DispatchError` if the author has not accumulated
    ///   any points in the current session.
    fn points_of(author: &AuthorOf<T>) -> Result<T::Points, DispatchError> {
        let current_session = CurrentSession::<T>::get();
        let points = BlockPointsStore::<T>::get((current_session, author))
            .ok_or(Error::<T>::BlockPointsNotFound)?;
        Ok(points)
    }

    /// **No-op method** for clearing accumulated points.
    ///
    /// Point data is retained indefinitely to:
    /// - Preserve full historical traceability
    /// - Support deterministic audits
    /// - Avoid accidental data loss before reward finalization
    ///
    /// Any future clearing, pruning, or archival must be performed
    /// via explicit governance or maintenance extrinsics.
    fn clear_points() {}

    /// Sets the points for an author in the current session.
    ///
    /// ## Semantics
    /// - Overwrites the existing points value for the author.
    /// - Acts as the **primitive storage write** for point updates.
    ///
    /// ## Notes
    /// - Typically used internally by higher-level operations such as
    ///   [`Self::add_point`].
    fn set_points(author: &AuthorOf<T>, points: T::Points) -> DispatchResult {
        let current_session = CurrentSession::<T>::get();
        BlockPointsStore::<T>::insert((current_session, author), points);
        Ok(())
    }

    /// Returns an iterator over all authors and their accumulated points
    /// for the **current session**.
    ///
    /// ## Semantics
    /// - Provides a complete view of the session-scoped points state.
    /// - Includes all authors who have accumulated at least one point.
    /// - The iterator reflects the **current state** and may change as
    ///   new points are added during the session.
    ///
    /// ## Usage
    /// - Intended for runtime operations such as:
    ///   - Reward computation
    ///   - Ranking or selection
    ///   - Performance evaluation
    ///
    /// ## Notes
    /// - Any clearing, pruning, or archival is the responsibility of
    ///   external logic (e.g., governance or maintenance extrinsics).
    fn iter_points() -> impl Iterator<Item = (AuthorOf<T>, T::Points)> {
        let current_session = CurrentSession::<T>::get();
        BlockPointsStore::<T>::iter_prefix((current_session,))
    }
}

// ===============================================================================
// ```````````````````````````````` REWARD AUTHORS ```````````````````````````````
// ===============================================================================

/// Implementation of the [`RewardAuthors`] trait for the pallet internal type
/// (not exposable).
///
/// This implementation bridges **abstract author points** with the
/// protocol's **reward and inflation mechanisms**, translating
/// session-scoped behavioural signals into scheduled economic rewards.
///
/// This layer does **not** mint, transfer, or finalize rewards directly.
/// Instead, it provides deterministic inputs to downstream reward logic
/// owned by the configured [`RoleManager`] adapters.
///
/// ## Design Notes
/// - Rewards are derived from **session-scoped point accumulation**.
/// - Points are interpreted as **relative behavioural weights**, not
///   absolute reward amounts.
/// - The payout context is configurable and may be based on:
///   - Total token issuance (inflation-based) or,
///   - Total backing + collateral stake (stake-weighted)
/// - All reward operations must remain **deterministic, auditable,
///   and reversible** until finalization.
///
/// ## Implementation Notes
/// - This implementation does not compute reward shares.
/// - Reward distribution logic is delegated to:
///   - [`Config::InflationModel`]
///   - [`Config::RewardModel`]
///   - [`CompensateRoles`]
/// - This layer only exposes:
///   - The payout context
///   - The eligible payee set
///   - A scheduling hook for rewards
impl<T: Config> RewardAuthors<AuthorOf<T>, AssetOf<T>, T::Points> for Internals<T> {
    /// Adapter used to query accumulated author points.
    type AuthorPointsAdapter = T::PointsAdapter;

    /// Type representing authors eligible for payout and their points.
    ///
    /// Typically a vector of author's ID and their correspoinding points.
    type PayoutFor = PayoutFor<T>;

    /// Context used by the inflation plugin model.
    type PayoutContext = T::InflationContext;

    /// Inflation plugin model used to derive reward budgets.
    type PayoutModel = T::InflationModel;

    /// Returns the total asset context used to compute rewards.
    ///
    /// ## Semantics
    /// Depending on configuration, this returns:
    /// - Total token issuance (supply-based inflation), or
    /// - Total backing + collateral stake (stake-weighted inflation)
    ///
    /// ## Notes
    /// - This value represents the **upper bound** for reward calculation.
    /// - It does not imply immediate minting or transfer.
    fn payout_via() -> AssetOf<T> {
        // Use total token issuance if inflation is supply-based.
        if T::InflateViaSupply::get() {
            return T::Asset::total_issuance().into();
        }

        // Otherwise, use total locked stake (backing + collateral).
        let backing_stake = T::RoleAdapter::total_backing();
        let collateral_stake = T::RoleAdapter::total_collateral();
        backing_stake.saturating_add(collateral_stake)
    }

    /// Type representing the set of reward payees.
    ///
    /// Typically a vector of author's ID and their
    /// correspoinding reward asset amount.
    type PayeeList = PayeeList<T>;

    /// Context supplied to the reward plugin model.
    type PayeeContext = T::RewardContext;

    /// Reward plugin model used to translate points into payouts.
    type PayeeModel = T::RewardModel;

    /// Schedules a reward for the given author.
    ///
    /// Acts as a thin delegation layer to [`CompensateRoles::reward`].
    ///
    /// ## Semantics
    /// - This function **does not finalize** the reward.
    /// - Rewards are scheduled with best-effort precision.
    /// - Downstream logic may:
    ///   - Aggregate
    ///   - Adjust
    ///   - Revert
    ///   the scheduled reward before finalization.
    ///
    /// ## Errors
    /// Returns a `DispatchError` if reward scheduling fails.
    fn reward(who: &AuthorOf<T>, value: AssetOf<T>) -> DispatchResult {
        T::RoleAdapter::reward(who, value, Precision::BestEffort)?;
        Ok(())
    }

    /// Returns the set of authors eligible for payout and their
    /// accumulated points for the current session.
    ///
    /// ## Notes
    /// - This function is expected to be called **at session end**.
    /// - Calling it earlier may yield partial or unstable results.
    /// - The returned data is treated as immutable for reward computation.
    fn payout_for() -> Self::PayoutFor {
        let iter = Self::AuthorPointsAdapter::iter_points();
        let mut payout_for = Self::PayoutFor::default();
        for (author, points) in iter {
            payout_for.extend(core::iter::once((author, points)));
        }

        payout_for
    }

    /// Hook invoked after a reward is successfully applied to an author.
    ///
    /// This hook emits the `Rewarded` event, reflecting the
    /// distributed reward amount for the given author.
    fn on_reward_success(who: &AuthorOf<T>, value: AssetOf<T>) {
        if T::EmitEvents::get() {
            Pallet::<T>::deposit_event(Event::RewardInitiated {
                author: who.clone(),
                value,
            });
        }
    }

    /// Hook invoked when applying a reward to an author fails.
    ///
    /// This hook emits the `RewardFailed` event, reflecting the
    /// error that prevented the reward from being applied.
    fn on_reward_fail(who: &AuthorOf<T>, error: DispatchError) {
        if T::EmitEvents::get() {
            Pallet::<T>::deposit_event(Event::RewardFailed {
                author: who.clone(),
                error,
            });
        }
    }
}

// ===============================================================================
// ``````````````````````````````` PENALIZE AUTHORS ``````````````````````````````
// ===============================================================================

/// Implementation of the [`PenalizeAuthors`] trait for the pallet internal type
/// (not-exposable).
///
/// This implementation bridges **author offence signals** with the
/// protocol's **penalty and slashing mechanisms**, enabling penalties
/// to be **scheduled and processed** according to runtime-defined rules.
///
/// Penalties, like rewards, follow a **deferred enforcement model**.
/// They are recorded and transformed first, then enforced later by
/// downstream role and penalty management logic.
///
/// ## Design Notes
/// - Penalties are **author-scoped** and apply to active roles.
/// - Enforcement is **scheduled**, not immediate.
/// - Multiple penalties may be:
///   - Aggregated
///   - Scaled
///   - Capped
///   - Reverted
///   prior to final enforcement.
/// - Penalty values are interpreted as **inputs**, not final amounts.
/// - Transformation and enforcement are governed by runtime-configured
///   penalty models for flexibility and governance control.
///
/// ## Implementation Notes
/// - This layer does **not** detect offences or compute severity.
/// - It does **not** finalize or immediately apply penalties.
/// - All penalty logic is delegated to:
///   - [`Config::PenaltyModel`]
///   - [`CompensateRoles::penalize`]
/// - This implementation guarantees deterministic, auditable scheduling
///   of penalties without side effects.
impl<T: Config> PenalizeAuthors<AuthorOf<T>, PenaltyOf<T>> for Internals<T> {
    /// Mapping of authors to their applied penalties (percentage typically).
    type PenaltyFor = PenaltyFor<T>;

    /// Context provided to the penalty plugin model for transformation.
    type PenaltyContext = T::PenaltyContext;

    /// Plugin Model responsible for transforming raw penalties according to
    /// runtime-defined rules (e.g. caps, scaling, thresholds).
    type PenaltyModel = T::PenaltyModel;

    /// Applies a penalty to the given author.
    ///
    /// Acts as a thin delegation layer to [`CompensateRoles::penalize`].
    ///
    /// ## Semantics
    /// - Penalties are **scheduled**, not applied immediately.
    /// - Downstream logic may:
    ///   - Aggregate multiple penalties
    ///   - Scale or cap penalties
    ///   - Delay or revert enforcement prior to finalization
    ///
    /// ## Notes
    /// - This function does not persist offence metadata.
    /// - Offence detection and validation are the responsibility
    ///   of the caller.
    ///
    /// ## Errors
    /// Returns a `DispatchError` if penalty scheduling fails.
    fn penalize(who: &AuthorOf<T>, penalty: PenaltyOf<T>) -> DispatchResult {
        <T::RoleAdapter as CompensateRoles<AuthorOf<T>>>::penalize(who, penalty)?;
        Ok(())
    }

    /// Hook invoked after a penalty is successfully applied to an author.
    ///
    /// This hook emits the `Penalized` event, reflecting the
    /// penalty enforced against the author.
    fn on_penalty_success(who: &AuthorOf<T>, penalty: PenaltyOf<T>) {
        if T::EmitEvents::get() {
            Pallet::<T>::deposit_event(Event::<T>::PenaltyInitiated {
                author: who.clone(),
                penalty,
            });
        }
    }

    /// Hook invoked when applying a penalty to an author fails.
    ///
    /// This hook emits the `PenaltyFailed` event, reflecting the
    /// error that prevented the penalty from being applied.
    fn on_penalty_fail(who: &AuthorOf<T>, error: DispatchError) {
        if T::EmitEvents::get() {
            Pallet::<T>::deposit_event(Event::<T>::PenaltyFailed {
                author: who.clone(),
                error,
            });
        }
    }
}

// ===============================================================================
// ````````````````````````````` ELECTION AFFIDAVITS `````````````````````````````
// ===============================================================================

/// Implementation of the [`ElectionAffidavits`] trait for the pallet.
///
/// This implementation bridges the generic [`ElectionAffidavits`] abstraction
/// with the pallet's internal affidavit registry ([`AuthorAffidavits`] &
/// [`AffidavitKeys`]), enabling authors to **self-report their election weights**
/// for upcoming sessions.
///
/// ## Design Notes
/// - **Affidavit submission** is only allowed when [`AllowAffidavits`] is enabled.
/// - Affidavits are stored *per session*, not globally, ensuring clean rotation.
/// - **Time gating** is enforced through [`AffidavitBeginsAt`](crate::AffidavitBeginsAt) and 
/// [`AffidavitEndsAt`](crate::AffidavitEndsAt), relative to average session length.
/// - Affidavit data is immutable within its session once the submission period ends.
/// - All operations must remain audit-safe and deterministic.
///
/// ## Implementation Notes
/// This bridge layer does not perform any ranking, scoring, or weighting logic.
/// Those responsibilities remain with the [`ElectAuthors`] and [`ElectionManager`]
/// implementations. The affidavit simply represents a **candidate's declaration**
/// of intent and associated metrics for the next election round.
impl<T: Config> ElectionAffidavits<AffidavitId<T>, ElectionVia<T>> for Pallet<T> {
    /// Checks whether an author can submit an affidavit for the upcoming session-election.
    ///
    /// - The global [`AllowAffidavits`] flag is enabled.
    /// - The current block is within the configured affidavit submission window.
    ///
    /// DispatchError otherwise
    fn can_submit_affidavit(who: &AffidavitId<T>) -> DispatchResult {
        // Check if Affidavit model is initiated
        ensure!(
            AllowAffidavits::<T>::get(),
            Error::<T>::AffidavitsNotAllowed
        );

        // Check if the author exists for the affidavit key ID
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let Some(author) = AffidavitKeys::<T>::get((for_session, who)) else {
            let try_next_session =
                AffidavitKeys::<T>::contains_key((for_session.saturating_add(One::one()), who));
            ensure!(
                !try_next_session,
                Error::<T>::DeclareDuringNextAffidavitSession
            );
            return Err(Error::<T>::AffidavitAuthorNotFound.into());
        };

        <T::RoleAdapter as RoleManager<AuthorOf<T>>>::is_available(&author)?;

        // Compute allowed submission window relative to session timing.
        let aff_window = Pallet::<T>::compute_affidavit_window()?;
        let start_block = aff_window.start;
        let end_block = aff_window.end;

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

        // Ensure affidavit period has started
        ensure!(start_block <= current_block, Error::<T>::NotAffidavitPeriod);

        // Ensure affidavit period has not ended
        ensure!(current_block <= end_block, Error::<T>::AffidavitPeriodEnded);

        Ok(())
    }

    /// Submits a new affidavit for the next session.
    ///
    /// Directly inserts the affidavit into storage for the upcoming session.
    ///
    /// ## Details
    /// - Persists the affidavit under the next session's affidavits mapping.
    /// - Overwrites any previously submitted affidavit for the same session.
    /// - Each author can maintain **only one recent affidavit per future session**.
    fn submit_affidavit(who: &AffidavitId<T>, affidavit: &ElectionVia<T>) -> DispatchResult {
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let author = AffidavitKeys::<T>::get((for_session, who))
            .ok_or(Error::<T>::AffidavitAuthorNotFound)?;
        let current_block = frame_system::Pallet::<T>::block_number();
        let mut try_affidavit: Vec<ElectionWeight<T>> = affidavit.clone().into_iter().collect();
        let result = WeakBoundedVec::<ElectionWeight<T>, T::MaxAffidavitWeights>::try_from(
            try_affidavit.clone(),
        );
        let actual_affidavit = match result {
            Ok(v) => v,
            Err(_) => {
                // Sort in descending order
                try_affidavit.sort_by(|a, b| b.cmp(a));
                WeakBoundedVec::<ElectionWeight<T>, T::MaxAffidavitWeights>::force_from(
                    try_affidavit,
                    None,
                )
            }
        };
        AuthorAffidavits::<T>::insert((for_session, author), (current_block, actual_affidavit));
        Ok(())
    }

    /// Generates an affidavit dynamically for the given author's affidavit ID.
    ///
    /// ## Overview
    /// - Inspects abstract weight via [`InspectWeight`] from [`Config::ElectionAdapter`].
    /// - Produces an [`ElectionVia`] structure that represents the
    ///   author's self-declared election weights.
    ///
    /// ## Returns
    /// - `Ok(ElectionVia)` on success.
    /// - DispatchError otherwise
    fn gen_affidavit(who: &AffidavitId<T>) -> Result<ElectionVia<T>, DispatchError> {
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let author = AffidavitKeys::<T>::get((for_session, who))
            .ok_or(Error::<T>::AffidavitAuthorNotFound)?;
        let weights =
            <T::ElectionAdapter as InspectWeight<AuthorOf<T>, ElectionVia<T>>>::weight_of(&author)?;
        Ok(weights.into())
    }

    /// Removes an existing upcoming-election affidavit for the given author.
    ///
    /// ## Workflow
    /// 1. Ensures the affidavit exists.
    /// 2. Removes it from storage for the next session.
    ///
    /// ## Notes
    /// - Used primarily when an author wishes to withdraw from election participation.
    fn remove_affidavit(who: &AffidavitId<T>) -> DispatchResult {
        Self::affidavit_exists(who)?;
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let author = AffidavitKeys::<T>::get((for_session, who))
            .ok_or(Error::<T>::AffidavitAuthorNotFound)?;
        AuthorAffidavits::<T>::remove((for_session, author));
        Ok(())
    }

    /// Retrieves an affidavit for the given author for the next session's election.
    ///
    /// ## Returns
    /// - The [`ElectionVia`] structure associated with the author.
    /// - DispatchError if no affidavit is stored for the next session election.
    fn get_affidavit(who: &AffidavitId<T>) -> Result<ElectionVia<T>, DispatchError> {
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let author = AffidavitKeys::<T>::get((for_session, who))
            .ok_or(Error::<T>::AffidavitAuthorNotFound)?;
        let (_, affidavit) = AuthorAffidavits::<T>::get((for_session, author))
            .ok_or(Error::<T>::AffidavitNotFound)?;
        Ok(affidavit.into_iter().collect())
    }

    /// Checks if an affidavit exists for the given author for the upcoming election.
    ///
    /// ## Returns
    /// - `Ok(())` if the affidavit exists.
    /// - DispatchError otherwise.
    fn affidavit_exists(who: &AffidavitId<T>) -> DispatchResult {
        let for_session = CurrentSession::<T>::get().saturating_add(One::one());
        let author = AffidavitKeys::<T>::get((for_session, who))
            .ok_or(Error::<T>::AffidavitAuthorNotFound)?;
        ensure!(
            AuthorAffidavits::<T>::contains_key((for_session, author)),
            Error::<T>::AffidavitNotFound
        );
        Ok(())
    }

    /// No-op method.
    ///
    /// This low-level implementation is intentionally left empty.
    ///
    /// Affidavit clearing is deferred to higher-level logic to:
    /// - Preserve full **historical traceability**.
    /// - Prevent accidental data loss before election finalization.
    ///
    /// ## Notes
    /// - The pallet should query affidavits per session **only once**.
    /// - Re-querying beyond this point can cause election inconsistencies.
    /// - Reserved for potential audit or archival extensions.
    fn clear_affidavits() {}

    /// Hook invoked after a successful affidavit submission.
    ///
    /// This hook emits the `AffidavitSubmitted` event, reflecting
    /// the submitted election weight for the author.
    fn on_submit_affidavit(who: &AffidavitId<T>, _affidavit: &ElectionVia<T>) {
        if T::EmitEvents::get() {
            let for_session = CurrentSession::<T>::get().saturating_add(One::one());
            #[cfg(any(feature = "dev", feature = "runtime-benchmarks"))]
            {
                let Some(author) = AffidavitKeys::<T>::get((for_session, who)) else {
                    return;
                };
                let affidavit = _affidavit;
                Self::deposit_event(Event::<T>::AffidavitSubmitted {
                    afdt_id: who.clone(),
                    session: for_session,
                    author,
                    affidavit: affidavit.clone(),
                });
            }
            #[cfg(not(any(feature = "dev", feature = "runtime-benchmarks")))]
            {
                Self::deposit_event(Event::<T>::AffidavitSubmitted {
                    afdt_id: who.clone(),
                    session: for_session,
                });
            }
        }
    }
}

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

#[cfg(test)]
mod tests {

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

    // --- Local crate imports ---
    use crate::{mock::*, types::Duration};

    // --- FRAME Suite ---
    use frame_suite::{blockchain::*, roles::*};

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

    // --- Substrate primitives ---
    use sp_runtime::WeakBoundedVec;

    // --- Std ---
    use std::vec;

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ```````````````````````````````` ELECT AUTHORS ````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn prepare_authors_success() {
        chain_manager_test_ext().execute_with(|| {
            let candidates = vec![
                (ALICE, vec![(Funder::Direct(CHARLIE), 30)]),
                (BOB, vec![(Funder::Direct(ALAN), 60)]),
                (MIKE, vec![(Funder::Direct(NIX), 20)]),
            ];

            System::set_block_number(6);
            assert_ok!(Internals::prepare_authors(candidates));

            let recent_elected = RecentElectedOn::get();
            assert_eq!(recent_elected, 6);
            assert_eq!(Elected::get((recent_elected, ALICE)), Some(()));
            assert_eq!(Elected::get((recent_elected, BOB)), Some(()));
            assert_eq!(Elected::get((recent_elected, MIKE)), Some(()));
        })
    }

    #[test]
    fn can_process_election_success() {
        chain_manager_test_ext().execute_with(|| {
            System::set_block_number(10);
            // Average session length = Period = 1 * HOURS = 600 blocks
            let avg_session_len: BlockNumber = NextSessionRotation::average_session_length();
            assert_eq!(avg_session_len, 600);
            // Session is set to start at block 15
            SessionStartsAt::put(15);
            // Affidavit submission begins at 20% of session length
            // 20% of 600 = 120 blocks
            // 15 + 120 => 135th block
            AffidavitBeginsAt::put(Duration::from_rational(2u32, 10u32));
            let aff_begin_at = AffidavitBeginsAt::get();
            assert_eq!(aff_begin_at, Duration::from_rational(2u32, 10u32));
            // Affidavit submission ends at 80% of session length
            // 80% of 600 = 480 blocks
            // 15 + 480 => 495th block
            AffidavitEndsAt::put(Duration::from_rational(8u32, 10u32));
            let aff_ends_at = AffidavitEndsAt::get();
            assert_eq!(aff_ends_at, Duration::from_rational(8u32, 10u32));
            // Election processing begins at 50% of the affidavit window
            // Affidavit window length = 495 - 135 = 360 blocks
            // 50% of 360 = 180 blocks
            // 135 + 180 = 315th block
            ElectionBeginsAt::put(Duration::from_rational(5u32, 10u32));
            let election_bgn_at = ElectionBeginsAt::get();
            assert_eq!(election_bgn_at, Duration::from_rational(5u32, 10u32));
            // Before affidavit submission window starts (block < 135)
            System::set_block_number(134);
            assert_err!(
                Internals::can_process_election(&Some(ALICE)),
                Error::NotAffidavitPeriod
            );
            // After affidavit window starts but before election window begins (block < 315)
            System::set_block_number(314);
            assert_err!(
                Internals::can_process_election(&Some(ALICE)),
                Error::NotElectionPeriod
            );
            // Election window has started (block >= 315 and <= 495)
            System::set_block_number(315);
            assert_ok!(Internals::can_process_election(&Some(ALICE)));
            // After affidavit window has ended (block > 495)
            System::set_block_number(496);
            assert_err!(
                Internals::can_process_election(&Some(ALICE)),
                Error::ElectionPeriodEnded
            );
        })
    }

    #[test]
    #[should_panic]
    fn can_process_election_panic_invalid_affidavit_period() {
        chain_manager_test_ext().execute_with(|| {
            SessionStartsAt::put(1);
            AffidavitBeginsAt::put(Duration::from_rational(5u32, 10u32));
            AffidavitEndsAt::put(Duration::from_rational(2u32, 10u32));
            Internals::can_process_election(&Some(ALICE)).unwrap();
        })
    }

    #[test]
    fn prepare_candidates_success() {
        chain_manager_test_ext().execute_with(|| {
            set_session(1);
            let users = vec![ALICE, CHARLIE, ALAN, MIKE, BOB, NIX];
            set_default_users_balance_and_hold(users).unwrap();
            let authors = vec![ALICE, BOB, MIKE];
            enroll_authors_with_default_collateral(authors).unwrap();

            direct_fund_author(CHARLIE, ALICE, STANDARD_FUND).unwrap();
            direct_fund_author(ALAN, BOB, SMALL_FUND).unwrap();
            direct_fund_author(NIX, MIKE, STANDARD_FUND).unwrap();

            AffidavitKeys::insert((2, AFFIDAVIT_KEY_A), ALICE);
            AffidavitKeys::insert((2, AFFIDAVIT_KEY_B), BOB);
            AffidavitKeys::insert((2, AFFIDAVIT_KEY_C), MIKE);

            let affidavit_alice_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit_alice_id).unwrap();
            let affidavit_bob_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_B).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_B, &affidavit_bob_id).unwrap();
            let affidavit_mike_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_C).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_C, &affidavit_mike_id).unwrap();

            let candidates = Internals::prepare_candidates().unwrap();
            let expected_candidates = vec![
                (BOB, vec![(Funder::Direct(ALAN), SMALL_FUND)]),
                (MIKE, vec![(Funder::Direct(NIX), STANDARD_FUND)]),
                (ALICE, vec![(Funder::Direct(CHARLIE), STANDARD_FUND)]),
            ];
            assert_eq!(candidates, expected_candidates);
        })
    }

    #[test]
    fn reveal_success() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE, BOB, NIX];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&BOB, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&MIKE, 200, Fortitude::Force).unwrap();

            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &BOB,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &MIKE,
                &Funder::Direct(NIX),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            AffidavitKeys::insert((1, AFFIDAVIT_KEY_B), BOB);
            AffidavitKeys::insert((1, AFFIDAVIT_KEY_C), MIKE);

            let affidavit_alice_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit_alice_id).unwrap();
            let affidavit_bob_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_B).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_B, &affidavit_bob_id).unwrap();
            let affidavit_mike_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_C).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_C, &affidavit_mike_id).unwrap();

            let candidates = Internals::prepare_candidates().unwrap();
            Internals::prepare_authors(candidates).unwrap();

            let reveal = Internals::reveal().unwrap();
            let expected_reveal = vec![BOB, MIKE, ALICE];
            assert_eq!(reveal, expected_reveal);
        })
    }

    #[test]
    fn prepare_election_success() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE, BOB, NIX];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&BOB, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&MIKE, 200, Fortitude::Force).unwrap();

            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &BOB,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &MIKE,
                &Funder::Direct(NIX),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            System::set_block_number(10);
            // Average session length = Period = 1 * HOURS = 600 blocks
            // Session is set to start at block 15
            SessionStartsAt::put(15);
            // Affidavit submission begins at 20% of session length
            AffidavitBeginsAt::put(Duration::from_rational(2u32, 10u32));
            // Affidavit submission ends at 80% of session length
            AffidavitEndsAt::put(Duration::from_rational(8u32, 10u32));
            // Election processing begins at 50% of the affidavit window
            ElectionBeginsAt::put(Duration::from_rational(5u32, 10u32));

            System::set_block_number(15);
            System::set_block_number(135);
            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            AffidavitKeys::insert((1, AFFIDAVIT_KEY_B), BOB);
            AffidavitKeys::insert((1, AFFIDAVIT_KEY_C), MIKE);

            let affidavit_alice_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit_alice_id).unwrap();
            let affidavit_bob_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_B).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_B, &affidavit_bob_id).unwrap();
            let affidavit_mike_id = Pallet::gen_affidavit(&AFFIDAVIT_KEY_C).unwrap();
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_C, &affidavit_mike_id).unwrap();

            System::set_block_number(315);
            assert_ok!(Internals::prepare_election(&Some(ALICE)));

            let reveal = Internals::reveal().unwrap();
            let expected_reveal = vec![BOB, MIKE, ALICE];
            assert_eq!(reveal, expected_reveal);
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ```````````````````````````````` AUTHOR POINTS ````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn points_of_success() {
        chain_manager_test_ext().execute_with(|| {
            set_default_user_balance_and_hold(ALICE).unwrap();
            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            CurrentSession::put(1);
            assert_err!(Pallet::points_of(&ALICE), Error::BlockPointsNotFound);
            Pallet::add_point(&ALICE).unwrap();
            let current_points = Pallet::points_of(&ALICE).unwrap();
            assert_eq!(current_points, 1);
            Pallet::add_point(&ALICE).unwrap();
            Pallet::add_point(&ALICE).unwrap();
            let current_points = Pallet::points_of(&ALICE).unwrap();
            assert_eq!(current_points, 3);
            Pallet::add_point(&ALICE).unwrap();
            let current_points = Pallet::points_of(&ALICE).unwrap();
            assert_eq!(current_points, 4);
        })
    }

    #[test]
    fn add_point_success() {
        chain_manager_test_ext().execute_with(|| {
            set_default_user_balance_and_hold(ALICE).unwrap();
            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            CurrentSession::put(1);
            assert!(PointsAdapter::points_of(&ALICE).is_err());
            assert_ok!(Pallet::add_point(&ALICE));
            let current_points = PointsAdapter::points_of(&ALICE).unwrap();
            assert_eq!(current_points, 1);
            assert_ok!(Pallet::add_point(&ALICE));
            assert_ok!(Pallet::add_point(&ALICE));

            let current_points = PointsAdapter::points_of(&ALICE).unwrap();
            assert_eq!(current_points, 3);
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````` REWARD AUTHORS ````````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn payout_via_returns_total_locked_stake_when_inflate_via_supply_is_disabled() {
        chain_manager_test_ext().execute_with(|| {
            let authors = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(authors).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            let payout = Internals::payout_via();
            assert_eq!(payout, 575);
        })
    }

    #[test]
    fn reward_success() {
        chain_manager_test_ext().execute_with(|| {
            set_default_user_balance_and_hold(ALICE).unwrap();
            System::set_block_number(5);
            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();

            System::set_block_number(16);
            assert_ok!(Internals::reward(&ALICE, 25));

            // Reward of 25 units is scheduled at block 18
            let rewards_of = RoleAdapter::get_rewards_of(&ALICE).unwrap();
            let expected_rewards_of = vec![(18, 25)];
            assert_eq!(rewards_of, expected_rewards_of);
        })
    }

    #[test]
    fn payout_for_success() {
        chain_manager_test_ext().execute_with(|| {
            let authors = vec![ALICE, CHARLIE, BOB];
            set_default_users_balance_and_hold(authors).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&CHARLIE, 100, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&BOB, 150, Fortitude::Force).unwrap();
            CurrentSession::put(1);
            Pallet::add_point(&ALICE).unwrap();
            Pallet::add_point(&CHARLIE).unwrap();
            Pallet::add_point(&BOB).unwrap();
            Pallet::add_point(&BOB).unwrap();

            let payout_for = Internals::payout_for();
            let expected_payout_for = vec![(BOB, 2), (ALICE, 1), (CHARLIE, 1)];
            assert_eq!(payout_for, expected_payout_for);
        })
    }

    #[test]
    fn payout_success() {
        chain_manager_test_ext().execute_with(|| {
            let authors = vec![ALICE, BOB, ALAN, MIKE];
            set_default_users_balance_and_hold(authors).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&BOB, 150, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &BOB,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            let payout = Internals::payout();
            // Since, the configured InflationModel is `ConstantPayout`, which always returns the
            // statically configured reward value (100).
            assert_eq!(payout, 100);
        })
    }

    #[test]
    fn reward_authors_success() {
        chain_manager_test_ext().execute_with(|| {
            let authors = vec![ALICE, BOB, ALAN, MIKE];
            set_default_users_balance_and_hold(authors).unwrap();

            System::set_block_number(5);
            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&BOB, 150, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &BOB,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            Pallet::add_point(&ALICE).unwrap();
            Pallet::add_point(&ALICE).unwrap();
            Pallet::add_point(&BOB).unwrap();
            Pallet::add_point(&BOB).unwrap();
            Pallet::add_point(&BOB).unwrap();
            Pallet::add_point(&ALICE).unwrap();
            Pallet::add_point(&ALICE).unwrap();
            Pallet::add_point(&ALICE).unwrap();

            System::set_block_number(16);
            Internals::reward_authors();

            let rewards_of_alice_id = RoleAdapter::get_rewards_of(&ALICE).unwrap();
            let rewards_of_bob_id = RoleAdapter::get_rewards_of(&BOB).unwrap();

            let expected_alice_id_rewards = vec![(18, 62)];
            let expected_bob_id_rewards = vec![(18, 38)];

            assert_eq!(rewards_of_alice_id, expected_alice_id_rewards);
            assert_eq!(rewards_of_bob_id, expected_bob_id_rewards);
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ``````````````````````````````` PENALIZE AUTHORS ``````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn penalize_success() {
        chain_manager_test_ext().execute_with(|| {
            set_default_user_balance_and_hold(ALICE).unwrap();

            System::set_block_number(5);
            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();

            System::set_block_number(16);
            assert_ok!(Internals::penalize(&ALICE, PenaltyRatio::from_percent(5)));

            // Penalty of 5% is scheduled at block 20
            let penalties_of = RoleAdapter::get_penalties_of(&ALICE).unwrap();
            let expected_penalties_of = vec![(20, PenaltyRatio::from_percent(5))];
            assert_eq!(penalties_of, expected_penalties_of);
        })
    }

    #[test]
    fn transform_penalty_success() {
        chain_manager_test_ext().execute_with(|| {
            let penalty_for = vec![
                (ALICE, PenaltyRatio::from_percent(10)),
                (MIKE, PenaltyRatio::from_percent(70)),
                (BOB, PenaltyRatio::from_percent(90)),
                (CHARLIE, PenaltyRatio::from_percent(80)),
            ];
            let tran_penalty_for = Internals::transform_penalty(penalty_for);
            // Since, the PenaltyModel used is `ThresholdPenalty` with `MyPenaltyThresholdContext` (70% threshold):
            // penalties above 70% are capped, and lower penalties are left unchanged
            let expected_tran = vec![
                (ALICE, PenaltyRatio::from_percent(10)),
                (MIKE, PenaltyRatio::from_percent(70)),
                (BOB, PenaltyRatio::from_percent(70)),
                (CHARLIE, PenaltyRatio::from_percent(70)),
            ];
            assert_eq!(tran_penalty_for, expected_tran);
        })
    }

    #[test]
    fn penalize_authors_success() {
        chain_manager_test_ext().execute_with(|| {
            set_default_user_balance_and_hold(ALICE).unwrap();
            set_default_user_balance_and_hold(BOB).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::enroll(&BOB, 150, Fortitude::Force).unwrap();

            System::set_block_number(16);
            let penalty_for = vec![
                (ALICE, PenaltyRatio::from_percent(25)),
                (BOB, PenaltyRatio::from_percent(72)),
            ];

            Internals::penalize_authors(penalty_for);

            let penalties_of_alice_id = RoleAdapter::get_penalties_of(&ALICE).unwrap();
            let expected_penalties_of_alice_id = vec![(20, PenaltyRatio::from_percent(25))];
            assert_eq!(penalties_of_alice_id, expected_penalties_of_alice_id);
            // BOB's penalty capped to 70%
            let penalties_of_bob_id = RoleAdapter::get_penalties_of(&BOB).unwrap();
            let expected_penalties_of_bob_id = vec![(20, PenaltyRatio::from_percent(70))];
            assert_eq!(penalties_of_bob_id, expected_penalties_of_bob_id);
        })
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ````````````````````````````` ELECTION AFFIDAVITS `````````````````````````````
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #[test]
    fn can_submit_affidait_success() {
        let mut env = new_ocw_env();
        env.ext.execute_with(|| {
            set_session_config();
            set_default_user_balance_and_hold(ALICE).unwrap();
            let afdt_pub = generate_affidavit_id();
            enroll_authors_with_default_collateral(vec![ALICE]).unwrap();
            ext_validate(ALICE, afdt_pub.clone()).unwrap();
            System::set_block_number(AFDT_SUBMISSION_START - 1);
            assert_err!(
                Pallet::can_submit_affidavit(&afdt_pub),
                Error::NotAffidavitPeriod
            );
            System::set_block_number(AFDT_SUBMISSION_START);
            assert_ok!(Pallet::can_submit_affidavit(&afdt_pub));
            System::set_block_number(AFDT_SUBMISSION_END + 1);
            assert_err!(
                Pallet::can_submit_affidavit(&afdt_pub),
                Error::AffidavitPeriodEnded
            );
        })
    }

    #[test]
    fn can_submit_affidait_err_affidavit_author_not_found() {
        chain_manager_test_ext().execute_with(|| {
            System::set_block_number(10);
            SessionStartsAt::put(15);
            AllowAffidavits::put(true);
            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let avg_session_len: BlockNumber = NextSessionRotation::average_session_length();
            assert_eq!(avg_session_len, 600);
            AffidavitBeginsAt::put(Duration::from_rational(2u32, 10u32));
            AffidavitEndsAt::put(Duration::from_rational(8u32, 10u32));
            ElectionBeginsAt::put(Duration::from_rational(5u32, 10u32));
            System::set_block_number(135);
            assert_err!(
                Pallet::can_submit_affidavit(&AFFIDAVIT_KEY_B),
                Error::AffidavitAuthorNotFound
            );
        })
    }

    #[test]
    fn gen_affidavit_success() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let election_via = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            let expected_affidavit =
                vec![(Funder::Direct(ALAN), 150), (Funder::Direct(CHARLIE), 100)];
            assert_eq!(election_via, expected_affidavit);
        })
    }

    #[test]
    fn gen_affidavit_err_affidavit_author_not_found() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            assert_err!(
                Pallet::gen_affidavit(&AFFIDAVIT_KEY_B),
                Error::AffidavitAuthorNotFound
            );
        })
    }

    #[test]
    fn submit_affidavit_success() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let affidavit = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            System::set_block_number(10);
            assert_ok!(Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit));

            let author_affidavit = AuthorOfAffidavits::get((1, ALICE)).unwrap();
            let vec = WeakBoundedVec::try_from(vec![
                (Funder::Direct(MIKE), 125),
                (Funder::Direct(ALAN), 150),
                (Funder::Direct(CHARLIE), 100),
            ])
            .unwrap();
            let expected_affidavit = (10, vec);
            assert_eq!(author_affidavit, expected_affidavit);
        })
    }

    #[test]
    fn get_affidavit_success() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let affidavit = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            System::set_block_number(10);
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit).unwrap();

            let actual_affidavit = Pallet::get_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            let expected_affidavit = vec![
                (Funder::Direct(MIKE), 125),
                (Funder::Direct(ALAN), 150),
                (Funder::Direct(CHARLIE), 100),
            ];
            assert_eq!(actual_affidavit, expected_affidavit);
        })
    }

    #[test]
    fn get_affidavit_err_affidavit_author_not_found() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let affidavit = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            System::set_block_number(10);
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit).unwrap();

            assert_err!(
                Pallet::get_affidavit(&AFFIDAVIT_KEY_B),
                Error::AffidavitAuthorNotFound
            );
        })
    }

    #[test]
    fn get_affidavit_err_affidavit_not_found() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            System::set_block_number(10);

            assert_err!(
                Pallet::get_affidavit(&AFFIDAVIT_KEY_A),
                Error::AffidavitNotFound
            );
        })
    }

    #[test]
    fn affidavit_exists_success() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let affidavit = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            System::set_block_number(10);
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit).unwrap();

            assert_ok!(Pallet::affidavit_exists(&AFFIDAVIT_KEY_A),);
        })
    }

    #[test]
    fn affidavit_exists_err_affidavit_author_not_found() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let affidavit = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            System::set_block_number(10);
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit).unwrap();

            assert_err!(
                Pallet::affidavit_exists(&AFFIDAVIT_KEY_B),
                Error::AffidavitAuthorNotFound
            );
        })
    }

    #[test]
    fn affidavit_exists_err_affidavit_not_found() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            System::set_block_number(10);

            assert_err!(
                Pallet::affidavit_exists(&AFFIDAVIT_KEY_A),
                Error::AffidavitNotFound
            );
        })
    }

    #[test]
    fn remove_affidavit_success() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let affidavit = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            System::set_block_number(10);
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit).unwrap();

            let actual_affidavit = AuthorOfAffidavits::get((1, ALICE));
            assert!(actual_affidavit.is_some());
            assert_ok!(Pallet::remove_affidavit(&AFFIDAVIT_KEY_A));
            assert_eq!(AuthorOfAffidavits::get((1, ALICE)), None);
        })
    }

    #[test]
    fn remove_affidavit_err_affidavit_author_not_found() {
        chain_manager_test_ext().execute_with(|| {
            let users = vec![ALICE, CHARLIE, ALAN, MIKE];
            set_default_users_balance_and_hold(users).unwrap();

            RoleAdapter::enroll(&ALICE, 200, Fortitude::Force).unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(CHARLIE),
                100,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(ALAN),
                150,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();
            RoleAdapter::fund(
                &ALICE,
                &Funder::Direct(MIKE),
                125,
                Precision::Exact,
                Fortitude::Force,
            )
            .unwrap();

            AffidavitKeys::insert((1, AFFIDAVIT_KEY_A), ALICE);
            let affidavit = Pallet::gen_affidavit(&AFFIDAVIT_KEY_A).unwrap();
            System::set_block_number(10);
            Pallet::submit_affidavit(&AFFIDAVIT_KEY_A, &affidavit).unwrap();

            assert_err!(
                Pallet::remove_affidavit(&AFFIDAVIT_KEY_B),
                Error::AffidavitAuthorNotFound
            );
        })
    }
}