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
// --- core ---
use core::marker::PhantomData;
// --- paritytech ---
use frame_election_provider_support::*;
use frame_support::{
	dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo, WithPostDispatchInfo},
	ensure,
	traits::{
		Currency, EstimateNextNewSession, ExistenceRequirement, Get, Imbalance, LockableCurrency,
		OnUnbalanced, UnixTime, WithdrawReasons,
	},
	weights::{DispatchClass, Weight},
};
use frame_system::pallet_prelude::BlockNumberFor;
use sp_runtime::{
	helpers_128bit,
	traits::{AccountIdConversion, AtLeast32BitUnsigned, Bounded, Convert, Saturating, Zero},
	Perbill, Perquintill, SaturatedConversion,
};
use sp_staking::{offence::*, *};
use sp_std::{borrow::ToOwned, collections::btree_map::BTreeMap, prelude::*};
// --- darwinia-network ---
use crate::*;
use darwinia_support::balance::StakingLock;

impl<T: Config> Pallet<T> {
	pub fn account_id() -> AccountId<T> {
		T::PalletId::get().into_account()
	}

	/// Update the ledger while bonding ring and compute the *KTON* reward
	pub fn bond_ring(
		stash: &AccountId<T>,
		controller: &AccountId<T>,
		value: RingBalance<T>,
		promise_month: u8,
		mut ledger: StakingLedgerT<T>,
	) -> Result<(TsInMs, TsInMs), DispatchError> {
		let StakingLedger { active, active_deposit_ring, deposit_items, active_kton, .. } =
			&mut ledger;

		let origin_active = active.clone();
		let start_time = T::UnixTime::now().as_millis().saturated_into::<TsInMs>();
		let mut expire_time = start_time;

		*active = active.saturating_add(value);

		// Last check: the new active amount of ledger must be more than ED.
		ensure!(
			*active >= T::RingCurrency::minimum_balance()
				|| *active_kton >= T::KtonCurrency::minimum_balance(),
			<Error<T>>::InsufficientBond
		);

		// If stash promise to an extra-lock
		// there will be extra reward (*KTON*), which can also be used for staking
		if promise_month > 0 {
			expire_time += promise_month as TsInMs * MONTH_IN_MILLISECONDS;
			*active_deposit_ring += value;

			let kton_return = inflation::compute_kton_reward::<T>(value, promise_month);
			let kton_positive_imbalance = T::KtonCurrency::deposit_creating(&stash, kton_return);

			T::KtonReward::on_unbalanced(kton_positive_imbalance);
			deposit_items.push(TimeDepositItem { value, start_time, expire_time });
		}

		Self::update_ledger(&controller, &ledger);
		Self::update_staking_pool(ledger.active, origin_active, Zero::zero(), Zero::zero());

		Ok((start_time, expire_time))
	}

	/// Update the ledger while bonding controller with *KTON*
	pub fn bond_kton(
		controller: &AccountId<T>,
		value: KtonBalance<T>,
		mut ledger: StakingLedgerT<T>,
	) -> DispatchResult {
		let StakingLedger { active, active_kton, .. } = &mut ledger;
		let origin_active_kton = active_kton.clone();

		*active_kton = origin_active_kton.saturating_add(value);

		// Last check: the new active amount of ledger must be more than ED.
		ensure!(
			*active >= T::RingCurrency::minimum_balance()
				|| *active_kton >= T::KtonCurrency::minimum_balance(),
			<Error<T>>::InsufficientBond
		);

		Self::update_ledger(&controller, &ledger);
		Self::update_staking_pool(
			Zero::zero(),
			Zero::zero(),
			ledger.active_kton,
			origin_active_kton,
		);

		Ok(())
	}

	/// Turn the expired deposit items into normal bond
	pub fn clear_mature_deposits(mut ledger: StakingLedgerT<T>) -> (StakingLedgerT<T>, bool) {
		let now = T::UnixTime::now().as_millis().saturated_into::<TsInMs>();
		let StakingLedger { stash, active_deposit_ring, deposit_items, .. } = &mut ledger;
		let mut mutated = false;

		deposit_items.retain(|item| {
			if item.expire_time > now {
				true
			} else {
				mutated = true;
				*active_deposit_ring = active_deposit_ring.saturating_sub(item.value);

				false
			}
		});

		if mutated {
			Self::deposit_event(Event::DepositsClaimed(stash.to_owned()));
		}

		(ledger, mutated)
	}

	// power is a mixture of ring and kton
	// For *RING* power = ring_ratio * POWER_COUNT / 2
	// For *KTON* power = kton_ratio * POWER_COUNT / 2
	pub fn currency_to_power<S: TryInto<Balance>>(active: S, pool: S) -> Power {
		(Perquintill::from_rational(
			active.saturated_into::<Balance>(),
			pool.saturated_into::<Balance>().max(1),
		) * (T::TotalPower::get() as Balance / 2)) as _
	}

	/// The total power that can be slashed from a stash account as of right now.
	pub fn power_of(stash: &AccountId<T>) -> Power {
		// Weight note: consider making the stake accessible through stash.
		Self::bonded(stash)
			.and_then(Self::ledger)
			.map(|l| {
				// dbg!(Self::currency_to_power::<_>(
				// 	l.active,
				// 	Self::ring_pool()
				// ));

				Self::currency_to_power::<_>(l.active, Self::ring_pool())
					+ Self::currency_to_power::<_>(l.active_kton, Self::kton_pool())
			})
			.unwrap_or_default()
	}

	pub fn stake_of(who: &AccountId<T>) -> (RingBalance<T>, KtonBalance<T>) {
		// Weight note: consider making the stake accessible through stash.
		Self::bonded(who)
			.and_then(Self::ledger)
			.map(|l| (l.active, l.active_kton))
			.unwrap_or_default()
	}

	pub fn weight_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
		Box::new(Self::weight_of)
	}

	pub fn weight_of(who: &AccountId<T>) -> VoteWeight {
		Self::power_of(who) as _
	}

	pub fn do_payout_stakers(
		validator_stash: AccountId<T>,
		era: EraIndex,
	) -> DispatchResultWithPostInfo {
		// Validate input data
		let current_era = <CurrentEra<T>>::get().ok_or_else(|| {
			<Error<T>>::InvalidEraToReward
				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
		})?;
		ensure!(
			era <= current_era,
			<Error<T>>::InvalidEraToReward
				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
		);
		let history_depth = Self::history_depth();
		ensure!(
			era >= current_era.saturating_sub(history_depth),
			<Error<T>>::InvalidEraToReward
				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
		);

		// Note: if era has no reward to be claimed, era may be future. better not to update
		// `ledger.claimed_rewards` in this case.
		let era_payout = <ErasValidatorReward<T>>::get(&era).ok_or_else(|| {
			<Error<T>>::InvalidEraToReward
				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
		})?;

		let controller = Self::bonded(&validator_stash).ok_or_else(|| {
			<Error<T>>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
		})?;
		let mut ledger = <Ledger<T>>::get(&controller).ok_or_else(|| <Error<T>>::NotController)?;

		ledger.claimed_rewards.retain(|&x| x >= current_era.saturating_sub(history_depth));
		match ledger.claimed_rewards.binary_search(&era) {
			Ok(_) => Err(<Error<T>>::AlreadyClaimed
				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))?,
			Err(pos) => ledger.claimed_rewards.insert(pos, era),
		}

		let exposure = <ErasStakersClipped<T>>::get(&era, &ledger.stash);

		/* Input data seems good, no errors allowed after this point */

		<Ledger<T>>::insert(&controller, &ledger);

		// Get Era reward points. It has TOTAL and INDIVIDUAL
		// Find the fraction of the era reward that belongs to the validator
		// Take that fraction of the eras rewards to split to nominator and validator
		//
		// Then look at the validator, figure out the proportion of their reward
		// which goes to them and each of their nominators.

		let era_reward_points = <ErasRewardPoints<T>>::get(&era);
		let total_reward_points = era_reward_points.total;
		let validator_reward_points = era_reward_points
			.individual
			.get(&ledger.stash)
			.map(|points| *points)
			.unwrap_or_else(|| Zero::zero());

		// Nothing to do if they have no reward points.
		if validator_reward_points.is_zero() {
			return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into());
		}

		// This is the fraction of the total reward that the validator and the
		// nominators will get.
		let validator_total_reward_part =
			Perbill::from_rational(validator_reward_points, total_reward_points);
		// This is how much validator + nominators are entitled to.
		let validator_total_payout = validator_total_reward_part * era_payout;

		let validator_prefs = Self::eras_validator_prefs(&era, &validator_stash);
		// Validator first gets a cut off the top.
		let validator_commission = validator_prefs.commission;
		let validator_commission_payout = validator_commission * validator_total_payout;

		let validator_leftover_payout = validator_total_payout - validator_commission_payout;
		// Now let's calculate how this is split to the validator.
		let validator_exposure_part =
			Perbill::from_rational(exposure.own_power, exposure.total_power);
		let validator_staking_payout = validator_exposure_part * validator_leftover_payout;

		Self::deposit_event(<Event<T>>::PayoutStarted(era, ledger.stash.clone()));

		// Due to the `payout * percent` there might be some losses
		let mut actual_payout = <RingPositiveImbalance<T>>::zero();

		// We can now make total validator payout:
		if let Some(imbalance) =
			Self::make_payout(&ledger.stash, validator_staking_payout + validator_commission_payout)
		{
			let payout = imbalance.peek();

			actual_payout.subsume(imbalance);

			Self::deposit_event(Event::Rewarded(ledger.stash, payout));
		}

		// Track the number of payout ops to nominators. Note:
		// `WeightInfo::payout_stakers_alive_staked` always assumes at least a validator is paid
		// out, so we do not need to count their payout op.
		let mut nominator_payout_count: u32 = 0;

		// Lets now calculate how this is split to the nominators.
		// Reward only the clipped exposures. Note this is not necessarily sorted.
		for nominator in exposure.others.iter() {
			let nominator_exposure_part =
				Perbill::from_rational(nominator.power, exposure.total_power);

			let nominator_reward: RingBalance<T> =
				nominator_exposure_part * validator_leftover_payout;
			// We can now make nominator payout:
			if let Some(imbalance) = Self::make_payout(&nominator.who, nominator_reward) {
				let payout = imbalance.peek();

				actual_payout.subsume(imbalance);

				// Note: this logic does not count payouts for `RewardDestination::None`.
				nominator_payout_count += 1;

				let e = <Event<T>>::Rewarded(nominator.who.clone(), payout);

				Self::deposit_event(e);
			}
		}

		T::RingCurrency::settle(
			&Self::account_id(),
			actual_payout,
			WithdrawReasons::all(),
			ExistenceRequirement::KeepAlive,
		)
		.map_err(|_| <Error<T>>::PayoutIns)?;

		debug_assert!(nominator_payout_count <= T::MaxNominatorRewardedPerValidator::get());
		Ok(Some(T::WeightInfo::payout_stakers_alive_staked(nominator_payout_count)).into())
	}

	/// Update the ledger for a controller.
	///
	/// BE CAREFUL:
	/// 	This will also update the stash lock.
	/// 	DO NOT modify the locks' staking amount outside this function.
	pub fn update_ledger(controller: &AccountId<T>, ledger: &StakingLedgerT<T>) {
		fn update_lock<A, B, C, BN>(stash: &A, active: B, staking_lock: &StakingLock<B, BN>, at: BN)
		where
			B: Copy + AtLeast32BitUnsigned + Zero,
			C: LockableCurrency<A, Balance = B>,
			BN: Copy + PartialOrd,
		{
			if active.is_zero() && staking_lock.unbondings.is_empty() {
				C::remove_lock(STAKING_ID, stash);
			} else {
				C::set_lock(
					STAKING_ID,
					stash,
					active.saturating_add(staking_lock.total_unbond_at(at)),
					WithdrawReasons::all(),
				);
			}
		}

		let StakingLedger {
			stash, active, active_kton, ring_staking_lock, kton_staking_lock, ..
		} = ledger;
		let now = <frame_system::Pallet<T>>::block_number();

		update_lock::<_, _, T::RingCurrency, _>(&stash, *active, ring_staking_lock, now);
		update_lock::<_, _, T::KtonCurrency, _>(&stash, *active_kton, kton_staking_lock, now);

		<Ledger<T>>::insert(controller, ledger);
	}

	/// Update the staking pool, once any account change its bond.
	pub fn update_staking_pool(
		active: RingBalance<T>,
		origin_active: RingBalance<T>,
		active_kton: KtonBalance<T>,
		origin_active_kton: KtonBalance<T>,
	) {
		if active != origin_active {
			<RingPool<T>>::mutate(|pool| {
				if origin_active > active {
					*pool = pool.saturating_sub(origin_active - active);
				} else {
					*pool = pool.saturating_add(active - origin_active);
				}
			});
		}
		if active_kton != origin_active_kton {
			<KtonPool<T>>::mutate(|pool| {
				if origin_active_kton > active_kton {
					*pool = pool.saturating_sub(origin_active_kton - active_kton);
				} else {
					*pool = pool.saturating_add(active_kton - origin_active_kton);
				}
			});
		}
	}

	/// Chill a stash account.
	pub fn chill_stash(stash: &AccountId<T>) {
		let chilled_as_validator = Self::do_remove_validator(stash);
		let chilled_as_nominator = Self::do_remove_nominator(stash);

		if chilled_as_validator || chilled_as_nominator {
			Self::deposit_event(<Event<T>>::Chilled(stash.clone()));
		}
	}

	/// Actually make a payment to a staker. This uses the currency's reward function
	/// to pay the right payee for the given staker account.
	pub fn make_payout(
		stash: &AccountId<T>,
		amount: RingBalance<T>,
	) -> Option<RingPositiveImbalance<T>> {
		let dest = Self::payee(stash);
		match dest {
			RewardDestination::Controller => Self::bonded(stash).and_then(|controller| {
				Some(T::RingCurrency::deposit_creating(&controller, amount))
			}),
			RewardDestination::Stash => T::RingCurrency::deposit_into_existing(stash, amount).ok(),
			RewardDestination::Staked => Self::bonded(stash)
				.and_then(|c| Self::ledger(&c).map(|l| (c, l)))
				.and_then(|(c, mut l)| {
					let r = T::RingCurrency::deposit_into_existing(stash, amount).ok();

					if r.is_some() {
						let origin_active = l.active.clone();
						l.active += amount;

						Self::update_ledger(&c, &l);
						Self::update_staking_pool(
							l.active,
							origin_active,
							Zero::zero(),
							Zero::zero(),
						);
					}

					r
				}),
			RewardDestination::Account(dest_account) =>
				Some(T::RingCurrency::deposit_creating(&dest_account, amount)),
			RewardDestination::None => None,
		}
	}

	/// Plan a new session potentially trigger a new era.
	pub fn new_session(session_index: SessionIndex, is_genesis: bool) -> Option<Vec<AccountId<T>>> {
		if let Some(current_era) = Self::current_era() {
			// Initial era has been set.
			let current_era_start_session_index = Self::eras_start_session_index(current_era)
				.unwrap_or_else(|| {
					frame_support::print("Error: start_session_index must be set for current_era");
					0
				});

			let era_length =
				session_index.checked_sub(current_era_start_session_index).unwrap_or(0); // Must never happen.

			match <ForceEra<T>>::get() {
				// Will be set to `NotForcing` again if a new era has been triggered.
				Forcing::ForceNew => (),
				// Short circuit to `try_trigger_new_era`.
				Forcing::ForceAlways => (),
				// Only go to `try_trigger_new_era` if deadline reached.
				Forcing::NotForcing if era_length >= T::SessionsPerEra::get() => (),
				_ => {
					// Either `Forcing::ForceNone`,
					// or `Forcing::NotForcing if era_length >= T::SessionsPerEra::get()`.
					return None;
				},
			}

			// New era.
			let maybe_new_era_validators = Self::try_trigger_new_era(session_index, is_genesis);
			if maybe_new_era_validators.is_some()
				&& matches!(<ForceEra<T>>::get(), Forcing::ForceNew)
			{
				<ForceEra<T>>::put(Forcing::NotForcing);
			}

			maybe_new_era_validators
		} else {
			// Set initial era.
			log!(debug, "Starting the first era.");
			Self::try_trigger_new_era(session_index, is_genesis)
		}
	}

	/// Start a session potentially starting an era.
	pub fn start_session(start_session: SessionIndex) {
		let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0);
		// This is only `Some` when current era has already progressed to the next era, while the
		// active era is one behind (i.e. in the *last session of the active era*, or *first session
		// of the new current era*, depending on how you look at it).
		if let Some(next_active_era_start_session_index) =
			Self::eras_start_session_index(next_active_era)
		{
			if next_active_era_start_session_index == start_session {
				Self::start_era(start_session);
			} else if next_active_era_start_session_index < start_session {
				// This arm should never happen, but better handle it than to stall the staking
				// pallet.
				frame_support::print("Warning: A session appears to have been skipped.");
				Self::start_era(start_session);
			}
		}

		for (index, disabled) in <OffendingValidators<T>>::get() {
			if disabled {
				T::SessionInterface::disable_validator(index);
			}
		}
	}

	/// End a session potentially ending an era.
	pub fn end_session(session_index: SessionIndex) {
		if let Some(active_era) = Self::active_era() {
			let next_active_era_start_session_index =
				Self::eras_start_session_index(active_era.index + 1).unwrap_or_else(|| {
					frame_support::print(
						"Error: start_session_index must be set for active_era + 1",
					);
					0
				});

			if next_active_era_start_session_index == session_index + 1 {
				Self::end_era(active_era, session_index);
			}
		}
	}

	///
	/// * Increment `active_era.index`,
	/// * reset `active_era.start`,
	/// * update `BondedEras` and apply slashes.
	pub fn start_era(start_session: SessionIndex) {
		let active_era = <ActiveEra<T>>::mutate(|active_era| {
			let new_index = active_era.as_ref().map(|info| info.index + 1).unwrap_or(0);
			*active_era = Some(ActiveEraInfo {
				index: new_index,
				// Set new active era start in next `on_finalize`. To guarantee usage of `Time`
				start: None,
			});
			new_index
		});

		let bonding_duration = T::BondingDurationInEra::get();

		<BondedEras<T>>::mutate(|bonded| {
			bonded.push((active_era, start_session));

			if active_era > bonding_duration {
				let first_kept = active_era - bonding_duration;

				// Prune out everything that's from before the first-kept index.
				let n_to_prune =
					bonded.iter().take_while(|&&(era_idx, _)| era_idx < first_kept).count();

				// Kill slashing metadata.
				for (pruned_era, _) in bonded.drain(..n_to_prune) {
					slashing::clear_era_metadata::<T>(pruned_era);
				}

				if let Some(&(_, first_session)) = bonded.first() {
					T::SessionInterface::prune_historical_up_to(first_session);
				}
			}
		});

		Self::apply_unapplied_slashes(active_era);
	}

	/// Compute payout for era.
	pub fn end_era(active_era: ActiveEraInfo, _session_index: SessionIndex) {
		// Note: active_era_start can be None if end era is called during genesis config.
		if let Some(active_era_start) = active_era.start {
			let now = T::UnixTime::now().as_millis().saturated_into::<TsInMs>();
			let living_time = Self::living_time();
			let era_duration = now - active_era_start;

			let (validator_payout, max_payout) = inflation::compute_total_payout::<T>(
				era_duration,
				Self::living_time(),
				T::Cap::get().saturating_sub(T::RingCurrency::total_issuance()),
				<PayoutFraction<T>>::get(),
			);
			let rest = max_payout.saturating_sub(validator_payout);

			Self::deposit_event(Event::EraPaid(active_era.index, validator_payout, rest));

			<LivingTime<T>>::put(living_time + era_duration);
			// Set ending era reward.
			<ErasValidatorReward<T>>::insert(&active_era.index, validator_payout);
			T::RingCurrency::deposit_creating(&Self::account_id(), validator_payout);
			T::RingRewardRemainder::on_unbalanced(T::RingCurrency::issue(rest));

			// Clear offending validators.
			<OffendingValidators<T>>::kill();
		}
	}

	/// Plan a new era.
	///
	/// * Bump the current era storage (which holds the latest planned era).
	/// * Store start session index for the new planned era.
	/// * Clean old era information.
	/// * Store staking information for the new planned era
	///
	/// Returns the new validator set.
	pub fn trigger_new_era(
		start_session_index: SessionIndex,
		exposures: Vec<(AccountId<T>, ExposureT<T>)>,
	) -> Vec<AccountId<T>> {
		// Increment or set current era.
		let new_planned_era = <CurrentEra<T>>::mutate(|s| {
			*s = Some(s.map(|s| s + 1).unwrap_or(0));
			s.unwrap()
		});
		<ErasStartSessionIndex<T>>::insert(&new_planned_era, &start_session_index);

		// Clean old era information.
		if let Some(old_era) = new_planned_era.checked_sub(Self::history_depth() + 1) {
			Self::clear_era_information(old_era);
		}

		// Set staking information for the new era.
		Self::store_stakers_info(exposures, new_planned_era)
	}

	/// Potentially plan a new era.
	///
	/// Get election result from `T::ElectionProvider`.
	/// In case election result has more than [`MinimumValidatorCount`] validator trigger a new era.
	///
	/// In case a new era is planned, the new validator set is returned.
	fn try_trigger_new_era(
		start_session_index: SessionIndex,
		is_genesis: bool,
	) -> Option<Vec<AccountId<T>>> {
		let election_result = if is_genesis {
			T::GenesisElectionProvider::elect().map_err(|e| {
				log!(warn, "genesis election provider failed due to {:?}", e);

				Self::deposit_event(Event::StakingElectionFailed);
			})
		} else {
			T::ElectionProvider::elect().map_err(|e| {
				log!(warn, "election provider failed due to {:?}", e);

				Self::deposit_event(Event::StakingElectionFailed);
			})
		}
		.ok()?;

		let exposures = Self::collect_exposures(election_result);

		if (exposures.len() as u32) < Self::minimum_validator_count().max(1) {
			// Session will panic if we ever return an empty validator set, thus max(1) ^^.
			match <CurrentEra<T>>::get() {
				Some(current_era) if current_era > 0 => log!(
					warn,
					"chain does not have enough staking candidates to operate for era {:?} ({} \
					elected, minimum is {})",
					<CurrentEra<T>>::get().unwrap_or(0),
					exposures.len(),
					Self::minimum_validator_count(),
				),
				None => {
					// The initial era is allowed to have no exposures.
					// In this case the SessionManager is expected to choose a sensible validator
					// set.
					// TODO: this should be simplified #8911
					<CurrentEra<T>>::put(0);
					<ErasStartSessionIndex<T>>::insert(0, &start_session_index);
				},
				_ => (),
			}

			Self::deposit_event(Event::StakingElectionFailed);

			return None;
		}

		Self::deposit_event(Event::StakersElected);

		Some(Self::trigger_new_era(start_session_index, exposures))
	}

	/// Process the output of the election.
	///
	/// Store staking information for the new planned era
	pub fn store_stakers_info(
		exposures: Vec<(AccountId<T>, ExposureT<T>)>,
		new_planned_era: EraIndex,
	) -> Vec<AccountId<T>> {
		let elected_stashes = exposures.iter().cloned().map(|(x, _)| x).collect::<Vec<_>>();
		// Populate stakers, exposures, and the snapshot of validator prefs.
		let mut total_stake = 0;

		exposures.into_iter().for_each(|(stash, exposure)| {
			total_stake = total_stake.saturating_add(exposure.total_power);

			<ErasStakers<T>>::insert(new_planned_era, &stash, &exposure);

			let mut exposure_clipped = exposure;
			let clipped_max_len = T::MaxNominatorRewardedPerValidator::get() as usize;

			if exposure_clipped.others.len() > clipped_max_len {
				exposure_clipped.others.sort_by(|a, b| a.power.cmp(&b.power).reverse());
				exposure_clipped.others.truncate(clipped_max_len);
			}

			<ErasStakersClipped<T>>::insert(&new_planned_era, &stash, exposure_clipped);
		});

		// Insert current era staking information
		<ErasTotalStake<T>>::insert(&new_planned_era, total_stake);

		// Collect the pref of all winners
		for stash in &elected_stashes {
			let pref = Self::validators(stash);

			<ErasValidatorPrefs<T>>::insert(&new_planned_era, stash, pref);
		}

		if new_planned_era > 0 {
			log!(
				info,
				"new validator set of size {:?} has been processed for era {:?}",
				elected_stashes.len(),
				new_planned_era,
			);
		}

		elected_stashes
	}

	/// Consume a set of [`Supports`] from [`sp_npos_elections`] and collect them into a
	/// [`Exposure`].
	pub fn collect_exposures(
		supports: Supports<AccountId<T>>,
	) -> Vec<(AccountId<T>, ExposureT<T>)> {
		supports
			.into_iter()
			.map(|(validator, support)| {
				// Build `struct exposure` from `support`
				let mut own_ring_balance: RingBalance<T> = Zero::zero();
				let mut own_kton_balance: KtonBalance<T> = Zero::zero();
				let mut own_power = 0;
				let mut total_power = 0;
				let mut others = Vec::with_capacity(support.voters.len());

				support.voters.into_iter().for_each(|(nominator, power_u128)| {
					// `T::TotalPower::get() == 1_000_000_000_u32`, will never overflow or get
					// truncated; qed
					let power = power_u128 as _;
					let origin_power = Self::power_of(&nominator);
					let origin_power_u128 = origin_power as _;

					let (origin_ring_balance, origin_kton_balance) = Self::stake_of(&nominator);
					let ring_balance = if let Ok(ring_balance) =
						helpers_128bit::multiply_by_rational(
							origin_ring_balance.saturated_into(),
							power_u128,
							origin_power_u128,
						) {
						ring_balance.saturated_into()
					} else {
						log!(
							error,
							"[staking] Origin RING: {:?}, Weight: {:?}, Origin Weight: {:?}",
							origin_ring_balance,
							power_u128,
							origin_power_u128
						);
						Zero::zero()
					};
					let kton_balance = if let Ok(kton_balance) =
						helpers_128bit::multiply_by_rational(
							origin_kton_balance.saturated_into(),
							power_u128,
							origin_power_u128,
						) {
						kton_balance.saturated_into()
					} else {
						log!(
							error,
							"[staking] Origin KTON: {:?}, Weight: {:?}, Origin Weight: {:?}",
							origin_kton_balance,
							power_u128,
							origin_power_u128
						);
						Zero::zero()
					};

					if nominator == validator {
						own_ring_balance = own_ring_balance.saturating_add(ring_balance);
						own_kton_balance = own_kton_balance.saturating_add(kton_balance);
						own_power = own_power.saturating_add(power);
					} else {
						others.push(IndividualExposure {
							who: nominator,
							ring_balance,
							kton_balance,
							power,
						});
					}
					total_power = total_power.saturating_add(power);
				});

				let exposure =
					Exposure { own_ring_balance, own_kton_balance, own_power, total_power, others };

				(validator, exposure)
			})
			.collect()
	}

	/// Remove all associated data of a stash account from the staking system.
	///
	/// Assumes storage is upgraded before calling.
	///
	/// This is called:
	/// - after a `withdraw_unbond()` call that frees all of a stash's bonded balance.
	/// - through `reap_stash()` if the balance has fallen to zero (through slashing).
	pub fn kill_stash(stash: &AccountId<T>, num_slashing_spans: u32) -> DispatchResult {
		let controller = <Bonded<T>>::get(stash).ok_or(<Error<T>>::NotStash)?;

		slashing::clear_stash_metadata::<T>(stash, num_slashing_spans)?;

		<Bonded<T>>::remove(stash);
		<Ledger<T>>::remove(&controller);

		<Payee<T>>::remove(stash);

		Self::do_remove_validator(stash);
		Self::do_remove_nominator(stash);

		<frame_system::Pallet<T>>::dec_consumers(stash);

		Ok(())
	}

	/// Clear all era information for given era.
	pub fn clear_era_information(era_index: EraIndex) {
		<ErasStakers<T>>::remove_prefix(era_index, None);
		<ErasStakersClipped<T>>::remove_prefix(era_index, None);
		<ErasValidatorPrefs<T>>::remove_prefix(era_index, None);
		<ErasValidatorReward<T>>::remove(era_index);
		<ErasRewardPoints<T>>::remove(era_index);
		<ErasTotalStake<T>>::remove(era_index);
		<ErasStartSessionIndex<T>>::remove(era_index);
	}

	/// Apply previously-unapplied slashes on the beginning of a new era, after a delay.
	pub fn apply_unapplied_slashes(active_era: EraIndex) {
		let slash_defer_duration = T::SlashDeferDuration::get();
		<Self as Store>::EarliestUnappliedSlash::mutate(|earliest| {
			if let Some(ref mut earliest) = earliest {
				let keep_from = active_era.saturating_sub(slash_defer_duration);
				for era in (*earliest)..keep_from {
					let era_slashes = <Self as Store>::UnappliedSlashes::take(&era);
					for slash in era_slashes {
						slashing::apply_slash::<T>(slash);
					}
				}

				*earliest = (*earliest).max(keep_from)
			}
		})
	}

	/// Add reward points to validators using their stash account ID.
	///
	/// Validators are keyed by stash account ID and must be in the current elected set.
	///
	/// For each element in the iterator the given number of points in u32 is added to the
	/// validator, thus duplicates are handled.
	///
	/// At the end of the era each the total payout will be distributed among validator
	/// relatively to their points.
	///
	/// COMPLEXITY: Complexity is `number_of_validator_to_reward x current_elected_len`.
	/// If you need to reward lots of validator consider using `reward_by_indices`.
	pub fn reward_by_ids(validators_points: impl IntoIterator<Item = (AccountId<T>, u32)>) {
		if let Some(active_era) = Self::active_era() {
			<ErasRewardPoints<T>>::mutate(active_era.index, |era_rewards| {
				for (validator, points) in validators_points.into_iter() {
					*era_rewards.individual.entry(validator).or_default() += points;
					era_rewards.total += points;
				}
			});
		}
	}

	/// Ensures that at the end of the current session there will be a new era.
	pub fn ensure_new_era() {
		match <ForceEra<T>>::get() {
			Forcing::ForceAlways | Forcing::ForceNew => (),
			_ => <ForceEra<T>>::put(Forcing::ForceNew),
		}
	}

	#[cfg(feature = "runtime-benchmarks")]
	pub fn add_era_stakers(
		current_era: EraIndex,
		controller: AccountId<T>,
		exposure: ExposureT<T>,
	) {
		<ErasStakers<T>>::insert(&current_era, &controller, &exposure);
	}

	#[cfg(feature = "runtime-benchmarks")]
	pub fn set_slash_reward_fraction(fraction: Perbill) {
		SlashRewardFraction::put(fraction);
	}

	/// Get all of the voters that are eligible for the npos election.
	///
	/// `maybe_max_len` can imposes a cap on the number of voters returned; First all the validator
	/// are included in no particular order, then remainder is taken from the nominators, as
	/// returned by [`Config::SortedListProvider`].
	///
	/// This will use nominators, and all the validators will inject a self vote.
	///
	/// This function is self-weighing as [`DispatchClass::Mandatory`].
	///
	/// ### Slashing
	///
	/// All nominations that have been submitted before the last non-zero slash of the validator are
	/// auto-chilled, but still count towards the limit imposed by `maybe_max_len`.
	pub fn get_npos_voters(
		maybe_max_len: Option<usize>,
	) -> Vec<(AccountId<T>, VoteWeight, Vec<AccountId<T>>)> {
		let max_allowed_len = {
			let nominator_count = <Nominators<T>>::count() as usize;
			let validator_count = <Validators<T>>::count() as usize;
			let all_voter_count = validator_count.saturating_add(nominator_count);

			maybe_max_len.unwrap_or(all_voter_count).min(all_voter_count)
		};
		let mut all_voters = <Vec<_>>::with_capacity(max_allowed_len);
		// first, grab all validators in no particular order, capped by the maximum allowed length.
		let mut validators_taken = 0u32;

		for (validator, _) in <Validators<T>>::iter().take(max_allowed_len) {
			// Append self vote.
			let self_vote =
				(validator.clone(), Self::weight_of(&validator), vec![validator.clone()]);
			all_voters.push(self_vote);
			validators_taken.saturating_inc();
		}

		// .. and grab whatever we have left from nominators.
		let nominators_quota = (max_allowed_len as u32).saturating_sub(validators_taken);
		let slashing_spans = <SlashingSpans<T>>::iter().collect::<BTreeMap<_, _>>();
		// track the count of nominators added to `all_voters
		let mut nominators_taken = 0u32;
		// track every nominator iterated over, but not necessarily added to `all_voters`
		let mut nominators_seen = 0u32;
		// cache the total-issuance once in this function
		let weight_of = Self::weight_of_fn();
		let mut nominators_iter = T::SortedListProvider::iter();

		while nominators_taken < nominators_quota && nominators_seen < nominators_quota * 2 {
			let nominator = match nominators_iter.next() {
				Some(nominator) => {
					nominators_seen.saturating_inc();
					nominator
				},
				None => break,
			};

			if let Some(Nominations { submitted_in, mut targets, suppressed: _ }) =
				<Nominators<T>>::get(&nominator)
			{
				log!(
					trace,
					"fetched nominator {:?} with weight {:?}",
					nominator,
					weight_of(&nominator)
				);
				targets.retain(|stash| {
					slashing_spans
						.get(stash)
						.map_or(true, |spans| submitted_in >= spans.last_nonzero_slash())
				});

				if !targets.len().is_zero() {
					all_voters.push((nominator.clone(), weight_of(&nominator), targets));
					nominators_taken.saturating_inc();
				}
			} else {
				log!(error, "DEFENSIVE: invalid item in `SortedListProvider`: {:?}", nominator)
			}
		}

		// all_voters should have not re-allocated.
		debug_assert!(all_voters.capacity() == max_allowed_len);

		Self::register_weight(T::WeightInfo::get_npos_voters(
			validators_taken,
			nominators_taken,
			slashing_spans.len() as u32,
		));

		log!(
			info,
			"generated {} npos voters, {} from validators and {} nominators",
			all_voters.len(),
			validators_taken,
			nominators_taken
		);

		all_voters
	}

	/// Get the targets for an upcoming npos election.
	///
	/// This function is self-weighing as [`DispatchClass::Mandatory`].
	pub fn get_npos_targets() -> Vec<AccountId<T>> {
		let mut validator_count = 0u32;
		let targets = <Validators<T>>::iter()
			.map(|(v, _)| {
				validator_count.saturating_inc();

				v
			})
			.collect::<Vec<_>>();

		Self::register_weight(T::WeightInfo::get_npos_targets(validator_count));

		targets
	}

	/// This function will add a nominator to the `Nominators` storage map,
	/// and [`SortedListProvider`].
	///
	/// If the nominator already exists, their nominations will be updated.
	///
	/// NOTE: you must ALWAYS use this function to add nominator or update their targets. Any access
	/// to `Nominators` or `VoterList` outside of this function is almost certainly
	/// wrong.
	pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations<T::AccountId>) {
		if !<Nominators<T>>::contains_key(who) {
			// maybe update sorted list. Error checking is defensive-only - this should never fail.
			if T::SortedListProvider::on_insert(who.clone(), Self::weight_of(who)).is_err() {
				log!(warn, "attempt to insert duplicate nominator ({:#?})", who);
				debug_assert!(false, "attempt to insert duplicate nominator");
			};

			debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
		}

		<Nominators<T>>::insert(who, nominations);
	}

	/// This function will remove a nominator from the `Nominators` storage map,
	/// and [`SortedListProvider`].
	///
	/// Returns true if `who` was removed from `Nominators`, otherwise false.
	///
	/// NOTE: you must ALWAYS use this function to remove a nominator from the system. Any access to
	/// `Nominators` or `VoterList` outside of this function is almost certainly
	/// wrong.
	pub fn do_remove_nominator(who: &T::AccountId) -> bool {
		if <Nominators<T>>::contains_key(who) {
			<Nominators<T>>::remove(who);
			T::SortedListProvider::on_remove(who);
			debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
			debug_assert_eq!(<Nominators<T>>::count(), T::SortedListProvider::count());
			true
		} else {
			false
		}
	}

	/// This function will add a validator to the `Validators` storage map.
	///
	/// If the validator already exists, their preferences will be updated.
	///
	/// NOTE: you must ALWAYS use this function to add a validator to the system. Any access to
	/// `Validators` or `VoterList` outside of this function is almost certainly
	/// wrong.
	pub fn do_add_validator(who: &T::AccountId, prefs: ValidatorPrefs) {
		<Validators<T>>::insert(who, prefs);
	}

	/// This function will remove a validator from the `Validators` storage map.
	///
	/// Returns true if `who` was removed from `Validators`, otherwise false.
	///
	/// NOTE: you must ALWAYS use this function to remove a validator from the system. Any access to
	/// `Validators` or `VoterList` outside of this function is almost certainly
	/// wrong.
	pub fn do_remove_validator(who: &T::AccountId) -> bool {
		if <Validators<T>>::contains_key(who) {
			<Validators<T>>::remove(who);
			true
		} else {
			false
		}
	}

	/// Register some amount of weight directly with the system pallet.
	///
	/// This is always mandatory weight.
	fn register_weight(weight: Weight) {
		<frame_system::Pallet<T>>::register_extra_weight_unchecked(
			weight,
			DispatchClass::Mandatory,
		);
	}
}

impl<T: Config> ElectionDataProvider for Pallet<T> {
	type AccountId = AccountId<T>;
	type BlockNumber = BlockNumberFor<T>;

	const MAXIMUM_VOTES_PER_VOTER: u32 = T::MAX_NOMINATIONS;

	fn desired_targets() -> data_provider::Result<u32> {
		Self::register_weight(T::DbWeight::get().reads(1));

		Ok(Self::validator_count())
	}

	fn voters(
		maybe_max_len: Option<usize>,
	) -> data_provider::Result<Vec<(AccountId<T>, VoteWeight, Vec<AccountId<T>>)>> {
		// This can never fail -- if `maybe_max_len` is `Some(_)` we handle it.
		let voters = Self::get_npos_voters(maybe_max_len);
		debug_assert!(maybe_max_len.map_or(true, |max| voters.len() <= max));

		Ok(voters)
	}

	fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
		let target_count = <Validators<T>>::count();

		// We can't handle this case yet -- return an error.
		if maybe_max_len.map_or(false, |max_len| target_count > max_len as u32) {
			return Err("Target snapshot too big");
		}

		Ok(Self::get_npos_targets())
	}

	fn next_election_prediction(now: BlockNumberFor<T>) -> BlockNumberFor<T> {
		let current_era = Self::current_era().unwrap_or(0);
		let current_session = Self::current_planned_session();
		let current_era_start_session_index =
			Self::eras_start_session_index(current_era).unwrap_or(0);
		let era_progress = current_session
			.saturating_sub(current_era_start_session_index)
			.min(T::SessionsPerEra::get());
		let until_this_session_end = T::NextNewSession::estimate_next_new_session(now)
			.0
			.unwrap_or_default()
			.saturating_sub(now);
		let session_length = T::NextNewSession::average_session_length();
		let sessions_left: BlockNumberFor<T> = match <ForceEra<T>>::get() {
			Forcing::ForceNone => Bounded::max_value(),
			Forcing::ForceNew | Forcing::ForceAlways => Zero::zero(),
			Forcing::NotForcing if era_progress >= T::SessionsPerEra::get() => Zero::zero(),
			Forcing::NotForcing => T::SessionsPerEra::get()
				.saturating_sub(era_progress)
				// One session is computed in this_session_end.
				.saturating_sub(1)
				.into(),
		};

		now.saturating_add(
			until_this_session_end.saturating_add(sessions_left.saturating_mul(session_length)),
		)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn add_voter(voter: T::AccountId, weight: VoteWeight, targets: Vec<T::AccountId>) {
		let stake = <RingBalance<T>>::try_from(weight).unwrap_or_else(|_| {
			panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
		});
		<Bonded<T>>::insert(voter.clone(), voter.clone());
		<Ledger<T>>::insert(
			voter.clone(),
			StakingLedger {
				stash: voter.clone(),
				active: stake,
				ring_staking_lock: StakingLock { staking_amount: stake, ..Default::default() },
				..Default::default()
			},
		);
		Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false });
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn add_target(target: T::AccountId) {
		let stake = <MinValidatorBond<T>>::get() * 100u32.into();
		<Bonded<T>>::insert(target.clone(), target.clone());
		<Ledger<T>>::insert(
			target.clone(),
			StakingLedger {
				stash: target.clone(),
				active: stake,
				ring_staking_lock: StakingLock { staking_amount: stake, ..Default::default() },
				..Default::default()
			},
		);
		Self::do_add_validator(
			&target,
			ValidatorPrefs { commission: Perbill::zero(), blocked: false },
		);
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn clear() {
		<Bonded<T>>::remove_all(None);
		<Ledger<T>>::remove_all(None);
		<Validators<T>>::remove_all();
		<Nominators<T>>::remove_all();

		T::SortedListProvider::unsafe_clear();
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn put_snapshot(
		voters: Vec<(AccountId<T>, VoteWeight, Vec<AccountId<T>>)>,
		targets: Vec<AccountId<T>>,
		target_stake: Option<VoteWeight>,
	) {
		targets.into_iter().for_each(|v| {
			let stake: BalanceOf<T> = target_stake
				.and_then(|w| <BalanceOf<T>>::try_from(w).ok())
				.unwrap_or(<MinNominatorBond<T>>::get() * 100u32.into());
			<Bonded<T>>::insert(v.clone(), v.clone());
			<Ledger<T>>::insert(
				v.clone(),
				StakingLedger {
					stash: v.clone(),
					active: stake,
					total: stake,
					unlocking: vec![],
					claimed_rewards: vec![],
				},
			);
			Self::do_add_validator(
				&v,
				ValidatorPrefs { commission: Perbill::zero(), blocked: false },
			);
		});

		voters.into_iter().for_each(|(v, s, t)| {
			let stake = <BalanceOf<T>>::try_from(s).unwrap_or_else(|_| {
				panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
			});
			<Bonded<T>>::insert(v.clone(), v.clone());
			<Ledger<T>>::insert(
				v.clone(),
				StakingLedger {
					stash: v.clone(),
					active: stake,
					total: stake,
					unlocking: vec![],
					claimed_rewards: vec![],
				},
			);
			Self::do_add_nominator(
				&v,
				Nominations { targets: t, submitted_in: 0, suppressed: false },
			);
		});
	}
}

impl<T: Config> pallet_session::SessionManager<AccountId<T>> for Pallet<T> {
	fn new_session(new_index: SessionIndex) -> Option<Vec<AccountId<T>>> {
		log!(trace, "planning new session {}", new_index);

		<CurrentPlannedSession<T>>::put(new_index);

		Self::new_session(new_index, false)
	}

	fn new_session_genesis(new_index: SessionIndex) -> Option<Vec<AccountId<T>>> {
		log!(trace, "planning new session {} at genesis", new_index);

		<CurrentPlannedSession<T>>::put(new_index);

		Self::new_session(new_index, true)
	}

	fn start_session(start_index: SessionIndex) {
		log!(trace, "starting session {}", start_index);

		Self::start_session(start_index)
	}

	fn end_session(end_index: SessionIndex) {
		log!(trace, "ending session {}", end_index);

		Self::end_session(end_index)
	}
}

impl<T: Config> pallet_session::historical::SessionManager<AccountId<T>, ExposureT<T>>
	for Pallet<T>
{
	fn new_session(new_index: SessionIndex) -> Option<Vec<(AccountId<T>, ExposureT<T>)>> {
		<Self as pallet_session::SessionManager<_>>::new_session(new_index).map(|validators| {
			let current_era = Self::current_era()
				// Must be some as a new era has been created.
				.unwrap_or(0);

			validators
				.into_iter()
				.map(|v| {
					let exposure = Self::eras_stakers(current_era, &v);
					(v, exposure)
				})
				.collect()
		})
	}

	fn new_session_genesis(new_index: SessionIndex) -> Option<Vec<(AccountId<T>, ExposureT<T>)>> {
		<Self as pallet_session::SessionManager<_>>::new_session_genesis(new_index).map(
			|validators| {
				let current_era = Self::current_era()
					// Must be some as a new era has been created.
					.unwrap_or(0);

				validators
					.into_iter()
					.map(|v| {
						let exposure = Self::eras_stakers(current_era, &v);
						(v, exposure)
					})
					.collect()
			},
		)
	}

	fn start_session(start_index: SessionIndex) {
		<Self as pallet_session::SessionManager<_>>::start_session(start_index)
	}

	fn end_session(end_index: SessionIndex) {
		<Self as pallet_session::SessionManager<_>>::end_session(end_index)
	}
}

/// This is intended to be used with `FilterHistoricalOffences`.
impl<T> OnOffenceHandler<AccountId<T>, pallet_session::historical::IdentificationTuple<T>, Weight>
	for Pallet<T>
where
	T: Config
		+ pallet_session::Config<ValidatorId = AccountId<T>>
		+ pallet_session::historical::Config<
			FullIdentification = ExposureT<T>,
			FullIdentificationOf = ExposureOf<T>,
		>,
	T::SessionHandler: pallet_session::SessionHandler<AccountId<T>>,
	T::SessionManager: pallet_session::SessionManager<AccountId<T>>,
	T::ValidatorIdOf: Convert<AccountId<T>, Option<AccountId<T>>>,
{
	fn on_offence(
		offenders: &[OffenceDetails<
			AccountId<T>,
			pallet_session::historical::IdentificationTuple<T>,
		>],
		slash_fraction: &[Perbill],
		slash_session: SessionIndex,
		disable_strategy: DisableStrategy,
	) -> Weight {
		let reward_proportion = <SlashRewardFraction<T>>::get();
		let mut consumed_weight: Weight = 0;
		let mut add_db_reads_writes = |reads, writes| {
			consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
		};

		let active_era = {
			let active_era = Self::active_era();
			add_db_reads_writes(1, 0);
			if active_era.is_none() {
				// This offence need not be re-submitted.
				return consumed_weight;
			}
			active_era.expect("value checked not to be `None`; qed").index
		};
		let active_era_start_session_index = Self::eras_start_session_index(active_era)
			.unwrap_or_else(|| {
				frame_support::print("Error: start_session_index must be set for current_era");
				0
			});
		add_db_reads_writes(1, 0);

		let window_start = active_era.saturating_sub(T::BondingDurationInEra::get());

		// Fast path for active-era report - most likely.
		// `slash_session` cannot be in a future active era. It must be in `active_era` or before.
		let slash_era = if slash_session >= active_era_start_session_index {
			active_era
		} else {
			let eras = <BondedEras<T>>::get();
			add_db_reads_writes(1, 0);

			// Reverse because it's more likely to find reports from recent eras.
			match eras.iter().rev().filter(|&&(_, ref sesh)| sesh <= &slash_session).next() {
				Some(&(ref slash_era, _)) => *slash_era,
				// Before bonding period. defensive - should be filtered out.
				None => return consumed_weight,
			}
		};

		<Self as Store>::EarliestUnappliedSlash::mutate(|earliest| {
			if earliest.is_none() {
				*earliest = Some(active_era)
			}
		});
		add_db_reads_writes(1, 1);

		let slash_defer_duration = T::SlashDeferDuration::get();

		let invulnerables = Self::invulnerables();
		add_db_reads_writes(1, 0);

		for (details, slash_fraction) in offenders.iter().zip(slash_fraction) {
			let (stash, exposure) = &details.offender;

			// Skip if the validator is invulnerable.
			if invulnerables.contains(stash) {
				continue;
			}

			let unapplied = slashing::compute_slash::<T>(slashing::SlashParams {
				stash,
				slash: *slash_fraction,
				exposure,
				slash_era,
				window_start,
				now: active_era,
				reward_proportion,
				disable_strategy,
			});

			if let Some(mut unapplied) = unapplied {
				let nominators_len = unapplied.others.len() as u64;
				let reporters_len = details.reporters.len() as u64;

				{
					let upper_bound = 1 /* Validator/NominatorSlashInEra */ + 2 /* fetch_spans */;
					let rw = upper_bound + nominators_len * upper_bound;
					add_db_reads_writes(rw, rw);
				}
				unapplied.reporters = details.reporters.clone();
				if slash_defer_duration == 0 {
					// Apply right away.
					slashing::apply_slash::<T>(unapplied);
					{
						let slash_cost = (6, 5);
						let reward_cost = (2, 2);
						add_db_reads_writes(
							(1 + nominators_len) * slash_cost.0 + reward_cost.0 * reporters_len,
							(1 + nominators_len) * slash_cost.1 + reward_cost.1 * reporters_len,
						);
					}
				} else {
					// Defer to end of some `slash_defer_duration` from now.
					<Self as Store>::UnappliedSlashes::mutate(active_era, move |for_later| {
						for_later.push(unapplied)
					});
					add_db_reads_writes(1, 1);
				}
			} else {
				add_db_reads_writes(4 /* fetch_spans */, 5 /* kick_out_if_recent */)
			}
		}

		consumed_weight
	}
}

/// Add reward points to block authors:
/// * 20 points to the block producer for producing a (non-uncle) block in the relay chain,
/// * 2 points to the block producer for each reference to a previously unreferenced uncle, and
/// * 1 point to the producer of each referenced uncle block.
impl<T> pallet_authorship::EventHandler<AccountId<T>, BlockNumberFor<T>> for Pallet<T>
where
	T: Config + pallet_authorship::Config + pallet_session::Config,
{
	fn note_author(author: AccountId<T>) {
		Self::reward_by_ids(vec![(author, 20)]);
	}

	fn note_uncle(uncle_author: T::AccountId, _age: T::BlockNumber) {
		// defensive-only: block author must exist.
		if let Some(block_author) = <pallet_authorship::Pallet<T>>::author() {
			Self::reward_by_ids(vec![(block_author, 2), (uncle_author, 1)])
		} else {
			crate::log!(warn, "block author not set, this should never happen");
		}
	}
}

/// Means for interacting with a specialized version of the `session` trait.
///
/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Config`
pub trait SessionInterface<AccountId>: frame_system::Config {
	/// Disable the validator at the given index, returns `false` if the validator was already
	/// disabled or the index is out of bounds.
	fn disable_validator(validator_index: u32) -> bool;
	/// Get the validators from session.
	fn validators() -> Vec<AccountId>;
	/// Prune historical session tries up to but not including the given index.
	fn prune_historical_up_to(up_to: SessionIndex);
}
impl<T: Config> SessionInterface<AccountId<T>> for T
where
	T: pallet_session::Config<ValidatorId = AccountId<T>>,
	T: pallet_session::historical::Config<
		FullIdentification = Exposure<AccountId<T>, RingBalance<T>, KtonBalance<T>>,
		FullIdentificationOf = ExposureOf<T>,
	>,
	T::SessionHandler: pallet_session::SessionHandler<AccountId<T>>,
	T::SessionManager: pallet_session::SessionManager<AccountId<T>>,
	T::ValidatorIdOf: Convert<AccountId<T>, Option<AccountId<T>>>,
{
	fn disable_validator(validator_index: u32) -> bool {
		<pallet_session::Pallet<T>>::disable_index(validator_index)
	}

	fn validators() -> Vec<AccountId<T>> {
		<pallet_session::Pallet<T>>::validators()
	}

	fn prune_historical_up_to(up_to: SessionIndex) {
		<pallet_session::historical::Pallet<T>>::prune_up_to(up_to);
	}
}

/// Filter historical offences out and only allow those from the bonding period.
pub struct FilterHistoricalOffences<T, R> {
	_inner: PhantomData<(T, R)>,
}
impl<T, Reporter, Offender, R, O> ReportOffence<Reporter, Offender, O>
	for FilterHistoricalOffences<Pallet<T>, R>
where
	T: Config,
	R: ReportOffence<Reporter, Offender, O>,
	O: Offence<Offender>,
{
	fn report_offence(reporters: Vec<Reporter>, offence: O) -> Result<(), OffenceError> {
		// Disallow any slashing from before the current bonding period.
		let offence_session = offence.session_index();
		let bonded_eras = <BondedEras<T>>::get();

		if bonded_eras.first().filter(|(_, start)| offence_session >= *start).is_some() {
			R::report_offence(reporters, offence)
		} else {
			<Pallet<T>>::deposit_event(Event::OldSlashingReportDiscarded(offence_session));
			Ok(())
		}
	}

	fn is_known_offence(offenders: &[Offender], time_slot: &O::TimeSlot) -> bool {
		R::is_known_offence(offenders, time_slot)
	}
}