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
// Copyright 2019-2022 PureStake Inc.
// This file is part of Moonbeam.

// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Moonbeam is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.

//! # Parachain Staking
//! Minimal staking pallet that implements collator selection by total backed stake.
//! The main difference between this pallet and `frame/pallet-staking` is that this pallet
//! uses direct delegation. Delegators choose exactly who they delegate and with what stake.
//! This is different from `frame/pallet-staking` where delegators approval vote and run Phragmen.
//!
//! ### Rules
//! There is a new round every `<Round<T>>::get().length` blocks.
//!
//! At the start of every round,
//! * issuance is calculated for collators (and their delegators) for block authoring
//! `T::RewardPaymentDelay` rounds ago
//! * a new set of collators is chosen from the candidates
//!
//! Immediately following a round change, payments are made once-per-block until all payments have
//! been made. In each such block, one collator is chosen for a rewards payment and is paid along
//! with each of its top `T::MaxTopDelegationsPerCandidate` delegators.
//!
//! To join the set of candidates, call `join_candidates` with `bond >= MinCandidateStk`.
//! To leave the set of candidates, call `schedule_leave_candidates`. If the call succeeds,
//! the collator is removed from the pool of candidates so they cannot be selected for future
//! collator sets, but they are not unbonded until their exit request is executed. Any signed
//! account may trigger the exit `T::LeaveCandidatesDelay` rounds after the round in which the
//! original request was made.
//!
//! To join the set of delegators, call `delegate` and pass in an account that is
//! already a collator candidate and `bond >= MinDelegation`. Each delegator can delegate up to
//! `T::MaxDelegationsPerDelegator` collator candidates by calling `delegate`.
//!
//! To revoke a delegation, call `revoke_delegation` with the collator candidate's account.
//! To leave the set of delegators and revoke all delegations, call `leave_delegators`.

#![cfg_attr(not(feature = "std"), no_std)]

mod auto_compound;
mod delegation_requests;
pub mod inflation;
pub mod migrations;
pub mod traits;
pub mod types;
pub mod weights;

#[cfg(any(test, feature = "runtime-benchmarks"))]
mod benchmarks;
#[cfg(test)]
mod mock;
mod set;
#[cfg(test)]
mod tests;

use frame_support::pallet;
pub use inflation::{InflationInfo, Range};
pub use weights::WeightInfo;

pub use auto_compound::{AutoCompoundConfig, AutoCompoundDelegations};
pub use delegation_requests::{CancelledScheduledRequest, DelegationAction, ScheduledRequest};
pub use pallet::*;
pub use traits::*;
pub use types::*;
pub use RoundIndex;

#[pallet]
pub mod pallet {
	use crate::delegation_requests::{
		CancelledScheduledRequest, DelegationAction, ScheduledRequest,
	};
	use crate::{set::BoundedOrderedSet, traits::*, types::*, InflationInfo, Range, WeightInfo};
	use crate::{AutoCompoundConfig, AutoCompoundDelegations};
	use frame_support::fail;
	use frame_support::pallet_prelude::*;
	use frame_support::traits::{
		tokens::WithdrawReasons, Currency, Get, Imbalance, LockIdentifier, LockableCurrency,
		ReservableCurrency,
	};
	use frame_system::pallet_prelude::*;
	use sp_consensus_slots::Slot;
	use sp_runtime::{
		traits::{Saturating, Zero},
		DispatchErrorWithPostInfo, Perbill, Percent,
	};
	use sp_std::{collections::btree_map::BTreeMap, prelude::*};

	/// Pallet for parachain staking
	#[pallet::pallet]
	#[pallet::without_storage_info]
	pub struct Pallet<T>(PhantomData<T>);

	pub type RoundIndex = u32;
	type RewardPoint = u32;
	pub type BalanceOf<T> =
		<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;

	pub const COLLATOR_LOCK_ID: LockIdentifier = *b"stkngcol";
	pub const DELEGATOR_LOCK_ID: LockIdentifier = *b"stkngdel";

	/// A hard limit for weight computation purposes for the max candidates that _could_
	/// theoretically exist.
	pub const MAX_CANDIDATES: u32 = 200;

	/// Configuration trait of this pallet.
	#[pallet::config]
	pub trait Config: frame_system::Config {
		/// Overarching event type
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
		/// The currency type
		type Currency: Currency<Self::AccountId>
			+ ReservableCurrency<Self::AccountId>
			+ LockableCurrency<Self::AccountId>;
		/// The origin for monetary governance
		type MonetaryGovernanceOrigin: EnsureOrigin<Self::RuntimeOrigin>;
		/// Minimum number of blocks per round
		#[pallet::constant]
		type MinBlocksPerRound: Get<u32>;
		/// If a collator doesn't produce any block on this number of rounds, it is notified as inactive.
		/// This value must be less than or equal to RewardPaymentDelay.
		#[pallet::constant]
		type MaxOfflineRounds: Get<u32>;
		/// Number of rounds that candidates remain bonded before exit request is executable
		#[pallet::constant]
		type LeaveCandidatesDelay: Get<RoundIndex>;
		/// Number of rounds candidate requests to decrease self-bond must wait to be executable
		#[pallet::constant]
		type CandidateBondLessDelay: Get<RoundIndex>;
		/// Number of rounds that delegators remain bonded before exit request is executable
		#[pallet::constant]
		type LeaveDelegatorsDelay: Get<RoundIndex>;
		/// Number of rounds that delegations remain bonded before revocation request is executable
		#[pallet::constant]
		type RevokeDelegationDelay: Get<RoundIndex>;
		/// Number of rounds that delegation less requests must wait before executable
		#[pallet::constant]
		type DelegationBondLessDelay: Get<RoundIndex>;
		/// Number of rounds after which block authors are rewarded
		#[pallet::constant]
		type RewardPaymentDelay: Get<RoundIndex>;
		/// Minimum number of selected candidates every round
		#[pallet::constant]
		type MinSelectedCandidates: Get<u32>;
		/// Maximum top delegations counted per candidate
		#[pallet::constant]
		type MaxTopDelegationsPerCandidate: Get<u32>;
		/// Maximum bottom delegations (not counted) per candidate
		#[pallet::constant]
		type MaxBottomDelegationsPerCandidate: Get<u32>;
		/// Maximum delegations per delegator
		#[pallet::constant]
		type MaxDelegationsPerDelegator: Get<u32>;
		/// Minimum stake required for any account to be a collator candidate
		#[pallet::constant]
		type MinCandidateStk: Get<BalanceOf<Self>>;
		/// Minimum stake for any registered on-chain account to delegate
		#[pallet::constant]
		type MinDelegation: Get<BalanceOf<Self>>;
		/// Get the current block author
		type BlockAuthor: Get<Self::AccountId>;
		/// Handler to notify the runtime when a collator is paid.
		/// If you don't need it, you can specify the type `()`.
		type OnCollatorPayout: OnCollatorPayout<Self::AccountId, BalanceOf<Self>>;
		/// Handler to distribute a collator's reward.
		/// To use the default implementation of minting rewards, specify the type `()`.
		type PayoutCollatorReward: PayoutCollatorReward<Self>;
		/// Handler to notify the runtime when a collator is inactive.
		/// The default behavior is to mark the collator as offline.
		/// If you need to use the default implementation, specify the type `()`.
		type OnInactiveCollator: OnInactiveCollator<Self>;
		/// Handler to notify the runtime when a new round begin.
		/// If you don't need it, you can specify the type `()`.
		type OnNewRound: OnNewRound;
		/// Get the current slot number
		type SlotProvider: Get<Slot>;
		/// Get the slot duration in milliseconds
		#[pallet::constant]
		type SlotDuration: Get<u64>;
		/// Get the average time beetween 2 blocks in milliseconds
		#[pallet::constant]
		type BlockTime: Get<u64>;
		/// Maximum candidates
		#[pallet::constant]
		type MaxCandidates: Get<u32>;
		/// Weight information for extrinsics in this pallet.
		type WeightInfo: WeightInfo;
	}

	#[pallet::error]
	pub enum Error<T> {
		DelegatorDNE,
		DelegatorDNEinTopNorBottom,
		DelegatorDNEInDelegatorSet,
		CandidateDNE,
		DelegationDNE,
		DelegatorExists,
		CandidateExists,
		CandidateBondBelowMin,
		InsufficientBalance,
		DelegatorBondBelowMin,
		DelegationBelowMin,
		AlreadyOffline,
		AlreadyActive,
		DelegatorAlreadyLeaving,
		DelegatorNotLeaving,
		DelegatorCannotLeaveYet,
		CannotDelegateIfLeaving,
		CandidateAlreadyLeaving,
		CandidateNotLeaving,
		CandidateCannotLeaveYet,
		CannotGoOnlineIfLeaving,
		ExceedMaxDelegationsPerDelegator,
		AlreadyDelegatedCandidate,
		InvalidSchedule,
		CannotSetBelowMin,
		RoundLengthMustBeGreaterThanTotalSelectedCollators,
		NoWritingSameValue,
		TotalInflationDistributionPercentExceeds100,
		TooLowCandidateCountWeightHintJoinCandidates,
		TooLowCandidateCountWeightHintCancelLeaveCandidates,
		TooLowCandidateCountToLeaveCandidates,
		TooLowDelegationCountToDelegate,
		TooLowCandidateDelegationCountToDelegate,
		TooLowCandidateDelegationCountToLeaveCandidates,
		TooLowDelegationCountToLeaveDelegators,
		PendingCandidateRequestsDNE,
		PendingCandidateRequestAlreadyExists,
		PendingCandidateRequestNotDueYet,
		PendingDelegationRequestDNE,
		PendingDelegationRequestAlreadyExists,
		PendingDelegationRequestNotDueYet,
		CannotDelegateLessThanOrEqualToLowestBottomWhenFull,
		PendingDelegationRevoke,
		TooLowDelegationCountToAutoCompound,
		TooLowCandidateAutoCompoundingDelegationCountToAutoCompound,
		TooLowCandidateAutoCompoundingDelegationCountToDelegate,
		TooLowCollatorCountToNotifyAsInactive,
		CannotBeNotifiedAsInactive,
		TooLowCandidateAutoCompoundingDelegationCountToLeaveCandidates,
		TooLowCandidateCountWeightHint,
		TooLowCandidateCountWeightHintGoOffline,
		CandidateLimitReached,
		CannotSetAboveMaxCandidates,
		RemovedCall,
		MarkingOfflineNotEnabled,
		CurrentRoundTooLow,
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(crate) fn deposit_event)]
	pub enum Event<T: Config> {
		/// Started new round.
		NewRound {
			starting_block: BlockNumberFor<T>,
			round: RoundIndex,
			selected_collators_number: u32,
			total_balance: BalanceOf<T>,
		},
		/// Account joined the set of collator candidates.
		JoinedCollatorCandidates {
			account: T::AccountId,
			amount_locked: BalanceOf<T>,
			new_total_amt_locked: BalanceOf<T>,
		},
		/// Candidate selected for collators. Total Exposed Amount includes all delegations.
		CollatorChosen {
			round: RoundIndex,
			collator_account: T::AccountId,
			total_exposed_amount: BalanceOf<T>,
		},
		/// Candidate requested to decrease a self bond.
		CandidateBondLessRequested {
			candidate: T::AccountId,
			amount_to_decrease: BalanceOf<T>,
			execute_round: RoundIndex,
		},
		/// Candidate has increased a self bond.
		CandidateBondedMore {
			candidate: T::AccountId,
			amount: BalanceOf<T>,
			new_total_bond: BalanceOf<T>,
		},
		/// Candidate has decreased a self bond.
		CandidateBondedLess {
			candidate: T::AccountId,
			amount: BalanceOf<T>,
			new_bond: BalanceOf<T>,
		},
		/// Candidate temporarily leave the set of collator candidates without unbonding.
		CandidateWentOffline { candidate: T::AccountId },
		/// Candidate rejoins the set of collator candidates.
		CandidateBackOnline { candidate: T::AccountId },
		/// Candidate has requested to leave the set of candidates.
		CandidateScheduledExit {
			exit_allowed_round: RoundIndex,
			candidate: T::AccountId,
			scheduled_exit: RoundIndex,
		},
		/// Cancelled request to leave the set of candidates.
		CancelledCandidateExit { candidate: T::AccountId },
		/// Cancelled request to decrease candidate's bond.
		CancelledCandidateBondLess {
			candidate: T::AccountId,
			amount: BalanceOf<T>,
			execute_round: RoundIndex,
		},
		/// Candidate has left the set of candidates.
		CandidateLeft {
			ex_candidate: T::AccountId,
			unlocked_amount: BalanceOf<T>,
			new_total_amt_locked: BalanceOf<T>,
		},
		/// Delegator requested to decrease a bond for the collator candidate.
		DelegationDecreaseScheduled {
			delegator: T::AccountId,
			candidate: T::AccountId,
			amount_to_decrease: BalanceOf<T>,
			execute_round: RoundIndex,
		},
		// Delegation increased.
		DelegationIncreased {
			delegator: T::AccountId,
			candidate: T::AccountId,
			amount: BalanceOf<T>,
			in_top: bool,
		},
		// Delegation decreased.
		DelegationDecreased {
			delegator: T::AccountId,
			candidate: T::AccountId,
			amount: BalanceOf<T>,
			in_top: bool,
		},
		/// Delegator requested to leave the set of delegators.
		DelegatorExitScheduled {
			round: RoundIndex,
			delegator: T::AccountId,
			scheduled_exit: RoundIndex,
		},
		/// Delegator requested to revoke delegation.
		DelegationRevocationScheduled {
			round: RoundIndex,
			delegator: T::AccountId,
			candidate: T::AccountId,
			scheduled_exit: RoundIndex,
		},
		/// Delegator has left the set of delegators.
		DelegatorLeft {
			delegator: T::AccountId,
			unstaked_amount: BalanceOf<T>,
		},
		/// Delegation revoked.
		DelegationRevoked {
			delegator: T::AccountId,
			candidate: T::AccountId,
			unstaked_amount: BalanceOf<T>,
		},
		/// Delegation kicked.
		DelegationKicked {
			delegator: T::AccountId,
			candidate: T::AccountId,
			unstaked_amount: BalanceOf<T>,
		},
		/// Cancelled a pending request to exit the set of delegators.
		DelegatorExitCancelled { delegator: T::AccountId },
		/// Cancelled request to change an existing delegation.
		CancelledDelegationRequest {
			delegator: T::AccountId,
			cancelled_request: CancelledScheduledRequest<BalanceOf<T>>,
			collator: T::AccountId,
		},
		/// New delegation (increase of the existing one).
		Delegation {
			delegator: T::AccountId,
			locked_amount: BalanceOf<T>,
			candidate: T::AccountId,
			delegator_position: DelegatorAdded<BalanceOf<T>>,
			auto_compound: Percent,
		},
		/// Delegation from candidate state has been remove.
		DelegatorLeftCandidate {
			delegator: T::AccountId,
			candidate: T::AccountId,
			unstaked_amount: BalanceOf<T>,
			total_candidate_staked: BalanceOf<T>,
		},
		/// Paid the account (delegator or collator) the balance as liquid rewards.
		Rewarded {
			account: T::AccountId,
			rewards: BalanceOf<T>,
		},
		/// Transferred to account which holds funds reserved for parachain bond.
		InflationDistributed {
			index: u32,
			account: T::AccountId,
			value: BalanceOf<T>,
		},
		InflationDistributionConfigUpdated {
			old: InflationDistributionConfig<T::AccountId>,
			new: InflationDistributionConfig<T::AccountId>,
		},
		/// Annual inflation input (first 3) was used to derive new per-round inflation (last 3)
		InflationSet {
			annual_min: Perbill,
			annual_ideal: Perbill,
			annual_max: Perbill,
			round_min: Perbill,
			round_ideal: Perbill,
			round_max: Perbill,
		},
		/// Staking expectations set.
		StakeExpectationsSet {
			expect_min: BalanceOf<T>,
			expect_ideal: BalanceOf<T>,
			expect_max: BalanceOf<T>,
		},
		/// Set total selected candidates to this value.
		TotalSelectedSet { old: u32, new: u32 },
		/// Set collator commission to this value.
		CollatorCommissionSet { old: Perbill, new: Perbill },
		/// Set blocks per round
		BlocksPerRoundSet {
			current_round: RoundIndex,
			first_block: BlockNumberFor<T>,
			old: u32,
			new: u32,
			new_per_round_inflation_min: Perbill,
			new_per_round_inflation_ideal: Perbill,
			new_per_round_inflation_max: Perbill,
		},
		/// Auto-compounding reward percent was set for a delegation.
		AutoCompoundSet {
			candidate: T::AccountId,
			delegator: T::AccountId,
			value: Percent,
		},
		/// Compounded a portion of rewards towards the delegation.
		Compounded {
			candidate: T::AccountId,
			delegator: T::AccountId,
			amount: BalanceOf<T>,
		},
	}

	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
		fn on_initialize(n: BlockNumberFor<T>) -> Weight {
			let mut weight = <T as Config>::WeightInfo::base_on_initialize();

			let mut round = <Round<T>>::get();
			if round.should_update(n) {
				// fetch current slot number
				let current_slot: u64 = T::SlotProvider::get().into();

				// account for SlotProvider read
				weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));

				// Compute round duration in slots
				let round_duration = (current_slot.saturating_sub(round.first_slot))
					.saturating_mul(T::SlotDuration::get());

				// mutate round
				round.update(n, current_slot);
				// notify that new round begin
				weight = weight.saturating_add(T::OnNewRound::on_new_round(round.current));
				// pay all stakers for T::RewardPaymentDelay rounds ago
				weight =
					weight.saturating_add(Self::prepare_staking_payouts(round, round_duration));
				// select top collator candidates for next round
				let (extra_weight, collator_count, _delegation_count, total_staked) =
					Self::select_top_candidates(round.current);
				weight = weight.saturating_add(extra_weight);
				// start next round
				<Round<T>>::put(round);
				Self::deposit_event(Event::NewRound {
					starting_block: round.first,
					round: round.current,
					selected_collators_number: collator_count,
					total_balance: total_staked,
				});
				// account for Round write
				weight = weight.saturating_add(T::DbWeight::get().reads_writes(0, 1));
			} else {
				weight = weight.saturating_add(Self::handle_delayed_payouts(round.current));
			}

			// add on_finalize weight
			//   read:  Author, Points, AwardedPts
			//   write: Points, AwardedPts
			weight = weight.saturating_add(T::DbWeight::get().reads_writes(3, 2));
			weight
		}
		fn on_finalize(_n: BlockNumberFor<T>) {
			Self::award_points_to_block_author();
		}
	}

	#[pallet::storage]
	#[pallet::getter(fn collator_commission)]
	/// Commission percent taken off of rewards for all collators
	type CollatorCommission<T: Config> = StorageValue<_, Perbill, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn total_selected)]
	/// The total candidates selected every round
	pub(crate) type TotalSelected<T: Config> = StorageValue<_, u32, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn inflation_distribution_info)]
	/// Inflation distribution configuration, including accounts that should receive inflation
	/// before it is distributed to collators and delegators.
	///
	/// The sum of the distribution percents must be less than or equal to 100.
	pub(crate) type InflationDistributionInfo<T: Config> =
		StorageValue<_, InflationDistributionConfig<T::AccountId>, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn round)]
	/// Current round index and next round scheduled transition
	pub type Round<T: Config> = StorageValue<_, RoundInfo<BlockNumberFor<T>>, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn delegator_state)]
	/// Get delegator state associated with an account if account is delegating else None
	pub(crate) type DelegatorState<T: Config> = StorageMap<
		_,
		Twox64Concat,
		T::AccountId,
		Delegator<T::AccountId, BalanceOf<T>>,
		OptionQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn candidate_info)]
	/// Get collator candidate info associated with an account if account is candidate else None
	pub(crate) type CandidateInfo<T: Config> =
		StorageMap<_, Twox64Concat, T::AccountId, CandidateMetadata<BalanceOf<T>>, OptionQuery>;

	pub struct AddGet<T, R> {
		_phantom: PhantomData<(T, R)>,
	}
	impl<T, R> Get<u32> for AddGet<T, R>
	where
		T: Get<u32>,
		R: Get<u32>,
	{
		fn get() -> u32 {
			T::get() + R::get()
		}
	}

	/// Stores outstanding delegation requests per collator.
	#[pallet::storage]
	#[pallet::getter(fn delegation_scheduled_requests)]
	pub(crate) type DelegationScheduledRequests<T: Config> = StorageMap<
		_,
		Blake2_128Concat,
		T::AccountId,
		BoundedVec<
			ScheduledRequest<T::AccountId, BalanceOf<T>>,
			AddGet<T::MaxTopDelegationsPerCandidate, T::MaxBottomDelegationsPerCandidate>,
		>,
		ValueQuery,
	>;

	/// Stores auto-compounding configuration per collator.
	#[pallet::storage]
	#[pallet::getter(fn auto_compounding_delegations)]
	pub(crate) type AutoCompoundingDelegations<T: Config> = StorageMap<
		_,
		Blake2_128Concat,
		T::AccountId,
		BoundedVec<
			AutoCompoundConfig<T::AccountId>,
			AddGet<T::MaxTopDelegationsPerCandidate, T::MaxBottomDelegationsPerCandidate>,
		>,
		ValueQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn top_delegations)]
	/// Top delegations for collator candidate
	pub(crate) type TopDelegations<T: Config> = StorageMap<
		_,
		Twox64Concat,
		T::AccountId,
		Delegations<T::AccountId, BalanceOf<T>>,
		OptionQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn bottom_delegations)]
	/// Bottom delegations for collator candidate
	pub(crate) type BottomDelegations<T: Config> = StorageMap<
		_,
		Twox64Concat,
		T::AccountId,
		Delegations<T::AccountId, BalanceOf<T>>,
		OptionQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn selected_candidates)]
	/// The collator candidates selected for the current round
	type SelectedCandidates<T: Config> =
		StorageValue<_, BoundedVec<T::AccountId, T::MaxCandidates>, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn total)]
	/// Total capital locked by this staking pallet
	pub(crate) type Total<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn candidate_pool)]
	/// The pool of collator candidates, each with their total backing stake
	pub(crate) type CandidatePool<T: Config> = StorageValue<
		_,
		BoundedOrderedSet<Bond<T::AccountId, BalanceOf<T>>, T::MaxCandidates>,
		ValueQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn at_stake)]
	/// Snapshot of collator delegation stake at the start of the round
	pub type AtStake<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		RoundIndex,
		Twox64Concat,
		T::AccountId,
		CollatorSnapshot<T::AccountId, BalanceOf<T>>,
		OptionQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn delayed_payouts)]
	/// Delayed payouts
	pub type DelayedPayouts<T: Config> =
		StorageMap<_, Twox64Concat, RoundIndex, DelayedPayout<BalanceOf<T>>, OptionQuery>;

	#[pallet::storage]
	#[pallet::getter(fn inflation_config)]
	/// Inflation configuration
	pub type InflationConfig<T: Config> = StorageValue<_, InflationInfo<BalanceOf<T>>, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn points)]
	/// Total points awarded to collators for block production in the round
	pub type Points<T: Config> = StorageMap<_, Twox64Concat, RoundIndex, RewardPoint, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn awarded_pts)]
	/// Points for each collator per round
	pub type AwardedPts<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		RoundIndex,
		Twox64Concat,
		T::AccountId,
		RewardPoint,
		ValueQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn marking_offline)]
	/// Killswitch to enable/disable marking offline feature.
	pub type EnableMarkingOffline<T: Config> = StorageValue<_, bool, ValueQuery>;

	#[pallet::genesis_config]
	pub struct GenesisConfig<T: Config> {
		/// Initialize balance and register all as collators: `(collator AccountId, balance Amount)`
		pub candidates: Vec<(T::AccountId, BalanceOf<T>)>,
		/// Initialize balance and make delegations:
		/// `(delegator AccountId, collator AccountId, delegation Amount, auto-compounding Percent)`
		pub delegations: Vec<(T::AccountId, T::AccountId, BalanceOf<T>, Percent)>,
		/// Inflation configuration
		pub inflation_config: InflationInfo<BalanceOf<T>>,
		/// Default fixed percent a collator takes off the top of due rewards
		pub collator_commission: Perbill,
		/// Default percent of inflation set aside for parachain bond every round
		pub parachain_bond_reserve_percent: Percent,
		/// Default number of blocks in a round
		pub blocks_per_round: u32,
		/// Number of selected candidates every round. Cannot be lower than MinSelectedCandidates
		pub num_selected_candidates: u32,
	}

	impl<T: Config> Default for GenesisConfig<T> {
		fn default() -> Self {
			Self {
				candidates: vec![],
				delegations: vec![],
				inflation_config: Default::default(),
				collator_commission: Default::default(),
				parachain_bond_reserve_percent: Default::default(),
				blocks_per_round: 1u32,
				num_selected_candidates: T::MinSelectedCandidates::get(),
			}
		}
	}

	#[pallet::genesis_build]
	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
		fn build(&self) {
			assert!(self.blocks_per_round > 0, "Blocks per round must be > 0");
			<InflationConfig<T>>::put(self.inflation_config.clone());
			let mut candidate_count = 0u32;
			// Initialize the candidates
			for &(ref candidate, balance) in &self.candidates {
				assert!(
					<Pallet<T>>::get_collator_stakable_free_balance(candidate) >= balance,
					"Account does not have enough balance to bond as a candidate."
				);
				if let Err(error) = <Pallet<T>>::join_candidates(
					T::RuntimeOrigin::from(Some(candidate.clone()).into()),
					balance,
					candidate_count,
				) {
					log::warn!("Join candidates failed in genesis with error {:?}", error);
				} else {
					candidate_count = candidate_count.saturating_add(1u32);
				}
			}

			let mut col_delegator_count: BTreeMap<T::AccountId, u32> = BTreeMap::new();
			let mut col_auto_compound_delegator_count: BTreeMap<T::AccountId, u32> =
				BTreeMap::new();
			let mut del_delegation_count: BTreeMap<T::AccountId, u32> = BTreeMap::new();
			// Initialize the delegations
			for &(ref delegator, ref target, balance, auto_compound) in &self.delegations {
				assert!(
					<Pallet<T>>::get_delegator_stakable_balance(delegator) >= balance,
					"Account does not have enough balance to place delegation."
				);
				let cd_count = if let Some(x) = col_delegator_count.get(target) {
					*x
				} else {
					0u32
				};
				let dd_count = if let Some(x) = del_delegation_count.get(delegator) {
					*x
				} else {
					0u32
				};
				let cd_auto_compound_count = col_auto_compound_delegator_count
					.get(target)
					.cloned()
					.unwrap_or_default();
				if let Err(error) = <Pallet<T>>::delegate_with_auto_compound(
					T::RuntimeOrigin::from(Some(delegator.clone()).into()),
					target.clone(),
					balance,
					auto_compound,
					cd_count,
					cd_auto_compound_count,
					dd_count,
				) {
					log::warn!("Delegate failed in genesis with error {:?}", error);
				} else {
					if let Some(x) = col_delegator_count.get_mut(target) {
						*x = x.saturating_add(1u32);
					} else {
						col_delegator_count.insert(target.clone(), 1u32);
					};
					if let Some(x) = del_delegation_count.get_mut(delegator) {
						*x = x.saturating_add(1u32);
					} else {
						del_delegation_count.insert(delegator.clone(), 1u32);
					};
					if !auto_compound.is_zero() {
						col_auto_compound_delegator_count
							.entry(target.clone())
							.and_modify(|x| *x = x.saturating_add(1))
							.or_insert(1);
					}
				}
			}
			// Set collator commission to default config
			<CollatorCommission<T>>::put(self.collator_commission);
			// Set parachain bond config to default config
			let pbr = InflationDistributionAccount {
				// must be set soon; if not => due inflation will be sent to collators/delegators
				account: T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes())
					.expect("infinite length input; no invalid inputs for type; qed"),
				percent: self.parachain_bond_reserve_percent,
			};
			let zeroed_account = InflationDistributionAccount {
				account: T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes())
					.expect("infinite length input; no invalid inputs for type; qed"),
				percent: Percent::zero(),
			};
			<InflationDistributionInfo<T>>::put::<InflationDistributionConfig<T::AccountId>>(
				[pbr, zeroed_account].into(),
			);
			// Set total selected candidates to value from config
			assert!(
				self.num_selected_candidates >= T::MinSelectedCandidates::get(),
				"{:?}",
				Error::<T>::CannotSetBelowMin
			);
			assert!(
				self.num_selected_candidates <= T::MaxCandidates::get(),
				"{:?}",
				Error::<T>::CannotSetAboveMaxCandidates
			);
			<TotalSelected<T>>::put(self.num_selected_candidates);
			// Choose top TotalSelected collator candidates
			let (_, v_count, _, total_staked) = <Pallet<T>>::select_top_candidates(1u32);
			// Start Round 1 at Block 0
			let round: RoundInfo<BlockNumberFor<T>> =
				RoundInfo::new(1u32, Zero::zero(), self.blocks_per_round, 0);
			<Round<T>>::put(round);
			<Pallet<T>>::deposit_event(Event::NewRound {
				starting_block: Zero::zero(),
				round: 1u32,
				selected_collators_number: v_count,
				total_balance: total_staked,
			});
		}
	}

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Set the expectations for total staked. These expectations determine the issuance for
		/// the round according to logic in `fn compute_issuance`
		#[pallet::call_index(0)]
		#[pallet::weight(<T as Config>::WeightInfo::set_staking_expectations())]
		pub fn set_staking_expectations(
			origin: OriginFor<T>,
			expectations: Range<BalanceOf<T>>,
		) -> DispatchResultWithPostInfo {
			T::MonetaryGovernanceOrigin::ensure_origin(origin)?;
			ensure!(expectations.is_valid(), Error::<T>::InvalidSchedule);
			let mut config = <InflationConfig<T>>::get();
			ensure!(
				config.expect != expectations,
				Error::<T>::NoWritingSameValue
			);
			config.set_expectations(expectations);
			Self::deposit_event(Event::StakeExpectationsSet {
				expect_min: config.expect.min,
				expect_ideal: config.expect.ideal,
				expect_max: config.expect.max,
			});
			<InflationConfig<T>>::put(config);
			Ok(().into())
		}

		/// Set the annual inflation rate to derive per-round inflation
		#[pallet::call_index(1)]
		#[pallet::weight(<T as Config>::WeightInfo::set_inflation())]
		pub fn set_inflation(
			origin: OriginFor<T>,
			schedule: Range<Perbill>,
		) -> DispatchResultWithPostInfo {
			T::MonetaryGovernanceOrigin::ensure_origin(origin)?;
			ensure!(schedule.is_valid(), Error::<T>::InvalidSchedule);
			let mut config = <InflationConfig<T>>::get();
			ensure!(config.annual != schedule, Error::<T>::NoWritingSameValue);
			config.annual = schedule;
			config.set_round_from_annual::<T>(schedule);
			Self::deposit_event(Event::InflationSet {
				annual_min: config.annual.min,
				annual_ideal: config.annual.ideal,
				annual_max: config.annual.max,
				round_min: config.round.min,
				round_ideal: config.round.ideal,
				round_max: config.round.max,
			});
			<InflationConfig<T>>::put(config);
			Ok(().into())
		}

		/// Deprecated: please use `set_inflation_distribution_config` instead.
		///
		///  Set the account that will hold funds set aside for parachain bond
		#[pallet::call_index(2)]
		#[pallet::weight(<T as Config>::WeightInfo::set_parachain_bond_account())]
		pub fn set_parachain_bond_account(
			origin: OriginFor<T>,
			new: T::AccountId,
		) -> DispatchResultWithPostInfo {
			T::MonetaryGovernanceOrigin::ensure_origin(origin.clone())?;
			let old = <InflationDistributionInfo<T>>::get().0;
			let new = InflationDistributionAccount {
				account: new,
				percent: old[0].percent.clone(),
			};
			Pallet::<T>::set_inflation_distribution_config(origin, [new, old[1].clone()].into())
		}

		/// Deprecated: please use `set_inflation_distribution_config` instead.
		///
		/// Set the percent of inflation set aside for parachain bond
		#[pallet::call_index(3)]
		#[pallet::weight(<T as Config>::WeightInfo::set_parachain_bond_reserve_percent())]
		pub fn set_parachain_bond_reserve_percent(
			origin: OriginFor<T>,
			new: Percent,
		) -> DispatchResultWithPostInfo {
			T::MonetaryGovernanceOrigin::ensure_origin(origin.clone())?;
			let old = <InflationDistributionInfo<T>>::get().0;
			let new = InflationDistributionAccount {
				account: old[0].account.clone(),
				percent: new,
			};
			Pallet::<T>::set_inflation_distribution_config(origin, [new, old[1].clone()].into())
		}

		/// Set the total number of collator candidates selected per round
		/// - changes are not applied until the start of the next round
		#[pallet::call_index(4)]
		#[pallet::weight(<T as Config>::WeightInfo::set_total_selected())]
		pub fn set_total_selected(origin: OriginFor<T>, new: u32) -> DispatchResultWithPostInfo {
			frame_system::ensure_root(origin)?;
			ensure!(
				new >= T::MinSelectedCandidates::get(),
				Error::<T>::CannotSetBelowMin
			);
			ensure!(
				new <= T::MaxCandidates::get(),
				Error::<T>::CannotSetAboveMaxCandidates
			);
			let old = <TotalSelected<T>>::get();
			ensure!(old != new, Error::<T>::NoWritingSameValue);
			ensure!(
				new < <Round<T>>::get().length,
				Error::<T>::RoundLengthMustBeGreaterThanTotalSelectedCollators,
			);
			<TotalSelected<T>>::put(new);
			Self::deposit_event(Event::TotalSelectedSet { old, new });
			Ok(().into())
		}

		/// Set the commission for all collators
		#[pallet::call_index(5)]
		#[pallet::weight(<T as Config>::WeightInfo::set_collator_commission())]
		pub fn set_collator_commission(
			origin: OriginFor<T>,
			new: Perbill,
		) -> DispatchResultWithPostInfo {
			frame_system::ensure_root(origin)?;
			let old = <CollatorCommission<T>>::get();
			ensure!(old != new, Error::<T>::NoWritingSameValue);
			<CollatorCommission<T>>::put(new);
			Self::deposit_event(Event::CollatorCommissionSet { old, new });
			Ok(().into())
		}

		/// Set blocks per round
		/// - if called with `new` less than length of current round, will transition immediately
		/// in the next block
		/// - also updates per-round inflation config
		#[pallet::call_index(6)]
		#[pallet::weight(<T as Config>::WeightInfo::set_blocks_per_round())]
		pub fn set_blocks_per_round(origin: OriginFor<T>, new: u32) -> DispatchResultWithPostInfo {
			frame_system::ensure_root(origin)?;
			ensure!(
				new >= T::MinBlocksPerRound::get(),
				Error::<T>::CannotSetBelowMin
			);
			let mut round = <Round<T>>::get();
			let (now, first, old) = (round.current, round.first, round.length);
			ensure!(old != new, Error::<T>::NoWritingSameValue);
			ensure!(
				new > <TotalSelected<T>>::get(),
				Error::<T>::RoundLengthMustBeGreaterThanTotalSelectedCollators,
			);
			round.length = new;
			// update per-round inflation given new rounds per year
			let mut inflation_config = <InflationConfig<T>>::get();
			inflation_config.reset_round::<T>(new);
			<Round<T>>::put(round);
			Self::deposit_event(Event::BlocksPerRoundSet {
				current_round: now,
				first_block: first,
				old: old,
				new: new,
				new_per_round_inflation_min: inflation_config.round.min,
				new_per_round_inflation_ideal: inflation_config.round.ideal,
				new_per_round_inflation_max: inflation_config.round.max,
			});
			<InflationConfig<T>>::put(inflation_config);
			Ok(().into())
		}

		/// Join the set of collator candidates
		#[pallet::call_index(7)]
		#[pallet::weight(<T as Config>::WeightInfo::join_candidates(*candidate_count))]
		pub fn join_candidates(
			origin: OriginFor<T>,
			bond: BalanceOf<T>,
			candidate_count: u32,
		) -> DispatchResultWithPostInfo {
			let acc = ensure_signed(origin)?;
			ensure!(
				bond >= T::MinCandidateStk::get(),
				Error::<T>::CandidateBondBelowMin
			);
			Self::join_candidates_inner(acc, bond, candidate_count)
		}

		/// Request to leave the set of candidates. If successful, the account is immediately
		/// removed from the candidate pool to prevent selection as a collator.
		#[pallet::call_index(8)]
		#[pallet::weight(<T as Config>::WeightInfo::schedule_leave_candidates(*candidate_count))]
		pub fn schedule_leave_candidates(
			origin: OriginFor<T>,
			candidate_count: u32,
		) -> DispatchResultWithPostInfo {
			let collator = ensure_signed(origin)?;
			let mut state = <CandidateInfo<T>>::get(&collator).ok_or(Error::<T>::CandidateDNE)?;
			let (now, when) = state.schedule_leave::<T>()?;
			let mut candidates = <CandidatePool<T>>::get();
			ensure!(
				candidate_count >= candidates.0.len() as u32,
				Error::<T>::TooLowCandidateCountToLeaveCandidates
			);
			if candidates.remove(&Bond::from_owner(collator.clone())) {
				<CandidatePool<T>>::put(candidates);
			}
			<CandidateInfo<T>>::insert(&collator, state);
			Self::deposit_event(Event::CandidateScheduledExit {
				exit_allowed_round: now,
				candidate: collator,
				scheduled_exit: when,
			});
			Ok(().into())
		}

		/// Execute leave candidates request
		#[pallet::call_index(9)]
		#[pallet::weight(
			<T as Config>::WeightInfo::execute_leave_candidates_worst_case(*candidate_delegation_count)
		)]
		pub fn execute_leave_candidates(
			origin: OriginFor<T>,
			candidate: T::AccountId,
			candidate_delegation_count: u32,
		) -> DispatchResultWithPostInfo {
			ensure_signed(origin)?;
			let state = <CandidateInfo<T>>::get(&candidate).ok_or(Error::<T>::CandidateDNE)?;
			ensure!(
				state.delegation_count <= candidate_delegation_count,
				Error::<T>::TooLowCandidateDelegationCountToLeaveCandidates
			);
			<Pallet<T>>::execute_leave_candidates_inner(candidate)
		}

		/// Cancel open request to leave candidates
		/// - only callable by collator account
		/// - result upon successful call is the candidate is active in the candidate pool
		#[pallet::call_index(10)]
		#[pallet::weight(<T as Config>::WeightInfo::cancel_leave_candidates(*candidate_count))]
		pub fn cancel_leave_candidates(
			origin: OriginFor<T>,
			candidate_count: u32,
		) -> DispatchResultWithPostInfo {
			let collator = ensure_signed(origin)?;
			let mut state = <CandidateInfo<T>>::get(&collator).ok_or(Error::<T>::CandidateDNE)?;
			ensure!(state.is_leaving(), Error::<T>::CandidateNotLeaving);
			state.go_online();
			let mut candidates = <CandidatePool<T>>::get();
			ensure!(
				candidates.0.len() as u32 <= candidate_count,
				Error::<T>::TooLowCandidateCountWeightHintCancelLeaveCandidates
			);
			let maybe_inserted_candidate = candidates
				.try_insert(Bond {
					owner: collator.clone(),
					amount: state.total_counted,
				})
				.map_err(|_| Error::<T>::CandidateLimitReached)?;
			ensure!(maybe_inserted_candidate, Error::<T>::AlreadyActive);
			<CandidatePool<T>>::put(candidates);
			<CandidateInfo<T>>::insert(&collator, state);
			Self::deposit_event(Event::CancelledCandidateExit {
				candidate: collator,
			});
			Ok(().into())
		}

		/// Temporarily leave the set of collator candidates without unbonding
		#[pallet::call_index(11)]
		#[pallet::weight(<T as Config>::WeightInfo::go_offline(MAX_CANDIDATES))]
		pub fn go_offline(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
			let collator = ensure_signed(origin)?;
			<Pallet<T>>::go_offline_inner(collator)
		}

		/// Rejoin the set of collator candidates if previously had called `go_offline`
		#[pallet::call_index(12)]
		#[pallet::weight(<T as Config>::WeightInfo::go_online(MAX_CANDIDATES))]
		pub fn go_online(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
			let collator = ensure_signed(origin)?;
			<Pallet<T>>::go_online_inner(collator)
		}

		/// Increase collator candidate self bond by `more`
		#[pallet::call_index(13)]
		#[pallet::weight(<T as Config>::WeightInfo::candidate_bond_more(MAX_CANDIDATES))]
		pub fn candidate_bond_more(
			origin: OriginFor<T>,
			more: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let candidate = ensure_signed(origin)?;
			<Pallet<T>>::candidate_bond_more_inner(candidate, more)
		}

		/// Request by collator candidate to decrease self bond by `less`
		#[pallet::call_index(14)]
		#[pallet::weight(<T as Config>::WeightInfo::schedule_candidate_bond_less())]
		pub fn schedule_candidate_bond_less(
			origin: OriginFor<T>,
			less: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let collator = ensure_signed(origin)?;
			let mut state = <CandidateInfo<T>>::get(&collator).ok_or(Error::<T>::CandidateDNE)?;
			let when = state.schedule_bond_less::<T>(less)?;
			<CandidateInfo<T>>::insert(&collator, state);
			Self::deposit_event(Event::CandidateBondLessRequested {
				candidate: collator,
				amount_to_decrease: less,
				execute_round: when,
			});
			Ok(().into())
		}

		/// Execute pending request to adjust the collator candidate self bond
		#[pallet::call_index(15)]
		#[pallet::weight(<T as Config>::WeightInfo::execute_candidate_bond_less(MAX_CANDIDATES))]
		pub fn execute_candidate_bond_less(
			origin: OriginFor<T>,
			candidate: T::AccountId,
		) -> DispatchResultWithPostInfo {
			ensure_signed(origin)?; // we may want to reward this if caller != candidate
			<Pallet<T>>::execute_candidate_bond_less_inner(candidate)
		}

		/// Cancel pending request to adjust the collator candidate self bond
		#[pallet::call_index(16)]
		#[pallet::weight(<T as Config>::WeightInfo::cancel_candidate_bond_less())]
		pub fn cancel_candidate_bond_less(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
			let collator = ensure_signed(origin)?;
			let mut state = <CandidateInfo<T>>::get(&collator).ok_or(Error::<T>::CandidateDNE)?;
			state.cancel_bond_less::<T>(collator.clone())?;
			<CandidateInfo<T>>::insert(&collator, state);
			Ok(().into())
		}

		/// DEPRECATED use delegateWithAutoCompound
		/// If caller is not a delegator and not a collator, then join the set of delegators
		/// If caller is a delegator, then makes delegation to change their delegation state
		#[pallet::call_index(17)]
		#[pallet::weight(
			<T as Config>::WeightInfo::delegate_with_auto_compound_worst()
		)]
		pub fn delegate(
			origin: OriginFor<T>,
			candidate: T::AccountId,
			amount: BalanceOf<T>,
			candidate_delegation_count: u32,
			delegation_count: u32,
		) -> DispatchResultWithPostInfo {
			let delegator = ensure_signed(origin)?;
			<AutoCompoundDelegations<T>>::delegate_with_auto_compound(
				candidate,
				delegator,
				amount,
				Percent::zero(),
				candidate_delegation_count,
				0,
				delegation_count,
			)
		}

		/// If caller is not a delegator and not a collator, then join the set of delegators
		/// If caller is a delegator, then makes delegation to change their delegation state
		/// Sets the auto-compound config for the delegation
		#[pallet::call_index(18)]
		#[pallet::weight(
			<T as Config>::WeightInfo::delegate_with_auto_compound(
				*candidate_delegation_count,
				*candidate_auto_compounding_delegation_count,
				*delegation_count,
			)
		)]
		pub fn delegate_with_auto_compound(
			origin: OriginFor<T>,
			candidate: T::AccountId,
			amount: BalanceOf<T>,
			auto_compound: Percent,
			candidate_delegation_count: u32,
			candidate_auto_compounding_delegation_count: u32,
			delegation_count: u32,
		) -> DispatchResultWithPostInfo {
			let delegator = ensure_signed(origin)?;
			<AutoCompoundDelegations<T>>::delegate_with_auto_compound(
				candidate,
				delegator,
				amount,
				auto_compound,
				candidate_delegation_count,
				candidate_auto_compounding_delegation_count,
				delegation_count,
			)
		}

		/// REMOVED, was schedule_leave_delegators
		#[pallet::call_index(19)]
		#[pallet::weight(<T as Config>::WeightInfo::set_staking_expectations())]
		pub fn removed_call_19(_origin: OriginFor<T>) -> DispatchResultWithPostInfo {
			fail!(Error::<T>::RemovedCall)
		}

		/// REMOVED, was execute_leave_delegators
		#[pallet::call_index(20)]
		#[pallet::weight(<T as Config>::WeightInfo::set_staking_expectations())]
		pub fn removed_call_20(_origin: OriginFor<T>) -> DispatchResultWithPostInfo {
			fail!(Error::<T>::RemovedCall)
		}

		/// REMOVED, was cancel_leave_delegators
		#[pallet::call_index(21)]
		#[pallet::weight(<T as Config>::WeightInfo::set_staking_expectations())]
		pub fn removed_call_21(_origin: OriginFor<T>) -> DispatchResultWithPostInfo {
			fail!(Error::<T>::RemovedCall)
		}

		/// Request to revoke an existing delegation. If successful, the delegation is scheduled
		/// to be allowed to be revoked via the `execute_delegation_request` extrinsic.
		/// The delegation receives no rewards for the rounds while a revoke is pending.
		/// A revoke may not be performed if any other scheduled request is pending.
		#[pallet::call_index(22)]
		#[pallet::weight(<T as Config>::WeightInfo::schedule_revoke_delegation(
			T::MaxTopDelegationsPerCandidate::get() + T::MaxBottomDelegationsPerCandidate::get()
		))]
		pub fn schedule_revoke_delegation(
			origin: OriginFor<T>,
			collator: T::AccountId,
		) -> DispatchResultWithPostInfo {
			let delegator = ensure_signed(origin)?;
			Self::delegation_schedule_revoke(collator, delegator)
		}

		/// Bond more for delegators wrt a specific collator candidate.
		#[pallet::call_index(23)]
		#[pallet::weight(<T as Config>::WeightInfo::delegator_bond_more(
			T::MaxTopDelegationsPerCandidate::get() + T::MaxBottomDelegationsPerCandidate::get()
		))]
		pub fn delegator_bond_more(
			origin: OriginFor<T>,
			candidate: T::AccountId,
			more: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let delegator = ensure_signed(origin)?;
			let (in_top, weight) = Self::delegation_bond_more_without_event(
				delegator.clone(),
				candidate.clone(),
				more.clone(),
			)?;
			Pallet::<T>::deposit_event(Event::DelegationIncreased {
				delegator,
				candidate,
				amount: more,
				in_top,
			});

			Ok(Some(weight).into())
		}

		/// Request bond less for delegators wrt a specific collator candidate. The delegation's
		/// rewards for rounds while the request is pending use the reduced bonded amount.
		/// A bond less may not be performed if any other scheduled request is pending.
		#[pallet::call_index(24)]
		#[pallet::weight(<T as Config>::WeightInfo::schedule_delegator_bond_less(
			T::MaxTopDelegationsPerCandidate::get() + T::MaxBottomDelegationsPerCandidate::get()
		))]
		pub fn schedule_delegator_bond_less(
			origin: OriginFor<T>,
			candidate: T::AccountId,
			less: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let delegator = ensure_signed(origin)?;
			Self::delegation_schedule_bond_decrease(candidate, delegator, less)
		}

		/// Execute pending request to change an existing delegation
		#[pallet::call_index(25)]
		#[pallet::weight(<T as Config>::WeightInfo::execute_delegator_revoke_delegation_worst())]
		pub fn execute_delegation_request(
			origin: OriginFor<T>,
			delegator: T::AccountId,
			candidate: T::AccountId,
		) -> DispatchResultWithPostInfo {
			ensure_signed(origin)?; // we may want to reward caller if caller != delegator
			Self::delegation_execute_scheduled_request(candidate, delegator)
		}

		/// Cancel request to change an existing delegation.
		#[pallet::call_index(26)]
		#[pallet::weight(<T as Config>::WeightInfo::cancel_delegation_request(350))]
		pub fn cancel_delegation_request(
			origin: OriginFor<T>,
			candidate: T::AccountId,
		) -> DispatchResultWithPostInfo {
			let delegator = ensure_signed(origin)?;
			Self::delegation_cancel_request(candidate, delegator)
		}

		/// Sets the auto-compounding reward percentage for a delegation.
		#[pallet::call_index(27)]
		#[pallet::weight(<T as Config>::WeightInfo::set_auto_compound(
			*candidate_auto_compounding_delegation_count_hint,
			*delegation_count_hint,
		))]
		pub fn set_auto_compound(
			origin: OriginFor<T>,
			candidate: T::AccountId,
			value: Percent,
			candidate_auto_compounding_delegation_count_hint: u32,
			delegation_count_hint: u32,
		) -> DispatchResultWithPostInfo {
			let delegator = ensure_signed(origin)?;
			<AutoCompoundDelegations<T>>::set_auto_compound(
				candidate,
				delegator,
				value,
				candidate_auto_compounding_delegation_count_hint,
				delegation_count_hint,
			)
		}

		/// Hotfix to remove existing empty entries for candidates that have left.
		#[pallet::call_index(28)]
		#[pallet::weight(
			T::DbWeight::get().reads_writes(2 * candidates.len() as u64, candidates.len() as u64)
		)]
		pub fn hotfix_remove_delegation_requests_exited_candidates(
			origin: OriginFor<T>,
			candidates: Vec<T::AccountId>,
		) -> DispatchResult {
			ensure_signed(origin)?;
			ensure!(candidates.len() < 100, <Error<T>>::InsufficientBalance);
			for candidate in &candidates {
				ensure!(
					<CandidateInfo<T>>::get(&candidate).is_none(),
					<Error<T>>::CandidateNotLeaving
				);
				ensure!(
					<DelegationScheduledRequests<T>>::get(&candidate).is_empty(),
					<Error<T>>::CandidateNotLeaving
				);
			}

			for candidate in candidates {
				<DelegationScheduledRequests<T>>::remove(candidate);
			}

			Ok(().into())
		}

		/// Notify a collator is inactive during MaxOfflineRounds
		#[pallet::call_index(29)]
		#[pallet::weight(<T as Config>::WeightInfo::notify_inactive_collator())]
		pub fn notify_inactive_collator(
			origin: OriginFor<T>,
			collator: T::AccountId,
		) -> DispatchResult {
			ensure!(
				<EnableMarkingOffline<T>>::get(),
				<Error<T>>::MarkingOfflineNotEnabled
			);
			ensure_signed(origin)?;

			let mut collators_len = 0usize;
			let max_collators = <TotalSelected<T>>::get();

			if let Some(len) = <SelectedCandidates<T>>::decode_len() {
				collators_len = len;
			};

			// Check collators length is not below or eq to 66% of max_collators.
			// We use saturating logic here with (2/3)
			// as it is dangerous to use floating point numbers directly.
			ensure!(
				collators_len * 3 > (max_collators * 2) as usize,
				<Error<T>>::TooLowCollatorCountToNotifyAsInactive
			);

			let round_info = <Round<T>>::get();
			let max_offline_rounds = T::MaxOfflineRounds::get();

			ensure!(
				round_info.current > max_offline_rounds,
				<Error<T>>::CurrentRoundTooLow
			);

			// Have rounds_to_check = [8,9]
			// in case we are in round 10 for instance
			// with MaxOfflineRounds = 2
			let first_round_to_check = round_info.current.saturating_sub(max_offline_rounds);
			let rounds_to_check = first_round_to_check..round_info.current;

			// If this counter is eq to max_offline_rounds,
			// the collator should be notified as inactive
			let mut inactive_counter: RoundIndex = 0u32;

			// Iter rounds to check
			//
			// - The collator has AtStake associated and their AwardedPts are zero
			//
			// If the previous condition is met in all rounds of rounds_to_check,
			// the collator is notified as inactive
			for r in rounds_to_check {
				let stake = <AtStake<T>>::get(r, &collator);
				let pts = <AwardedPts<T>>::get(r, &collator);

				if stake.is_some() && pts.is_zero() {
					inactive_counter = inactive_counter.saturating_add(1);
				}
			}

			if inactive_counter == max_offline_rounds {
				let _ = T::OnInactiveCollator::on_inactive_collator(
					collator.clone(),
					round_info.current.saturating_sub(1),
				);
			} else {
				return Err(<Error<T>>::CannotBeNotifiedAsInactive.into());
			}

			Ok(().into())
		}

		/// Enable/Disable marking offline feature
		#[pallet::call_index(30)]
		#[pallet::weight(
			Weight::from_parts(3_000_000u64, 4_000u64)
				.saturating_add(T::DbWeight::get().writes(1u64))
		)]
		pub fn enable_marking_offline(origin: OriginFor<T>, value: bool) -> DispatchResult {
			ensure_root(origin)?;
			<EnableMarkingOffline<T>>::set(value);
			Ok(())
		}

		/// Force join the set of collator candidates.
		/// It will skip the minimum required bond check.
		#[pallet::call_index(31)]
		#[pallet::weight(<T as Config>::WeightInfo::join_candidates(*candidate_count))]
		pub fn force_join_candidates(
			origin: OriginFor<T>,
			account: T::AccountId,
			bond: BalanceOf<T>,
			candidate_count: u32,
		) -> DispatchResultWithPostInfo {
			T::MonetaryGovernanceOrigin::ensure_origin(origin.clone())?;
			Self::join_candidates_inner(account, bond, candidate_count)
		}

		/// Set the inflation distribution configuration.
		#[pallet::call_index(32)]
		#[pallet::weight(<T as Config>::WeightInfo::set_inflation_distribution_config())]
		pub fn set_inflation_distribution_config(
			origin: OriginFor<T>,
			new: InflationDistributionConfig<T::AccountId>,
		) -> DispatchResultWithPostInfo {
			T::MonetaryGovernanceOrigin::ensure_origin(origin)?;
			let old = <InflationDistributionInfo<T>>::get().0;
			let new = new.0;
			ensure!(old != new, Error::<T>::NoWritingSameValue);
			let total_percent = new.iter().fold(0, |acc, x| acc + x.percent.deconstruct());
			ensure!(
				total_percent <= 100,
				Error::<T>::TotalInflationDistributionPercentExceeds100,
			);
			<InflationDistributionInfo<T>>::put::<InflationDistributionConfig<T::AccountId>>(
				new.clone().into(),
			);
			Self::deposit_event(Event::InflationDistributionConfigUpdated {
				old: old.into(),
				new: new.into(),
			});
			Ok(().into())
		}
	}

	/// Represents a payout made via `pay_one_collator_reward`.
	pub(crate) enum RewardPayment {
		/// A collator was paid
		Paid,
		/// A collator was skipped for payment. This can happen if they haven't been awarded any
		/// points, that is, they did not produce any blocks.
		Skipped,
		/// All collator payments have been processed.
		Finished,
	}

	impl<T: Config> Pallet<T> {
		pub fn set_candidate_bond_to_zero(acc: &T::AccountId) -> Weight {
			let actual_weight =
				<T as Config>::WeightInfo::set_candidate_bond_to_zero(T::MaxCandidates::get());
			if let Some(mut state) = <CandidateInfo<T>>::get(&acc) {
				state.bond_less::<T>(acc.clone(), state.bond);
				<CandidateInfo<T>>::insert(&acc, state);
			}
			actual_weight
		}

		pub fn is_delegator(acc: &T::AccountId) -> bool {
			<DelegatorState<T>>::get(acc).is_some()
		}

		pub fn is_candidate(acc: &T::AccountId) -> bool {
			<CandidateInfo<T>>::get(acc).is_some()
		}

		pub fn is_selected_candidate(acc: &T::AccountId) -> bool {
			<SelectedCandidates<T>>::get().binary_search(acc).is_ok()
		}

		pub fn join_candidates_inner(
			acc: T::AccountId,
			bond: BalanceOf<T>,
			candidate_count: u32,
		) -> DispatchResultWithPostInfo {
			ensure!(!Self::is_candidate(&acc), Error::<T>::CandidateExists);
			ensure!(!Self::is_delegator(&acc), Error::<T>::DelegatorExists);
			let mut candidates = <CandidatePool<T>>::get();
			let old_count = candidates.0.len() as u32;
			ensure!(
				candidate_count >= old_count,
				Error::<T>::TooLowCandidateCountWeightHintJoinCandidates
			);
			let maybe_inserted_candidate = candidates
				.try_insert(Bond {
					owner: acc.clone(),
					amount: bond,
				})
				.map_err(|_| Error::<T>::CandidateLimitReached)?;
			ensure!(maybe_inserted_candidate, Error::<T>::CandidateExists);

			ensure!(
				Self::get_collator_stakable_free_balance(&acc) >= bond,
				Error::<T>::InsufficientBalance,
			);
			T::Currency::set_lock(COLLATOR_LOCK_ID, &acc, bond, WithdrawReasons::all());
			let candidate = CandidateMetadata::new(bond);
			<CandidateInfo<T>>::insert(&acc, candidate);
			let empty_delegations: Delegations<T::AccountId, BalanceOf<T>> = Default::default();
			// insert empty top delegations
			<TopDelegations<T>>::insert(&acc, empty_delegations.clone());
			// insert empty bottom delegations
			<BottomDelegations<T>>::insert(&acc, empty_delegations);
			<CandidatePool<T>>::put(candidates);
			let new_total = <Total<T>>::get().saturating_add(bond);
			<Total<T>>::put(new_total);
			Self::deposit_event(Event::JoinedCollatorCandidates {
				account: acc,
				amount_locked: bond,
				new_total_amt_locked: new_total,
			});
			Ok(().into())
		}

		pub fn go_offline_inner(collator: T::AccountId) -> DispatchResultWithPostInfo {
			let mut state = <CandidateInfo<T>>::get(&collator).ok_or(Error::<T>::CandidateDNE)?;
			let mut candidates = <CandidatePool<T>>::get();
			let actual_weight = <T as Config>::WeightInfo::go_offline(candidates.0.len() as u32);

			ensure!(
				state.is_active(),
				DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: <Error<T>>::AlreadyOffline.into(),
				}
			);
			state.go_offline();

			if candidates.remove(&Bond::from_owner(collator.clone())) {
				<CandidatePool<T>>::put(candidates);
			}
			<CandidateInfo<T>>::insert(&collator, state);
			Self::deposit_event(Event::CandidateWentOffline {
				candidate: collator,
			});
			Ok(Some(actual_weight).into())
		}

		pub fn go_online_inner(collator: T::AccountId) -> DispatchResultWithPostInfo {
			let mut state = <CandidateInfo<T>>::get(&collator).ok_or(Error::<T>::CandidateDNE)?;
			let mut candidates = <CandidatePool<T>>::get();
			let actual_weight = <T as Config>::WeightInfo::go_online(candidates.0.len() as u32);

			ensure!(
				!state.is_active(),
				DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: <Error<T>>::AlreadyActive.into(),
				}
			);
			ensure!(
				!state.is_leaving(),
				DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: <Error<T>>::CannotGoOnlineIfLeaving.into(),
				}
			);
			state.go_online();

			let maybe_inserted_candidate = candidates
				.try_insert(Bond {
					owner: collator.clone(),
					amount: state.total_counted,
				})
				.map_err(|_| Error::<T>::CandidateLimitReached)?;
			ensure!(
				maybe_inserted_candidate,
				DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: <Error<T>>::AlreadyActive.into(),
				},
			);

			<CandidatePool<T>>::put(candidates);
			<CandidateInfo<T>>::insert(&collator, state);
			Self::deposit_event(Event::CandidateBackOnline {
				candidate: collator,
			});
			Ok(Some(actual_weight).into())
		}

		pub fn candidate_bond_more_inner(
			collator: T::AccountId,
			more: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let mut state = <CandidateInfo<T>>::get(&collator).ok_or(Error::<T>::CandidateDNE)?;
			let actual_weight =
				<T as Config>::WeightInfo::candidate_bond_more(T::MaxCandidates::get());

			state
				.bond_more::<T>(collator.clone(), more)
				.map_err(|err| DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: err,
				})?;
			let (is_active, total_counted) = (state.is_active(), state.total_counted);
			<CandidateInfo<T>>::insert(&collator, state);
			if is_active {
				Self::update_active(collator, total_counted);
			}
			Ok(Some(actual_weight).into())
		}

		pub fn execute_candidate_bond_less_inner(
			candidate: T::AccountId,
		) -> DispatchResultWithPostInfo {
			let mut state = <CandidateInfo<T>>::get(&candidate).ok_or(Error::<T>::CandidateDNE)?;
			let actual_weight =
				<T as Config>::WeightInfo::execute_candidate_bond_less(T::MaxCandidates::get());

			state
				.execute_bond_less::<T>(candidate.clone())
				.map_err(|err| DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: err,
				})?;
			<CandidateInfo<T>>::insert(&candidate, state);
			Ok(Some(actual_weight).into())
		}

		pub fn execute_leave_candidates_inner(
			candidate: T::AccountId,
		) -> DispatchResultWithPostInfo {
			let state = <CandidateInfo<T>>::get(&candidate).ok_or(Error::<T>::CandidateDNE)?;
			let actual_auto_compound_delegation_count =
				<AutoCompoundingDelegations<T>>::decode_len(&candidate).unwrap_or_default() as u32;

			// TODO use these to return actual weight used via `execute_leave_candidates_ideal`
			let actual_delegation_count = state.delegation_count;
			let actual_weight = <T as Config>::WeightInfo::execute_leave_candidates_ideal(
				actual_delegation_count,
				actual_auto_compound_delegation_count,
			);

			state
				.can_leave::<T>()
				.map_err(|err| DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: err,
				})?;
			let return_stake = |bond: Bond<T::AccountId, BalanceOf<T>>| {
				// remove delegation from delegator state
				let mut delegator = DelegatorState::<T>::get(&bond.owner).expect(
					"Collator state and delegator state are consistent. 
						Collator state has a record of this delegation. Therefore, 
						Delegator state also has a record. qed.",
				);

				if let Some(remaining) = delegator.rm_delegation::<T>(&candidate) {
					Self::delegation_remove_request_with_state(
						&candidate,
						&bond.owner,
						&mut delegator,
					);
					<AutoCompoundDelegations<T>>::remove_auto_compound(&candidate, &bond.owner);

					if remaining.is_zero() {
						// we do not remove the scheduled delegation requests from other collators
						// since it is assumed that they were removed incrementally before only the
						// last delegation was left.
						<DelegatorState<T>>::remove(&bond.owner);
						T::Currency::remove_lock(DELEGATOR_LOCK_ID, &bond.owner);
					} else {
						<DelegatorState<T>>::insert(&bond.owner, delegator);
					}
				} else {
					// TODO: review. we assume here that this delegator has no remaining staked
					// balance, so we ensure the lock is cleared
					T::Currency::remove_lock(DELEGATOR_LOCK_ID, &bond.owner);
				}
			};
			// total backing stake is at least the candidate self bond
			let mut total_backing = state.bond;
			// return all top delegations
			let top_delegations =
				<TopDelegations<T>>::take(&candidate).expect("CandidateInfo existence checked");
			for bond in top_delegations.delegations {
				return_stake(bond);
			}
			total_backing = total_backing.saturating_add(top_delegations.total);
			// return all bottom delegations
			let bottom_delegations =
				<BottomDelegations<T>>::take(&candidate).expect("CandidateInfo existence checked");
			for bond in bottom_delegations.delegations {
				return_stake(bond);
			}
			total_backing = total_backing.saturating_add(bottom_delegations.total);
			// return stake to collator
			T::Currency::remove_lock(COLLATOR_LOCK_ID, &candidate);
			<CandidateInfo<T>>::remove(&candidate);
			<DelegationScheduledRequests<T>>::remove(&candidate);
			<AutoCompoundingDelegations<T>>::remove(&candidate);
			<TopDelegations<T>>::remove(&candidate);
			<BottomDelegations<T>>::remove(&candidate);
			let new_total_staked = <Total<T>>::get().saturating_sub(total_backing);
			<Total<T>>::put(new_total_staked);
			Self::deposit_event(Event::CandidateLeft {
				ex_candidate: candidate,
				unlocked_amount: total_backing,
				new_total_amt_locked: new_total_staked,
			});
			Ok(Some(actual_weight).into())
		}

		/// Returns an account's stakable balance which is not locked in delegation staking
		pub fn get_delegator_stakable_balance(acc: &T::AccountId) -> BalanceOf<T> {
			let mut stakable_balance =
				T::Currency::free_balance(acc).saturating_add(T::Currency::reserved_balance(acc));

			if let Some(state) = <DelegatorState<T>>::get(acc) {
				stakable_balance = stakable_balance.saturating_sub(state.total());
			}
			stakable_balance
		}

		/// Returns an account's free balance which is not locked in collator staking
		pub fn get_collator_stakable_free_balance(acc: &T::AccountId) -> BalanceOf<T> {
			let mut balance = T::Currency::free_balance(acc);
			if let Some(info) = <CandidateInfo<T>>::get(acc) {
				balance = balance.saturating_sub(info.bond);
			}
			balance
		}

		/// Returns a delegations auto-compound value.
		pub fn delegation_auto_compound(
			candidate: &T::AccountId,
			delegator: &T::AccountId,
		) -> Percent {
			<AutoCompoundDelegations<T>>::auto_compound(candidate, delegator)
		}

		/// Caller must ensure candidate is active before calling
		pub(crate) fn update_active(candidate: T::AccountId, total: BalanceOf<T>) {
			let mut candidates = <CandidatePool<T>>::get();
			candidates.remove(&Bond::from_owner(candidate.clone()));
			candidates
				.try_insert(Bond {
					owner: candidate,
					amount: total,
				})
				.expect(
					"the candidate is removed in previous step so the length cannot increase; qed",
				);
			<CandidatePool<T>>::put(candidates);
		}

		/// Compute round issuance based on duration of the given round
		fn compute_issuance(round_duration: u64, round_length: u32) -> BalanceOf<T> {
			let ideal_duration: BalanceOf<T> = round_length
				.saturating_mul(T::BlockTime::get() as u32)
				.into();
			let config = <InflationConfig<T>>::get();
			let round_issuance = crate::inflation::round_issuance_range::<T>(config.round);

			// Initial formula: (round_duration / ideal_duration) * ideal_issuance
			// We multiply before the division to reduce rounding effects
			BalanceOf::<T>::from(round_duration as u32).saturating_mul(round_issuance.ideal)
				/ (ideal_duration)
		}

		/// Remove delegation from candidate state
		/// Amount input should be retrieved from delegator and it informs the storage lookups
		pub(crate) fn delegator_leaves_candidate(
			candidate: T::AccountId,
			delegator: T::AccountId,
			amount: BalanceOf<T>,
		) -> DispatchResult {
			let mut state = <CandidateInfo<T>>::get(&candidate).ok_or(Error::<T>::CandidateDNE)?;
			state.rm_delegation_if_exists::<T>(&candidate, delegator.clone(), amount)?;
			let new_total_locked = <Total<T>>::get().saturating_sub(amount);
			<Total<T>>::put(new_total_locked);
			let new_total = state.total_counted;
			<CandidateInfo<T>>::insert(&candidate, state);
			Self::deposit_event(Event::DelegatorLeftCandidate {
				delegator: delegator,
				candidate: candidate,
				unstaked_amount: amount,
				total_candidate_staked: new_total,
			});
			Ok(())
		}

		pub(crate) fn prepare_staking_payouts(
			round_info: RoundInfo<BlockNumberFor<T>>,
			round_duration: u64,
		) -> Weight {
			let RoundInfo {
				current: now,
				length: round_length,
				..
			} = round_info;

			// This function is called right after the round index increment,
			// and the goal is to compute the payout informations for the round that just ended.
			// We don't need to saturate here because the genesis round is 1.
			let prepare_payout_for_round = now - 1;

			// Return early if there is no blocks for this round
			if <Points<T>>::get(prepare_payout_for_round).is_zero() {
				return Weight::zero();
			}

			// Compute total issuance based on round duration
			let total_issuance = Self::compute_issuance(round_duration, round_length);
			// reserve portion of issuance for parachain bond account
			let mut left_issuance = total_issuance;

			let configs = <InflationDistributionInfo<T>>::get().0;
			for (index, config) in configs.iter().enumerate() {
				if config.percent.is_zero() {
					continue;
				}
				let reserve = config.percent * total_issuance;
				if let Ok(imb) = T::Currency::deposit_into_existing(&config.account, reserve) {
					// update round issuance if transfer succeeds
					left_issuance = left_issuance.saturating_sub(imb.peek());
					Self::deposit_event(Event::InflationDistributed {
						index: index as u32,
						account: config.account.clone(),
						value: imb.peek(),
					});
				}
			}

			let payout = DelayedPayout {
				round_issuance: total_issuance,
				total_staking_reward: left_issuance,
				collator_commission: <CollatorCommission<T>>::get(),
			};

			<DelayedPayouts<T>>::insert(prepare_payout_for_round, payout);

			<T as Config>::WeightInfo::prepare_staking_payouts()
		}

		/// Wrapper around pay_one_collator_reward which handles the following logic:
		/// * whether or not a payout needs to be made
		/// * cleaning up when payouts are done
		/// * returns the weight consumed by pay_one_collator_reward if applicable
		fn handle_delayed_payouts(now: RoundIndex) -> Weight {
			let delay = T::RewardPaymentDelay::get();

			// don't underflow uint
			if now < delay {
				return Weight::from_parts(0u64, 0);
			}

			let paid_for_round = now.saturating_sub(delay);

			if let Some(payout_info) = <DelayedPayouts<T>>::get(paid_for_round) {
				let result = Self::pay_one_collator_reward(paid_for_round, payout_info);

				// clean up storage items that we no longer need
				if matches!(result.0, RewardPayment::Finished) {
					<DelayedPayouts<T>>::remove(paid_for_round);
					<Points<T>>::remove(paid_for_round);
				}
				result.1 // weight consumed by pay_one_collator_reward
			} else {
				Weight::from_parts(0u64, 0)
			}
		}

		/// Payout a single collator from the given round.
		///
		/// Returns an optional tuple of (Collator's AccountId, total paid)
		/// or None if there were no more payouts to be made for the round.
		pub(crate) fn pay_one_collator_reward(
			paid_for_round: RoundIndex,
			payout_info: DelayedPayout<BalanceOf<T>>,
		) -> (RewardPayment, Weight) {
			// 'early_weight' tracks weight used for reads/writes done early in this fn before its
			// early-exit codepaths.
			let mut early_weight = Weight::zero();

			// TODO: it would probably be optimal to roll Points into the DelayedPayouts storage
			// item so that we do fewer reads each block
			let total_points = <Points<T>>::get(paid_for_round);
			early_weight = early_weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));

			if total_points.is_zero() {
				// TODO: this case is obnoxious... it's a value query, so it could mean one of two
				// different logic errors:
				// 1. we removed it before we should have
				// 2. we called pay_one_collator_reward when we were actually done with deferred
				//    payouts
				log::warn!("pay_one_collator_reward called with no <Points<T>> for the round!");
				return (RewardPayment::Finished, early_weight);
			}

			let collator_fee = payout_info.collator_commission;
			let collator_issuance = collator_fee * payout_info.round_issuance;
			if let Some((collator, state)) =
				<AtStake<T>>::iter_prefix(paid_for_round).drain().next()
			{
				// read and kill AtStake
				early_weight = early_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));

				// Take the awarded points for the collator
				let pts = <AwardedPts<T>>::take(paid_for_round, &collator);
				// read and kill AwardedPts
				early_weight = early_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));
				if pts == 0 {
					return (RewardPayment::Skipped, early_weight);
				}

				// 'extra_weight' tracks weight returned from fns that we delegate to which can't be
				// known ahead of time.
				let mut extra_weight = Weight::zero();
				let pct_due = Perbill::from_rational(pts, total_points);
				let total_paid = pct_due * payout_info.total_staking_reward;
				let mut amt_due = total_paid;

				let num_delegators = state.delegations.len();
				let mut num_paid_delegations = 0u32;
				let mut num_auto_compounding = 0u32;
				let num_scheduled_requests =
					<DelegationScheduledRequests<T>>::decode_len(&collator).unwrap_or_default();
				if state.delegations.is_empty() {
					// solo collator with no delegators
					extra_weight = extra_weight
						.saturating_add(T::PayoutCollatorReward::payout_collator_reward(
							paid_for_round,
							collator.clone(),
							amt_due,
						))
						.saturating_add(T::OnCollatorPayout::on_collator_payout(
							paid_for_round,
							collator.clone(),
							amt_due,
						));
				} else {
					// pay collator first; commission + due_portion
					let collator_pct = Perbill::from_rational(state.bond, state.total);
					let commission = pct_due * collator_issuance;
					amt_due = amt_due.saturating_sub(commission);
					let collator_reward = (collator_pct * amt_due).saturating_add(commission);
					extra_weight = extra_weight
						.saturating_add(T::PayoutCollatorReward::payout_collator_reward(
							paid_for_round,
							collator.clone(),
							collator_reward,
						))
						.saturating_add(T::OnCollatorPayout::on_collator_payout(
							paid_for_round,
							collator.clone(),
							collator_reward,
						));

					// pay delegators due portion
					for BondWithAutoCompound {
						owner,
						amount,
						auto_compound,
					} in state.delegations
					{
						let percent = Perbill::from_rational(amount, state.total);
						let due = percent * amt_due;
						if !due.is_zero() {
							num_auto_compounding += if auto_compound.is_zero() { 0 } else { 1 };
							num_paid_delegations += 1u32;
							Self::mint_and_compound(
								due,
								auto_compound.clone(),
								collator.clone(),
								owner.clone(),
							);
						}
					}
				}

				extra_weight = extra_weight.saturating_add(
					<T as Config>::WeightInfo::pay_one_collator_reward_best(
						num_paid_delegations,
						num_auto_compounding,
						num_scheduled_requests as u32,
					),
				);

				(
					RewardPayment::Paid,
					<T as Config>::WeightInfo::pay_one_collator_reward(num_delegators as u32)
						.saturating_add(extra_weight),
				)
			} else {
				// Note that we don't clean up storage here; it is cleaned up in
				// handle_delayed_payouts()
				(RewardPayment::Finished, Weight::from_parts(0u64, 0))
			}
		}

		/// Compute the top `TotalSelected` candidates in the CandidatePool and return
		/// a vec of their AccountIds (sorted by AccountId).
		///
		/// If the returned vec is empty, the previous candidates should be used.
		pub fn compute_top_candidates() -> Vec<T::AccountId> {
			let top_n = <TotalSelected<T>>::get() as usize;
			if top_n == 0 {
				return vec![];
			}

			let candidates = <CandidatePool<T>>::get().0;

			// If the number of candidates is greater than top_n, select the candidates with higher
			// amount. Otherwise, return all the candidates.
			if candidates.len() > top_n {
				// Partially sort candidates such that element at index `top_n - 1` is sorted, and
				// all the elements in the range 0..top_n are the top n elements.
				let sorted_candidates = candidates
					.try_mutate(|inner| {
						inner.select_nth_unstable_by(top_n - 1, |a, b| {
							// Order by amount, then owner. The owner is needed to ensure a stable order
							// when two accounts have the same amount.
							a.amount
								.cmp(&b.amount)
								.then_with(|| a.owner.cmp(&b.owner))
								.reverse()
						});
					})
					.expect("sort cannot increase item count; qed");

				let mut collators = sorted_candidates
					.into_iter()
					.take(top_n)
					.map(|x| x.owner)
					.collect::<Vec<_>>();

				// Sort collators by AccountId
				collators.sort();

				collators
			} else {
				// Return all candidates
				// The candidates are already sorted by AccountId, so no need to sort again
				candidates.into_iter().map(|x| x.owner).collect::<Vec<_>>()
			}
		}
		/// Best as in most cumulatively supported in terms of stake
		/// Returns [collator_count, delegation_count, total staked]
		pub(crate) fn select_top_candidates(now: RoundIndex) -> (Weight, u32, u32, BalanceOf<T>) {
			let (mut collator_count, mut delegation_count, mut total) =
				(0u32, 0u32, BalanceOf::<T>::zero());
			// choose the top TotalSelected qualified candidates, ordered by stake
			let collators = Self::compute_top_candidates();
			if collators.is_empty() {
				// SELECTION FAILED TO SELECT >=1 COLLATOR => select collators from previous round
				let last_round = now.saturating_sub(1u32);
				let mut total_per_candidate: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();
				// set this round AtStake to last round AtStake
				for (account, snapshot) in <AtStake<T>>::iter_prefix(last_round) {
					collator_count = collator_count.saturating_add(1u32);
					delegation_count =
						delegation_count.saturating_add(snapshot.delegations.len() as u32);
					total = total.saturating_add(snapshot.total);
					total_per_candidate.insert(account.clone(), snapshot.total);
					<AtStake<T>>::insert(now, account, snapshot);
				}
				// `SelectedCandidates` remains unchanged from last round
				// emit CollatorChosen event for tools that use this event
				for candidate in <SelectedCandidates<T>>::get() {
					let snapshot_total = total_per_candidate
						.get(&candidate)
						.expect("all selected candidates have snapshots");
					Self::deposit_event(Event::CollatorChosen {
						round: now,
						collator_account: candidate,
						total_exposed_amount: *snapshot_total,
					})
				}
				let weight = <T as Config>::WeightInfo::select_top_candidates(0, 0);
				return (weight, collator_count, delegation_count, total);
			}

			// snapshot exposure for round for weighting reward distribution
			for account in collators.iter() {
				let state = <CandidateInfo<T>>::get(account)
					.expect("all members of CandidateQ must be candidates");

				collator_count = collator_count.saturating_add(1u32);
				delegation_count = delegation_count.saturating_add(state.delegation_count);
				total = total.saturating_add(state.total_counted);
				let CountedDelegations {
					uncounted_stake,
					rewardable_delegations,
				} = Self::get_rewardable_delegators(&account);
				let total_counted = state.total_counted.saturating_sub(uncounted_stake);

				let auto_compounding_delegations = <AutoCompoundingDelegations<T>>::get(&account)
					.into_iter()
					.map(|x| (x.delegator, x.value))
					.collect::<BTreeMap<_, _>>();
				let rewardable_delegations = rewardable_delegations
					.into_iter()
					.map(|d| BondWithAutoCompound {
						owner: d.owner.clone(),
						amount: d.amount,
						auto_compound: auto_compounding_delegations
							.get(&d.owner)
							.cloned()
							.unwrap_or_else(|| Percent::zero()),
					})
					.collect();

				let snapshot = CollatorSnapshot {
					bond: state.bond,
					delegations: rewardable_delegations,
					total: total_counted,
				};
				<AtStake<T>>::insert(now, account, snapshot);
				Self::deposit_event(Event::CollatorChosen {
					round: now,
					collator_account: account.clone(),
					total_exposed_amount: state.total_counted,
				});
			}
			// insert canonical collator set
			<SelectedCandidates<T>>::put(
				BoundedVec::try_from(collators)
					.expect("subset of collators is always less than or equal to max candidates"),
			);

			let avg_delegator_count = delegation_count.checked_div(collator_count).unwrap_or(0);
			let weight = <T as Config>::WeightInfo::select_top_candidates(
				collator_count,
				avg_delegator_count,
			);
			(weight, collator_count, delegation_count, total)
		}

		/// Apply the delegator intent for revoke and decrease in order to build the
		/// effective list of delegators with their intended bond amount.
		///
		/// This will:
		/// - if [DelegationChange::Revoke] is outstanding, set the bond amount to 0.
		/// - if [DelegationChange::Decrease] is outstanding, subtract the bond by specified amount.
		/// - else, do nothing
		///
		/// The intended bond amounts will be used while calculating rewards.
		pub(crate) fn get_rewardable_delegators(collator: &T::AccountId) -> CountedDelegations<T> {
			let requests = <DelegationScheduledRequests<T>>::get(collator)
				.into_iter()
				.map(|x| (x.delegator, x.action))
				.collect::<BTreeMap<_, _>>();
			let mut uncounted_stake = BalanceOf::<T>::zero();
			let rewardable_delegations = <TopDelegations<T>>::get(collator)
				.expect("all members of CandidateQ must be candidates")
				.delegations
				.into_iter()
				.map(|mut bond| {
					bond.amount = match requests.get(&bond.owner) {
						None => bond.amount,
						Some(DelegationAction::Revoke(_)) => {
							uncounted_stake = uncounted_stake.saturating_add(bond.amount);
							BalanceOf::<T>::zero()
						}
						Some(DelegationAction::Decrease(amount)) => {
							uncounted_stake = uncounted_stake.saturating_add(*amount);
							bond.amount.saturating_sub(*amount)
						}
					};

					bond
				})
				.collect();
			CountedDelegations {
				uncounted_stake,
				rewardable_delegations,
			}
		}

		/// This function exists as a helper to delegator_bond_more & auto_compound functionality.
		/// Any changes to this function must align with both user-initiated bond increases and
		/// auto-compounding bond increases.
		/// Any feature-specific preconditions should be validated before this function is invoked.
		/// Any feature-specific events must be emitted after this function is invoked.
		pub fn delegation_bond_more_without_event(
			delegator: T::AccountId,
			candidate: T::AccountId,
			more: BalanceOf<T>,
		) -> Result<
			(bool, Weight),
			DispatchErrorWithPostInfo<frame_support::dispatch::PostDispatchInfo>,
		> {
			let mut state = <DelegatorState<T>>::get(&delegator).ok_or(Error::<T>::DelegatorDNE)?;
			ensure!(
				!Self::delegation_request_revoke_exists(&candidate, &delegator),
				Error::<T>::PendingDelegationRevoke
			);

			let actual_weight = <T as Config>::WeightInfo::delegator_bond_more(
				<DelegationScheduledRequests<T>>::decode_len(&candidate).unwrap_or_default() as u32,
			);
			let in_top = state
				.increase_delegation::<T>(candidate.clone(), more)
				.map_err(|err| DispatchErrorWithPostInfo {
					post_info: Some(actual_weight).into(),
					error: err,
				})?;

			Ok((in_top, actual_weight))
		}

		/// Mint a specified reward amount to the beneficiary account. Emits the [Rewarded] event.
		pub fn mint(amt: BalanceOf<T>, to: T::AccountId) {
			if let Ok(amount_transferred) = T::Currency::deposit_into_existing(&to, amt) {
				Self::deposit_event(Event::Rewarded {
					account: to.clone(),
					rewards: amount_transferred.peek(),
				});
			}
		}

		/// Mint a specified reward amount to the collator's account. Emits the [Rewarded] event.
		pub fn mint_collator_reward(
			_paid_for_round: RoundIndex,
			collator_id: T::AccountId,
			amt: BalanceOf<T>,
		) -> Weight {
			if let Ok(amount_transferred) = T::Currency::deposit_into_existing(&collator_id, amt) {
				Self::deposit_event(Event::Rewarded {
					account: collator_id.clone(),
					rewards: amount_transferred.peek(),
				});
			}
			<T as Config>::WeightInfo::mint_collator_reward()
		}

		/// Mint and compound delegation rewards. The function mints the amount towards the
		/// delegator and tries to compound a specified percent of it back towards the delegation.
		/// If a scheduled delegation revoke exists, then the amount is only minted, and nothing is
		/// compounded. Emits the [Compounded] event.
		pub fn mint_and_compound(
			amt: BalanceOf<T>,
			compound_percent: Percent,
			candidate: T::AccountId,
			delegator: T::AccountId,
		) {
			if let Ok(amount_transferred) =
				T::Currency::deposit_into_existing(&delegator, amt.clone())
			{
				Self::deposit_event(Event::Rewarded {
					account: delegator.clone(),
					rewards: amount_transferred.peek(),
				});

				let compound_amount = compound_percent.mul_ceil(amount_transferred.peek());
				if compound_amount.is_zero() {
					return;
				}

				if let Err(err) = Self::delegation_bond_more_without_event(
					delegator.clone(),
					candidate.clone(),
					compound_amount.clone(),
				) {
					log::debug!(
						"skipped compounding staking reward towards candidate '{:?}' for delegator '{:?}': {:?}",
						candidate,
						delegator,
						err
					);
					return;
				};

				Pallet::<T>::deposit_event(Event::Compounded {
					delegator,
					candidate,
					amount: compound_amount.clone(),
				});
			};
		}
	}

	/// Add reward points to block authors:
	/// * 20 points to the block producer for producing a block in the chain
	impl<T: Config> Pallet<T> {
		fn award_points_to_block_author() {
			let author = T::BlockAuthor::get();
			let now = <Round<T>>::get().current;
			let score_plus_20 = <AwardedPts<T>>::get(now, &author).saturating_add(20);
			<AwardedPts<T>>::insert(now, author, score_plus_20);
			<Points<T>>::mutate(now, |x| *x = x.saturating_add(20));
		}
	}

	impl<T: Config> nimbus_primitives::CanAuthor<T::AccountId> for Pallet<T> {
		fn can_author(account: &T::AccountId, _slot: &u32) -> bool {
			Self::is_selected_candidate(account)
		}
	}

	impl<T: Config> Get<Vec<T::AccountId>> for Pallet<T> {
		fn get() -> Vec<T::AccountId> {
			Self::selected_candidates().into_inner()
		}
	}
}