pallet-staking-async 0.11.0

FRAME pallet staking async
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;
use crate::{session_rotation::Eras, slashing};
use pallet_staking_async_rc_client as rc_client;
use sp_runtime::{Perquintill, Rounding};
use sp_staking::StakingInterface;
use std::collections::BTreeMap;

#[test]
fn nominators_also_get_slashed_pro_rata() {
	ExtBuilder::default()
		.validator_count(4)
		.set_status(41, StakerStatus::Validator)
		.build_and_execute(|| {
			let initial_exposure = Staking::eras_stakers(active_era(), &11);
			assert_eq!(
				initial_exposure,
				Exposure {
					total: 1250,
					own: 1000,
					others: vec![IndividualExposure { who: 101, value: 250 }]
				}
			);

			// staked values;
			let nominator_stake = Staking::ledger(101.into()).unwrap().active;
			let nominator_balance = asset::stakeable_balance::<Test>(&101);
			let validator_stake = Staking::ledger(11.into()).unwrap().active;
			let validator_balance = asset::stakeable_balance::<Test>(&11);
			let exposed_stake = initial_exposure.total;
			let exposed_validator = initial_exposure.own;
			let exposed_nominator = initial_exposure.others.first().unwrap().value;

			// register a slash for 11 with 10%.
			add_slash(11);
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::OffenceReported {
					offence_era: 1,
					validator: 11,
					fraction: Perbill::from_percent(10)
				}]
			);

			// roll one block until it is applied
			assert_eq!(SlashDeferDuration::get(), 0);
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
					Event::Slashed { staker: 11, amount: 100 },
					Event::Slashed { staker: 101, amount: 25 }
				]
			);

			// both stakes must have been decreased.
			assert!(Staking::ledger(101.into()).unwrap().active < nominator_stake);
			assert!(Staking::ledger(11.into()).unwrap().active < validator_stake);

			let slash_amount = Perbill::from_percent(10) * exposed_stake;
			let validator_share =
				Perbill::from_rational(exposed_validator, exposed_stake) * slash_amount;
			let nominator_share =
				Perbill::from_rational(exposed_nominator, exposed_stake) * slash_amount;

			// both slash amounts need to be positive for the test to make sense.
			assert!(validator_share > 0);
			assert!(nominator_share > 0);

			// both stakes must have been decreased pro-rata.
			assert_eq!(
				Staking::ledger(101.into()).unwrap().active,
				nominator_stake - nominator_share
			);
			assert_eq!(
				Staking::ledger(11.into()).unwrap().active,
				validator_stake - validator_share
			);
			assert_eq!(
				asset::stakeable_balance::<Test>(&101), // free balance
				nominator_balance - nominator_share,
			);
			assert_eq!(
				asset::stakeable_balance::<Test>(&11), // free balance
				validator_balance - validator_share,
			);
		});
}

#[test]
fn slashing_performed_according_exposure() {
	// This test checks that slashing is performed according the exposure (or more precisely,
	// historical exposure), not the current balance.
	ExtBuilder::default().nominate(false).build_and_execute(|| {
		assert_eq!(Staking::eras_stakers(active_era(), &11).own, 1000);

		// Handle an offence with a historical exposure.
		add_slash_with_percent(11, 50);
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::OffenceReported {
				offence_era: 1,
				validator: 11,
				fraction: Perbill::from_percent(50)
			}]
		);

		// roll one block until it is applied
		assert_eq!(SlashDeferDuration::get(), 0);

		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
				Event::Slashed { staker: 11, amount: 500 },
			]
		);

		// The stash account should be slashed for 250 (50% of 500).
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000 / 2);
	});
}

#[test]
fn offence_doesnt_force_new_era() {
	ExtBuilder::default().build_and_execute(|| {
		assert_eq!(ForceEra::<T>::get(), Forcing::NotForcing);
		add_slash(11);
		assert_eq!(ForceEra::<T>::get(), Forcing::NotForcing);
	});
}

#[test]
fn offence_ensures_new_era_without_clobbering() {
	ExtBuilder::default().build_and_execute(|| {
		assert_ok!(Staking::force_new_era_always(RuntimeOrigin::root()));
		assert_eq!(ForceEra::<T>::get(), Forcing::ForceAlways);

		add_slash(11);

		assert_eq!(ForceEra::<T>::get(), Forcing::ForceAlways);
	});
}

#[test]
fn add_slash_works() {
	ExtBuilder::default().nominate(false).build_and_execute(|| {
		assert_eq_uvec!(session_validators(), vec![11, 21]);

		add_slash(11);
		// roll to apply the slash
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: 1,
					validator: 11,
					fraction: Perbill::from_percent(10)
				},
				Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
				Event::Slashed { staker: 11, amount: 100 },
			]
		);

		// no one is chilled, FYI
		assert!(Validators::<T>::contains_key(11));
	});
}

#[test]
fn only_first_reporter_receive_the_slice() {
	// This test verifies that the first reporter of the offence receive their slice from the
	// slashed amount.
	ExtBuilder::default().nominate(false).build_and_execute(|| {
		// The reporters' reward is calculated from the total exposure.
		assert_eq!(Staking::eras_stakers(active_era(), &11).total, 1000);

		let initial_balance_1 = asset::total_balance::<T>(&1);
		let initial_balance_2 = asset::total_balance::<T>(&2);

		<Staking as rc_client::AHStakingInterface>::on_new_offences(
			session_mock::Session::current_index(),
			vec![rc_client::Offence {
				offender: 11,
				reporters: vec![1, 2],
				slash_fraction: Perbill::from_percent(50),
			}],
		);
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: 1,
					validator: 11,
					fraction: Perbill::from_percent(50)
				},
				Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
				Event::Slashed { staker: 11, amount: 500 },
			]
		);

		let reward = 500 / 10;
		assert_eq!(asset::total_balance::<T>(&1), initial_balance_1 + reward);
		// second reporter got nothing
		assert_eq!(asset::total_balance::<T>(&2), initial_balance_2);
	});
}

#[test]
fn subsequent_reports_pay_out_reward_based_on_net_slash() {
	// This test verifies that the reporters of the offence receive their slice from the slashed
	// amount.
	ExtBuilder::default().nominate(false).build_and_execute(|| {
		// The reporters' reward is calculated from the total exposure.
		let initial_balance = 1000;

		assert_eq!(Staking::eras_stakers(active_era(), &11).total, initial_balance);
		let initial_balance_1 = asset::total_balance::<T>(&1);

		<Staking as rc_client::AHStakingInterface>::on_new_offences(
			session_mock::Session::current_index(),
			vec![rc_client::Offence {
				offender: 11,
				reporters: vec![1],
				slash_fraction: Perbill::from_percent(20),
			}],
		);
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::OffenceReported {
				offence_era: 1,
				validator: 11,
				fraction: Perbill::from_percent(20)
			}]
		);

		Session::roll_next();

		let slash = Perbill::from_percent(20) * initial_balance;
		let reward = SlashRewardFraction::<T>::get() * slash;
		// slash is 1000/5
		assert_eq!(slash, 200);
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
				Event::Slashed { staker: 11, amount: slash },
			]
		);
		// reward is 10% of the slash
		assert_eq!(reward, 20);
		assert_eq!(asset::total_balance::<T>(&1), initial_balance_1 + reward);

		<Staking as rc_client::AHStakingInterface>::on_new_offences(
			session_mock::Session::current_index(),
			vec![rc_client::Offence {
				offender: 11,
				reporters: vec![1],
				slash_fraction: Perbill::from_percent(50),
			}],
		);

		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::OffenceReported {
				offence_era: 1,
				validator: 11,
				fraction: Perbill::from_percent(50)
			}]
		);

		Session::roll_next();

		let prior_slash = slash;
		let prior_reward = reward;

		// since the slash is in the same era, the prior slash is discounted.
		// total slash is 1000/2 = 500, out of which 200 is already slashed. So net slash is 300.
		let slash = Perbill::from_percent(50) * initial_balance - prior_slash;
		assert_eq!(slash, 300);
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
				Event::Slashed { staker: 11, amount: slash },
			]
		);

		// reward is 10% of the slash
		let reward = SlashRewardFraction::<T>::get() * slash;
		assert_eq!(reward, 30);
		assert_eq!(asset::total_balance::<T>(&1), initial_balance_1 + prior_reward + reward);
	});
}

#[test]
fn deferred_slashes_are_deferred() {
	ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| {
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500);

		let exposure = Staking::eras_stakers(active_era(), &11);
		let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value;

		// only 1 page of exposure, so slashes will be applied in one block.
		assert_eq!(Eras::<T>::exposure_page_count(1, &11), 1);

		add_slash(11);
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::OffenceReported {
				offence_era: 1,
				validator: 11,
				fraction: Perbill::from_percent(10)
			}]
		);

		// slash computed in the next block
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 11, page: 0 },]
		);

		// nominations are not removed regardless of the deferring.
		assert_eq!(Nominators::<T>::get(101).unwrap().targets, vec![11, 21]);

		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500);

		Session::roll_until_active_era(2);
		// no slash applied
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::SessionRotated { starting_session: 4, active_era: 1, planned_era: 2 },
				Event::PagedElectionProceeded { page: 0, result: Ok(2) },
				Event::SessionRotated { starting_session: 5, active_era: 1, planned_era: 2 },
				Event::EraPaid { era_index: 1, validator_payout: 7500, remainder: 7500 },
				Event::SessionRotated { starting_session: 6, active_era: 2, planned_era: 2 }
			]
		);

		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500);

		// the slashes for era 1 will start applying in era 3, to end before era 4.
		Session::roll_until_active_era(3);
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::SessionRotated { starting_session: 7, active_era: 2, planned_era: 3 },
				Event::PagedElectionProceeded { page: 0, result: Ok(2) },
				Event::SessionRotated { starting_session: 8, active_era: 2, planned_era: 3 },
				Event::EraPaid { era_index: 2, validator_payout: 7500, remainder: 7500 },
				Event::SessionRotated { starting_session: 9, active_era: 3, planned_era: 3 }
			]
		);

		// Slashes not applied yet. Will apply in the next block after era starts.
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500);

		// trigger slashing by advancing block.
		Session::roll_next();

		assert_eq!(asset::stakeable_balance::<T>(&11), 900);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500 - (nominated_value / 10));

		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::Slashed { staker: 11, amount: 100 },
				Event::Slashed { staker: 101, amount: 25 }
			]
		);
	})
}

#[test]
fn retroactive_deferred_slashes_two_eras_before() {
	ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| {
		assert_eq!(BondingDuration::get(), 3);
		assert_eq!(Nominators::<T>::get(101).unwrap().targets, vec![11, 21]);

		Session::roll_until_active_era(2);
		let _ = staking_events_since_last_call();

		// slash for era 1 detected in era 2, defer for 2, apply in era 3.
		add_slash_in_era(11, 1, Perbill::from_percent(10));
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::OffenceReported {
				offence_era: 1,
				validator: 11,
				fraction: Perbill::from_percent(10)
			}]
		);

		// computed in next block, but not applied
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 11, page: 0 }]
		);

		Session::roll_until_active_era(3);
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::SessionRotated { starting_session: 7, active_era: 2, planned_era: 3 },
				Event::PagedElectionProceeded { page: 0, result: Ok(2) },
				Event::SessionRotated { starting_session: 8, active_era: 2, planned_era: 3 },
				Event::EraPaid { era_index: 2, validator_payout: 7500, remainder: 7500 },
				Event::SessionRotated { starting_session: 9, active_era: 3, planned_era: 3 }
			]
		);

		// Slashes not applied yet. Will apply in the next block after era starts.
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::Slashed { staker: 11, amount: 100 },
				Event::Slashed { staker: 101, amount: 25 }
			]
		);
	})
}

#[test]
fn retroactive_deferred_slashes_one_before() {
	ExtBuilder::default()
		.slash_defer_duration(2)
		.nominate(false)
		.build_and_execute(|| {
			assert_eq!(BondingDuration::get(), 3);

			// unbond at slash era.
			Session::roll_until_active_era(2);

			assert_ok!(Staking::chill(RuntimeOrigin::signed(11)));
			assert_ok!(Staking::unbond(RuntimeOrigin::signed(11), 100));

			Session::roll_until_active_era(3);
			// ignore all events thus far
			let _ = staking_events_since_last_call();

			add_slash_in_era(11, 2, Perbill::from_percent(10));
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::OffenceReported {
					offence_era: 2,
					validator: 11,
					fraction: Perbill::from_percent(10)
				}]
			);

			// computed in next block, but not applied
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::SlashComputed { offence_era: 2, slash_era: 4, offender: 11, page: 0 }]
			);

			Session::roll_until_active_era(4);
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::SessionRotated { starting_session: 10, active_era: 3, planned_era: 4 },
					Event::PagedElectionProceeded { page: 0, result: Ok(2) },
					Event::SessionRotated { starting_session: 11, active_era: 3, planned_era: 4 },
					Event::EraPaid { era_index: 3, validator_payout: 7500, remainder: 7500 },
					Event::SessionRotated { starting_session: 12, active_era: 4, planned_era: 4 }
				]
			);

			// no slash applied yet
			assert_eq!(Staking::ledger(11.into()).unwrap().total, 1000);

			// slash happens at next blocks.
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::Slashed { staker: 11, amount: 100 }]
			);

			// their ledger has already been slashed.
			assert_eq!(Staking::ledger(11.into()).unwrap().total, 900);
			assert_ok!(Staking::unbond(RuntimeOrigin::signed(11), 1000));
			assert_eq!(Staking::ledger(11.into()).unwrap().total, 900);
		})
}

#[test]
fn dont_slash_if_fraction_is_zero() {
	// Don't slash if the fraction is zero.
	ExtBuilder::default().nominate(false).build_and_execute(|| {
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);

		add_slash_with_percent(11, 0);
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::OffenceReported { offence_era: 1, validator: 11, fraction: Zero::zero() }]
		);

		// The validator hasn't been slashed. The new era is not forced.
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		assert_eq!(ForceEra::<T>::get(), Forcing::NotForcing);
	});
}

#[test]
fn only_slash_validator_for_max_in_era() {
	// multiple slashes within one era are only applied if it is more than any previous slash in the
	// same era.
	ExtBuilder::default().nominate(false).build_and_execute(|| {
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);

		add_slash_with_percent(11, 50);
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: 1,
					validator: 11,
					fraction: Perbill::from_percent(50)
				},
				Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
				Event::Slashed { staker: 11, amount: 500 }
			]
		);

		// The validator has been slashed and has been force-chilled.
		assert_eq!(asset::stakeable_balance::<T>(&11), 500);

		add_slash_with_percent(11, 25);
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::OffenceReported {
				offence_era: 1,
				validator: 11,
				fraction: Perbill::from_percent(25)
			},]
		);

		// The validator has not been slashed additionally.
		assert_eq!(asset::stakeable_balance::<T>(&11), 500);

		// now slash for more than 50
		add_slash_with_percent(11, 60);
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: 1,
					validator: 11,
					fraction: Perbill::from_percent(60)
				},
				Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
				Event::Slashed { staker: 11, amount: 100 }
			]
		);

		// The validator got slashed 10% more.
		assert_eq!(asset::stakeable_balance::<T>(&11), 400);
	})
}

#[test]
fn really_old_offences_are_ignored() {
	ExtBuilder::default()
		.slash_defer_duration(27)
		.bonding_duration(28)
		.build_and_execute(|| {
			Session::roll_until_active_era(100);

			let expected_oldest_reportable_offence = active_era() - (SlashDeferDuration::get() - 1);

			assert_eq!(expected_oldest_reportable_offence, 74);

			// clear staking events until now
			staking_events_since_last_call();

			// WHEN: reporting offence for era 72 and 73, which are too old.
			add_slash_in_era(11, 72, Perbill::from_percent(10));
			add_slash_in_era(21, 73, Perbill::from_percent(10));

			// THEN: offence is ignored.
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::OffenceTooOld {
						offence_era: 72,
						validator: 11,
						fraction: Perbill::from_percent(10)
					},
					Event::OffenceTooOld {
						offence_era: 73,
						validator: 21,
						fraction: Perbill::from_percent(10)
					},
				]
			);

			// also check that the ignored offences are not stored anywhere
			assert!(OffenceQueue::<Test>::iter_prefix(72).next().is_none());
			assert!(OffenceQueue::<Test>::iter_prefix(73).next().is_none());
			assert!(!OffenceQueueEras::<Test>::get().unwrap_or_default().contains(&72));
			assert!(!OffenceQueueEras::<Test>::get().unwrap_or_default().contains(&73));

			// WHEN: reporting offence for era 74.
			add_slash_in_era(11, 74, Perbill::from_percent(10));

			// THEN: offence is reported.
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::OffenceReported {
					offence_era: 74,
					validator: 11,
					fraction: Perbill::from_percent(10)
				}]
			);

			// AND: computed in the next block.
			Session::roll_next();

			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::SlashComputed {
					offence_era: 74,
					slash_era: 101,
					offender: 11,
					page: 0
				},]
			);

			// Slash is applied at the start of the next era.
			Session::roll_until_active_era(101);
			// clear staking events until now
			staking_events_since_last_call();

			// this should apply the slash.
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::Slashed { staker: 11, amount: 100 },
					// Nominator 101 is exposed to 11, so they are slashed too.
					Event::Slashed { staker: 101, amount: 25 }
				]
			);
		});
}

#[test]
fn nominator_is_slashed_by_max_for_validator_in_era() {
	ExtBuilder::default().build_and_execute(|| {
		Session::roll_until_active_era(3);

		// Validators 11 and 21, Nominator 101 exposed to both.
		let validator_one = 11;
		let validator_two = 21;
		let nominator = 101;

		assert_eq!(asset::stakeable_balance::<T>(&validator_one), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&validator_two), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&nominator), 500);
		assert_eq!(Staking::slashable_balance_of(&validator_two), 1000);

		let exposure_v1 = Staking::eras_stakers(active_era(), &11);
		let exposure_v2 = Staking::eras_stakers(active_era(), &21);
		let nominated_value_v1 = exposure_v1.others.iter().find(|o| o.who == 101).unwrap().value;
		let nominated_value_v2 = exposure_v2.others.iter().find(|o| o.who == 101).unwrap().value;

		// clear staking events until now
		staking_events_since_last_call();

		// First slash
		let slash_era = 2;
		add_slash_in_era(validator_one, slash_era, Perbill::from_percent(10));
		Session::roll_next();

		let slash_v1_amount = Perbill::from_percent(10) * 1000u128;
		assert_eq!(slash_v1_amount, 100);
		let first_slash_nominator_amount = Perbill::from_percent(10) * nominated_value_v1;
		assert_eq!(first_slash_nominator_amount, 25);

		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: slash_era,
					validator: validator_one,
					fraction: Perbill::from_percent(10)
				},
				Event::SlashComputed {
					offence_era: slash_era,
					slash_era,
					offender: validator_one,
					page: 0
				},
				Event::Slashed { staker: validator_one, amount: slash_v1_amount },
				Event::Slashed { staker: nominator, amount: first_slash_nominator_amount }
			]
		);

		assert_eq!(asset::stakeable_balance::<T>(&validator_one), 1000 - slash_v1_amount);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500 - first_slash_nominator_amount);

		// Second slash: higher value, same era.
		add_slash_in_era(validator_two, slash_era, Perbill::from_percent(30));
		Session::roll_next();

		let slash_v2_amount = Perbill::from_percent(30) * 1000u128;
		assert_eq!(slash_v2_amount, 300);
		// full nominator value is slashed, even though nominator was already slashed in this era.
		let second_slash_nominator_amount = Perbill::from_percent(30) * nominated_value_v2;
		assert_eq!(second_slash_nominator_amount, 75);

		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: slash_era,
					validator: validator_two,
					fraction: Perbill::from_percent(30)
				},
				Event::SlashComputed {
					offence_era: slash_era,
					slash_era,
					offender: validator_two,
					page: 0
				},
				Event::Slashed { staker: validator_two, amount: slash_v2_amount },
				Event::Slashed { staker: nominator, amount: second_slash_nominator_amount }
			]
		);

		// 11 was not further slashed, but 21 and 101 were.
		assert_eq!(asset::stakeable_balance::<T>(&validator_one), 900);
		let v2_stakeable = asset::stakeable_balance::<T>(&validator_two);
		assert_eq!(v2_stakeable, 1000 - slash_v2_amount);
		// 101 is slashed twice.
		let nominator_slashable_balance = Staking::slashable_balance_of(&101);
		assert_eq!(
			nominator_slashable_balance,
			500 - first_slash_nominator_amount - second_slash_nominator_amount
		);

		// Third slash: in same era and on same validator as first, higher in-era value, but lower
		// slash value than slash 2.
		add_slash_in_era(validator_one, slash_era, Perbill::from_percent(20));
		Session::roll_next();

		// the slash perbill delta is (first: 20 - second: 10) = 10% for v1
		let third_slash_nominator_amount = Perbill::from_percent(10) * nominated_value_v1;
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: slash_era,
					validator: validator_one,
					fraction: Perbill::from_percent(20),
				},
				Event::SlashComputed {
					offence_era: slash_era,
					slash_era,
					offender: validator_one,
					page: 0
				},
				Event::Slashed {
					staker: validator_one,
					amount: Perbill::from_percent(10) * 1000u128, // the slash perbill delta is 10%
				},
				Event::Slashed {
					staker: nominator,
					// the slash perbill delta is 10% for v1
					amount: third_slash_nominator_amount,
				},
			]
		);

		// 11 and 101 was further slashed, but 21 was not.
		assert_eq!(
			asset::stakeable_balance::<T>(&validator_one),
			1000 - slash_v1_amount - (Perbill::from_percent(10) * 1000u128)
		);
		assert_eq!(
			asset::stakeable_balance::<T>(&nominator),
			500 - first_slash_nominator_amount -
				second_slash_nominator_amount -
				third_slash_nominator_amount
		);
		assert_eq!(asset::stakeable_balance::<T>(&21), v2_stakeable);
	});
}

#[test]
fn fully_slashed_account_can_be_reaped() {
	// ensures that `SlashingSpans` and `SpanSlash` of an account is removed after reaping.
	ExtBuilder::default()
		.existential_deposit(2)
		.balance_factor(2)
		.build_and_execute(|| {
			// Given a bonded account.
			assert_eq!(asset::stakeable_balance::<T>(&11), 2000);

			// When slashed.
			add_slash_with_percent(11, 10);
			Session::roll_next();

			// Then the account's balance is reduced.
			assert_eq!(asset::stakeable_balance::<T>(&11), 2000 - 200);

			// When fully slashed.
			add_slash_with_percent(11, 100);
			Session::roll_next();

			// Then the account's balance is reduced to 0.
			assert_eq!(asset::stakeable_balance::<T>(&11), 0);
			// Non staked balance is not touched.
			assert_eq!(asset::total_balance::<T>(&11), ExistentialDeposit::get());

			// And the account can be reaped.
			assert_ok!(Staking::reap_stash(RuntimeOrigin::signed(20), 11, 0));
		})
}

#[test]
fn garbage_collection_on_window_pruning() {
	// ensures that `ValidatorSlashInEra` are cleared after
	// `BondingDuration`.
	ExtBuilder::default().build_and_execute(|| {
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		let now = active_era();

		let exposure = Staking::eras_stakers(now, &11);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500);
		let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value;

		add_slash(11);
		Session::roll_next();

		assert_eq!(asset::stakeable_balance::<T>(&11), 900);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500 - (nominated_value / 10));

		assert!(ValidatorSlashInEra::<T>::get(&now, &11).is_some());

		for era in (0..(HistoryDepth::get() + 1)).map(|offset| offset + now + 1) {
			assert!(ValidatorSlashInEra::<T>::get(&now, &11).is_some());
			Session::roll_until_active_era(era);
		}

		// After HistoryDepth + 1 eras, lazy pruning is triggered.
		// We need to manually call prune_era_step to actually remove the data.
		let prune_era = now;
		while EraPruningState::<T>::get(prune_era).is_some() {
			assert_ok!(Staking::prune_era_step(RuntimeOrigin::signed(10), prune_era));
		}

		assert!(ValidatorSlashInEra::<T>::get(&now, &11).is_none());
	})
}

#[test]
fn staker_cannot_bail_deferred_slash() {
	// as long as SlashDeferDuration is less than BondingDuration, this should not be possible.
	ExtBuilder::default()
		.slash_defer_duration(2)
		.bonding_duration(3)
		.build_and_execute(|| {
			assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
			assert_eq!(asset::stakeable_balance::<T>(&101), 500);

			add_slash(11);
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::OffenceReported {
						offence_era: 1,
						validator: 11,
						fraction: Perbill::from_percent(10)
					},
					Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 11, page: 0 }
				]
			);

			// now we chill
			assert_ok!(Staking::chill(RuntimeOrigin::signed(101)));
			assert_ok!(Staking::unbond(RuntimeOrigin::signed(101), 500));

			assert_eq!(CurrentEra::<T>::get().unwrap(), 1);
			assert_eq!(active_era(), 1);

			assert_eq!(
				Ledger::<T>::get(101).unwrap(),
				StakingLedgerInspect {
					active: 0,
					total: 500,
					stash: 101,
					unlocking: bounded_vec![UnlockChunk { era: 4u32, value: 500 }],
				}
			);

			// no slash yet.
			assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
			assert_eq!(asset::stakeable_balance::<T>(&101), 500);

			// no slash yet.
			Session::roll_until_active_era(2);
			assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
			assert_eq!(asset::stakeable_balance::<T>(&101), 500);

			// no slash yet.
			Session::roll_until_active_era(3);
			let _ = staking_events_since_last_call();
			assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
			assert_eq!(asset::stakeable_balance::<T>(&101), 500);
			assert_eq!(CurrentEra::<T>::get().unwrap(), 3);
			assert_eq!(active_era(), 3);

			// and cannot yet unbond:
			assert_storage_noop!(assert!(Staking::withdraw_unbonded(
				RuntimeOrigin::signed(101),
				0
			)
			.is_ok()));

			// first block of era 3, slashes are applied.
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::Slashed { staker: 11, amount: 100 },
					Event::Slashed { staker: 101, amount: 25 }
				]
			);

			assert_eq!(asset::stakeable_balance::<T>(&11), 900);
			assert_eq!(asset::stakeable_balance::<T>(&101), 500 - 25);

			// and the leftover of the funds can now be unbonded.
		})
}

#[test]
fn remove_deferred() {
	ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| {
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500);

		// deferred to start of era 3.
		add_slash(11);
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: 1,
					validator: 11,
					fraction: Perbill::from_percent(10)
				},
				Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 11, page: 0 }
			]
		);

		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
		assert_eq!(asset::stakeable_balance::<T>(&101), 500);

		Session::roll_until_active_era(2);
		let _ = staking_events_since_last_call();
		// reported later, but deferred to start of era 3 as well.
		add_slash_in_era(11, 1, Perbill::from_percent(15));
		Session::roll_next();
		assert_eq!(
			staking_events_since_last_call(),
			vec![
				Event::OffenceReported {
					offence_era: 1,
					validator: 11,
					fraction: Perbill::from_percent(15)
				},
				Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 11, page: 0 }
			]
		);

		assert_eq!(
			UnappliedSlashes::<T>::iter_prefix(&3).collect::<Vec<_>>(),
			vec![
				(
					(11, Perbill::from_percent(10), 0),
					UnappliedSlash {
						validator: 11,
						own: 100,
						others: bounded_vec![(101, 25)],
						reporter: None,
						// 10% of the slash
						payout: (100 + 25) / 10
					}
				),
				(
					(11, Perbill::from_percent(15), 0),
					UnappliedSlash {
						validator: 11,
						own: 50,
						others: bounded_vec![(101, 12)],
						reporter: None,
						// 10% of the slash
						payout: (50 + 12) / 10
					}
				),
			]
		);

		// fails if empty
		assert_noop!(
			Staking::cancel_deferred_slash(RuntimeOrigin::root(), 3, vec![]),
			Error::<T>::EmptyTargets
		);

		// cancel the slash with 12% (which covers the 10% slash but not the 15% slash)
		assert_ok!(Staking::cancel_deferred_slash(
			RuntimeOrigin::root(),
			3,
			vec![(11, Perbill::from_percent(12))],
		));

		// validator 11 slash is set to be cancelled for era 3 with upto 12% cancellation.
		assert_eq!(CancelledSlashes::<T>::get(&3), vec![(11, Perbill::from_percent(12))]);

		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::SlashCancelled { slash_era: 3, validator: 11 }]
		);

		// roll to the slashing era.
		Session::roll_until_active_era(3);
		// slash still exists in unapplied.
		assert_eq!(UnappliedSlashes::<T>::iter_prefix(&3).count(), 2);

		// clear events from session rotation
		let _ = staking_events_since_last_call();

		Session::roll_next();
		// first slash (10%) is cancelled, no events
		assert_eq!(staking_events_since_last_call(), vec![]);
		// one slash processed, one more to go
		assert_eq!(UnappliedSlashes::<T>::iter_prefix(&3).count(), 1);

		Session::roll_next();
		// second slash (15%) is NOT cancelled, so it gets applied
		let events = staking_events_since_last_call();
		assert_eq!(events.len(), 2);
		// The 15% slash already has computed amounts in the UnappliedSlash
		// Based on the test setup, it has own: 50, others: [(101, 12)]
		assert_eq!(events[0], Event::Slashed { staker: 11, amount: 50 });
		assert_eq!(events[1], Event::Slashed { staker: 101, amount: 12 });

		// check balances after 15% slash
		assert_eq!(asset::stakeable_balance::<T>(&11), 950);
		assert_eq!(asset::stakeable_balance::<T>(&101), 488);

		// all unapplied slashes should have been removed
		assert_eq!(UnappliedSlashes::<T>::iter_prefix(&3).count(), 0);
		// cancelled slashes should have been cleared after all era slashes are applied.
		assert_eq!(CancelledSlashes::<T>::get(&3), vec![]);
	})
}

#[test]
fn remove_multi_deferred() {
	ExtBuilder::default()
		.slash_defer_duration(2)
		.validator_count(4)
		.set_status(41, StakerStatus::Validator)
		.set_status(51, StakerStatus::Validator)
		.build_and_execute(|| {
			assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
			assert_eq!(asset::stakeable_balance::<T>(&101), 500);

			add_slash_with_percent(11, 10);
			add_slash_with_percent(21, 10);
			add_slash_with_percent(41, 25);
			Session::roll_next();
			Session::roll_next();
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::OffenceReported {
						offence_era: 1,
						validator: 11,
						fraction: Perbill::from_percent(10)
					},
					Event::OffenceReported {
						offence_era: 1,
						validator: 21,
						fraction: Perbill::from_percent(10)
					},
					Event::OffenceReported {
						offence_era: 1,
						validator: 41,
						fraction: Perbill::from_percent(25)
					},
					Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 41, page: 0 },
					Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 21, page: 0 },
					Event::SlashComputed { offence_era: 1, slash_era: 3, offender: 11, page: 0 },
				]
			);

			// there are 3 slashes to be applied in era 3.
			assert_eq!(UnappliedSlashes::<T>::iter_prefix(&3).count(), 3);

			// lets cancel 2 of them with their respective slash percentages.
			assert_ok!(Staking::cancel_deferred_slash(
				RuntimeOrigin::root(),
				3,
				vec![(11, Perbill::from_percent(10)), (21, Perbill::from_percent(10))]
			));

			// check cancelled slashes are stored correctly
			let cancelled = CancelledSlashes::<T>::get(&3);
			assert_eq!(cancelled.len(), 2);
			assert!(cancelled.contains(&(11, Perbill::from_percent(10))));
			assert!(cancelled.contains(&(21, Perbill::from_percent(10))));

			let slashes = UnappliedSlashes::<T>::iter_prefix(&3).collect::<Vec<_>>();
			assert_eq!(slashes.len(), 3);

			// go to slash era.
			Session::roll_until_active_era(3);
			let _ = staking_events_since_last_call();

			// Process all slashes - they are processed one per block
			let mut slash_events = vec![];
			for _ in 0..3 {
				Session::roll_next();
				let events = staking_events_since_last_call();
				for event in events {
					if let Event::Slashed { .. } = event {
						slash_events.push(event);
					}
				}
			}

			// Only validator 41 should have been slashed
			assert_eq!(slash_events.len(), 1);
			// Validator 41's exposure is 4000, with 25% slash = 1000
			assert_eq!(slash_events[0], Event::Slashed { staker: 41, amount: 1000 });

			// all unapplied slashes are cleared
			assert_eq!(UnappliedSlashes::<T>::iter_prefix(&3).count(), 0);

			// also the cancelled slashes are removed since after this era they are no longer
			// needed.
			assert_eq!(CancelledSlashes::<T>::get(&3), vec![]);
		})
}

#[test]
fn cancel_all_slashes_with_100_percent() {
	// This demonstrates that when a validator has multiple slash entries in the same era,
	// governance can cancel them all with a 100% cancellation.
	ExtBuilder::default()
		.validator_count(4)
		.slash_defer_duration(2)
		.build_and_execute(|| {
			// our validator
			assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
			// nominator exposed to our validator
			assert_eq!(asset::stakeable_balance::<T>(&101), 500);

			// Check current era
			assert_eq!(active_era(), 1);

			// Add 10 slashes in era 1
			for i in 1..=10 {
				add_slash_with_percent(11, i * 5);
				// Process the offence
				Session::roll_next();
			}

			// Collect all events
			let events = staking_events_since_last_call();

			// Count reported and computed events
			let reported_count =
				events.iter().filter(|e| matches!(e, Event::OffenceReported { .. })).count();
			let computed_count =
				events.iter().filter(|e| matches!(e, Event::SlashComputed { .. })).count();

			// Verify all 10 offences were reported and computed
			assert_eq!(reported_count, 10);
			assert_eq!(computed_count, 10);

			// With defer duration 2, slashes from era 1 will be applied in era 3
			// All 10 slash entries should exist
			assert_eq!(UnappliedSlashes::<T>::iter_prefix(&3).count(), 10);

			// Governance cancels all slashes for validator 11 by setting 100% cancellation
			assert_ok!(Staking::cancel_deferred_slash(
				RuntimeOrigin::root(),
				3,
				vec![(11, Perbill::from_percent(100))],
			));

			// Verify the cancellation event
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::SlashCancelled { slash_era: 3, validator: 11 }]
			);

			// Verify CancelledSlashes storage contains our cancellation
			let cancelled = CancelledSlashes::<T>::get(&3);
			assert_eq!(cancelled.len(), 1);
			assert_eq!(cancelled[0], (11, Perbill::from_percent(100)));

			// Roll to the slash era
			Session::roll_until_active_era(3);
			// clear staking events
			let _ = staking_events_since_last_call();

			// Process all 10 slashes - they are processed one per block
			for _ in 0..10 {
				Session::roll_next();

				// Verify no slash was applied
				let events = staking_events_since_last_call();
				let slash_events: Vec<_> =
					events.iter().filter(|e| matches!(e, Event::Slashed { .. })).collect();
				assert_eq!(slash_events.len(), 0);
			}

			// Verify balances remain unchanged
			assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
			assert_eq!(asset::stakeable_balance::<T>(&101), 500);

			// Verify all storages are cleaned up
			assert_eq!(UnappliedSlashes::<T>::iter_prefix(&3).count(), 0);
			assert_eq!(CancelledSlashes::<T>::get(&3), vec![]);
		})
}

#[test]
fn apply_slash_rejects_cancelled_slashes() {
	ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| {
		// validator 11 has initial balance and is bonded
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);

		// Add a slash for validator 11 in era 1 (will be deferred to era 3)
		add_slash(11);
		Session::roll_next();
		let _ = staking_events_since_last_call();

		// Check current era
		assert_eq!(active_era(), 1);

		// Verify the slash is scheduled for era 3
		let slash_era = 3;
		let slash_key = (11, Perbill::from_percent(10), 0);
		assert!(UnappliedSlashes::<T>::contains_key(&slash_era, &slash_key));

		// Governance cancels this slash
		assert_ok!(Staking::cancel_deferred_slash(
			RuntimeOrigin::root(),
			slash_era,
			vec![(11, Perbill::from_percent(10))],
		));

		// Verify the cancellation event was emitted
		assert_eq!(
			staking_events_since_last_call(),
			vec![Event::SlashCancelled { slash_era, validator: 11 }]
		);

		// Verify the slash is cancelled
		let cancelled = CancelledSlashes::<T>::get(&slash_era);
		assert_eq!(cancelled, vec![(11, Perbill::from_percent(10))]);

		// Move to era 3 when the slash would be applied
		Session::roll_until_active_era(3);

		// Try to manually apply the cancelled slash - this should fail
		assert_noop!(
			Staking::apply_slash(RuntimeOrigin::signed(1), slash_era, slash_key),
			Error::<T>::CancelledSlash
		);

		// Verify the slash is still in UnappliedSlashes
		assert!(UnappliedSlashes::<T>::contains_key(&slash_era, &slash_key));

		// Verify no actual slash was applied (balance remains unchanged)
		assert_eq!(asset::stakeable_balance::<T>(&11), 1000);
	})
}

#[test]
fn proportional_slash_stop_slashing_if_remaining_zero() {
	ExtBuilder::default().nominate(true).build_and_execute(|| {
		let c = |era, value| UnlockChunk::<Balance> { era, value };

		// we have some chunks, but they are not affected.
		let unlocking = bounded_vec![c(1, 10), c(2, 10)];

		// Given
		let mut ledger = StakingLedger::<T>::new(123, 20);
		ledger.total = 40;
		ledger.unlocking = unlocking;

		assert_eq!(BondingDuration::get(), 3);

		// should not slash more than the amount requested, by accidentally slashing the first
		// chunk.
		assert_eq!(ledger.slash(18, 1, 0), 18);
	});
}

#[test]
fn proportional_ledger_slash_works() {
	ExtBuilder::default().nominate(true).build_and_execute(|| {
		let c = |era, value| UnlockChunk::<Balance> { era, value };
		// Given
		let mut ledger = StakingLedger::<T>::new(123, 10);
		assert_eq!(BondingDuration::get(), 3);

		// When we slash a ledger with no unlocking chunks
		assert_eq!(ledger.slash(5, 1, 0), 5);
		// Then
		assert_eq!(ledger.total, 5);
		assert_eq!(ledger.active, 5);
		assert_eq!(LedgerSlashPerEra::get().0, 5);
		assert_eq!(LedgerSlashPerEra::get().1, Default::default());

		// When we slash a ledger with no unlocking chunks and the slash amount is greater then the
		// total
		assert_eq!(ledger.slash(11, 1, 0), 5);
		// Then
		assert_eq!(ledger.total, 0);
		assert_eq!(ledger.active, 0);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(LedgerSlashPerEra::get().1, Default::default());

		// Given
		ledger.unlocking = bounded_vec![c(4, 10), c(5, 10)];
		ledger.total = 2 * 10;
		ledger.active = 0;
		// When all the chunks overlap with the slash eras
		assert_eq!(ledger.slash(20, 0, 0), 20);
		// Then
		assert_eq!(ledger.unlocking, vec![]);
		assert_eq!(ledger.total, 0);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(LedgerSlashPerEra::get().1, BTreeMap::from([(4, 0), (5, 0)]));

		// Given
		ledger.unlocking = bounded_vec![c(4, 100), c(5, 100), c(6, 100), c(7, 100)];
		ledger.total = 4 * 100;
		ledger.active = 0;
		// When the first 2 chunks don't overlap with the affected range of unlock eras.
		assert_eq!(ledger.slash(140, 0, 3), 140);
		// Then
		assert_eq!(ledger.unlocking, vec![c(4, 100), c(5, 100), c(6, 30), c(7, 30)]);
		assert_eq!(ledger.total, 4 * 100 - 140);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(LedgerSlashPerEra::get().1, BTreeMap::from([(6, 30), (7, 30)]));

		// Given
		ledger.unlocking = bounded_vec![c(4, 100), c(5, 100), c(6, 100), c(7, 100)];
		ledger.total = 4 * 100;
		ledger.active = 0;
		// When the first 2 chunks don't overlap with the affected range of unlock eras.
		assert_eq!(ledger.slash(15, 0, 3), 15);
		// Then
		assert_eq!(ledger.unlocking, vec![c(4, 100), c(5, 100), c(6, 100 - 8), c(7, 100 - 7)]);
		assert_eq!(ledger.total, 4 * 100 - 15);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(LedgerSlashPerEra::get().1, BTreeMap::from([(6, 92), (7, 93)]));

		// Given
		ledger.unlocking = bounded_vec![c(4, 40), c(5, 100), c(6, 10), c(7, 250)];
		ledger.active = 500;
		// 900
		ledger.total = 40 + 10 + 100 + 250 + 500;
		// When we have a partial slash that touches all chunks
		assert_eq!(ledger.slash(900 / 2, 0, 0), 450);
		// Then
		assert_eq!(ledger.active, 500 / 2);
		assert_eq!(
			ledger.unlocking,
			vec![c(4, 40 / 2), c(5, 100 / 2), c(6, 10 / 2), c(7, 250 / 2)]
		);
		assert_eq!(ledger.total, 900 / 2);
		assert_eq!(LedgerSlashPerEra::get().0, 500 / 2);
		assert_eq!(
			LedgerSlashPerEra::get().1,
			BTreeMap::from([(4, 40 / 2), (5, 100 / 2), (6, 10 / 2), (7, 250 / 2)])
		);

		// slash 1/4th with not chunk.
		ledger.unlocking = bounded_vec![];
		ledger.active = 500;
		ledger.total = 500;
		// When we have a partial slash that touches all chunks
		assert_eq!(ledger.slash(500 / 4, 0, 0), 500 / 4);
		// Then
		assert_eq!(ledger.active, 3 * 500 / 4);
		assert_eq!(ledger.unlocking, vec![]);
		assert_eq!(ledger.total, ledger.active);
		assert_eq!(LedgerSlashPerEra::get().0, 3 * 500 / 4);
		assert_eq!(LedgerSlashPerEra::get().1, Default::default());

		// Given we have the same as above,
		ledger.unlocking = bounded_vec![c(4, 40), c(5, 100), c(6, 10), c(7, 250)];
		ledger.active = 500;
		ledger.total = 40 + 10 + 100 + 250 + 500; // 900
		assert_eq!(ledger.total, 900);
		// When we have a higher min balance
		assert_eq!(
			ledger.slash(
				900 / 2,
				25, /* min balance - chunks with era 0 & 2 will be slashed to <=25, causing it
				     * to get swept */
				0
			),
			450
		);
		assert_eq!(ledger.active, 500 / 2);
		// the last chunk was not slashed 50% like all the rest, because some other earlier chunks
		// got dusted.
		assert_eq!(ledger.unlocking, vec![c(5, 100 / 2), c(7, 150)]);
		assert_eq!(ledger.total, 900 / 2);
		assert_eq!(LedgerSlashPerEra::get().0, 500 / 2);
		assert_eq!(
			LedgerSlashPerEra::get().1,
			BTreeMap::from([(4, 0), (5, 100 / 2), (6, 0), (7, 150)])
		);

		// Given
		// slash order --------------------NA--------2----------0----------1----
		ledger.unlocking = bounded_vec![c(4, 40), c(5, 100), c(6, 10), c(7, 250)];
		ledger.active = 500;
		ledger.total = 40 + 10 + 100 + 250 + 500; // 900
		assert_eq!(
			ledger.slash(
				500 + 10 + 250 + 100 / 2, // active + era 6 + era 7 + era 5 / 2
				0,
				3 /* slash era 6 first, so the affected parts are era 6, era 7 and
				   * ledge.active. This will cause the affected to go to zero, and then we will
				   * start slashing older chunks */
			),
			500 + 250 + 10 + 100 / 2
		);
		// Then
		assert_eq!(ledger.active, 0);
		assert_eq!(ledger.unlocking, vec![c(4, 40), c(5, 100 / 2)]);
		assert_eq!(ledger.total, 90);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(LedgerSlashPerEra::get().1, BTreeMap::from([(5, 100 / 2), (6, 0), (7, 0)]));

		// Given
		// iteration order------------------NA---------2----------0----------1----
		ledger.unlocking = bounded_vec![c(4, 100), c(5, 100), c(6, 100), c(7, 100)];
		ledger.active = 100;
		ledger.total = 5 * 100;
		// When
		assert_eq!(
			ledger.slash(
				351, // active + era 6 + era 7 + era 5 / 2 + 1
				50,  // min balance - everything slashed below 50 will get dusted
				3    /* slash era 3+3 first, so the affected parts are era 6, era 7 and
				      * ledge.active. This will cause the affected to go to zero, and then we
				      * will start slashing older chunks */
			),
			400
		);
		// Then
		assert_eq!(ledger.active, 0);
		assert_eq!(ledger.unlocking, vec![c(4, 100)]);
		assert_eq!(ledger.total, 100);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(LedgerSlashPerEra::get().1, BTreeMap::from([(5, 0), (6, 0), (7, 0)]));

		// Tests for saturating arithmetic

		// Given
		let slash = u64::MAX as Balance * 2;
		// The value of the other parts of ledger that will get slashed
		let value = slash - (10 * 4);

		ledger.active = 10;
		ledger.unlocking = bounded_vec![c(4, 10), c(5, 10), c(6, 10), c(7, value)];
		ledger.total = value + 40;
		// When
		let slash_amount = ledger.slash(slash, 0, 0);
		assert_eq_error_rate!(slash_amount, slash, 5);
		// Then
		assert_eq!(ledger.active, 0); // slash of 9
		assert_eq!(ledger.unlocking, vec![]);
		assert_eq!(ledger.total, 0);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(LedgerSlashPerEra::get().1, BTreeMap::from([(4, 0), (5, 0), (6, 0), (7, 0)]));

		// Given
		use sp_runtime::PerThing as _;
		let slash = u64::MAX as Balance * 2;
		let value = u64::MAX as Balance * 2;
		let unit = 100;
		// slash * value that will saturate
		assert!(slash.checked_mul(value).is_none());
		// but slash * unit won't.
		assert!(slash.checked_mul(unit).is_some());
		ledger.unlocking = bounded_vec![c(4, unit), c(5, value), c(6, unit), c(7, unit)];
		//--------------------------------------note value^^^
		ledger.active = unit;
		ledger.total = unit * 4 + value;
		// When
		assert_eq!(ledger.slash(slash, 0, 0), slash);
		// Then
		// The amount slashed out of `unit`
		let affected_balance = value + unit * 4;
		let ratio = Perquintill::from_rational_with_rounding(slash, affected_balance, Rounding::Up)
			.unwrap();
		// `unit` after the slash is applied
		let unit_slashed = {
			let unit_slash = ratio.mul_ceil(unit);
			unit - unit_slash
		};
		let value_slashed = {
			let value_slash = ratio.mul_ceil(value);
			value - value_slash
		};
		assert_eq!(ledger.active, unit_slashed);
		assert_eq!(ledger.unlocking, vec![c(5, value_slashed), c(7, 32)]);
		assert_eq!(ledger.total, value_slashed + 32);
		assert_eq!(LedgerSlashPerEra::get().0, 0);
		assert_eq!(
			LedgerSlashPerEra::get().1,
			BTreeMap::from([(4, 0), (5, value_slashed), (6, 0), (7, 32)])
		);
	});
}

#[test]
fn withdrawals_are_blocked_for_unprocessed_and_unapplied_slashes() {
	ExtBuilder::default()
		.slash_defer_duration(2)
		.bonding_duration(3)
		.add_staker(61, 1000, StakerStatus::Validator)
		.add_staker(71, 1000, StakerStatus::Validator)
		.add_staker(81, 1000, StakerStatus::Validator)
		.add_staker(91, 1000, StakerStatus::Validator)
		// we want to replicate a scenario where all offences could not be processed in 1 era, so we
		// reduce the era length to 1 block.
		.session_per_era(1)
		.period(1)
		.validator_count(6)
		.build_and_execute(|| {
			// NOTE for curious reader: Era change still takes 2 blocks... don't ask why ¯\_(ツ)_/¯
			let _expected_era_length = 2;

			// Set up nominator.
			let validator = 11;
			let nominator = 301;
			bond_nominator(nominator, 500, vec![validator]);

			// create unbonding chunks for the next two eras.
			Session::roll_until_active_era(2);
			assert_ok!(Staking::unbond(RuntimeOrigin::signed(nominator), 100));
			Session::roll_until_active_era(3);
			assert_ok!(Staking::unbond(RuntimeOrigin::signed(nominator), 150));

			// Rationale: We want to simulate a backlog of offences from era 3 that remain
			// unprocessed by the time unbonding becomes possible in era 6.
			//
			// Offences for era 3 must be reported no later than era 4, since slashing application
			// starts in era 5. To achieve this, we flood era 3 with more than 4 offences, all
			// reported just before the end of era 4. Given there are only 2 blocks per era
			// (limiting processing throughput), this ensures not all offences will be processed by
			// era 6 — blocking withdrawal as intended.

			// go to era 4.
			Session::roll_until_active_era(4);

			// roll one block of 2 of era 4.
			Session::roll_next();

			// flood offence pipeline with offences for era 3.
			// Note: our validator 11 is not slashed.
			add_slash_in_era(21, 3, Perbill::from_percent(10));
			add_slash_in_era(61, 3, Perbill::from_percent(10));
			add_slash_in_era(71, 3, Perbill::from_percent(10));
			add_slash_in_era(81, 3, Perbill::from_percent(10));
			add_slash_in_era(91, 3, Perbill::from_percent(10));

			// lets roll to era 6 where all unbonding chunks are available to withdraw.
			Session::roll_until_active_era(6);
			assert_eq!(active_era(), 6);

			// Ensure unbonding chunks can all be withdrawn by era 6.
			let expected_chunks: BoundedVec<UnlockChunk<Balance>, MaxUnlockingChunks> = bounded_vec![
				// era is unbond_era + bonding_duration, starting from era 2 + 3.
				UnlockChunk { era: 5, value: 100 },
				UnlockChunk { era: 6, value: 150 },
			];
			assert_eq!(Ledger::<T>::get(nominator).unwrap().unlocking, expected_chunks);

			// and we created 5 offences, of which 3 would be processed in last block of era 4, and
			// 2 blocks of era 5.
			assert_eq!(era_unprocessed_offence_count(3), 5 - 3);
			assert_eq!(OffenceQueueEras::<T>::get().unwrap(), vec![3]);

			// all nominator balance other than ED is staked.
			let nominator_balance_pre_withdraw = Balances::free_balance(&nominator);
			assert_eq!(nominator_balance_pre_withdraw, 1);

			// Since the eras are too short, the offences that needed to be applied for last era 5
			// are still unapplied. This will block the withdrawal.
			assert_eq!(era_unapplied_slash_count(5), 1);

			// WHEN: the nominator tries to withdraw unbonded funds while there are unapplied
			// offence in the last era.
			assert_noop!(
				Staking::withdraw_unbonded(RuntimeOrigin::signed(nominator), 0),
				Error::<T>::UnappliedSlashesInPreviousEra
			);

			// let's clear the slashes by manually applying them.
			apply_pending_slashes_from_previous_era();
			// ensure unapplied slashes are cleared.
			assert_eq!(era_unapplied_slash_count(5), 0);

			// WHEN: the nominator tries to withdraw unbonded funds.
			assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(nominator), 0));

			// THEN: only the first unbonding chunk is withdrawn, as the second one is blocked by
			// unprocessed offences.
			let nominator_balance_post_withdraw_1 = Balances::free_balance(&nominator);
			// free balance increases by unlock chunk 1 value.
			assert_eq!(nominator_balance_post_withdraw_1, nominator_balance_pre_withdraw + 100);

			// rolling a block creates another unapplied slash for era 3 as well as process a
			// remaining offence.
			Session::roll_next();
			assert_eq!(era_unapplied_slash_count(5), 1);
			// clear the pending slashes.
			apply_pending_slashes_from_previous_era();

			// there is still one offence unprocessed for era 3.
			assert_eq!(era_unprocessed_offence_count(3), 1);

			// withdrawals are still not possible for era (3 + 3 =) 6.
			assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(nominator), 0));
			assert_eq!(Balances::free_balance(&nominator), nominator_balance_post_withdraw_1);

			// WHEN: all offences are processed.
			Session::roll_next();
			// Note that active_era has bumped to 7.
			assert_eq!(active_era(), 7);
			// The previous block created another unapplied slash for era 5, but we only block
			// withdrawals upto 1 block (to give enough time for offchain actors to apply slashes
			// manually). So, we dont need to apply pending slashes for era 5.
			assert_eq!(era_unapplied_slash_count(5), 1);
			// But era 6 (last era) has no unapplied slashes.
			assert_eq!(era_unapplied_slash_count(6), 0);
			// We also ensure all offences in the queue for era 3 are now processed.
			assert_eq!(era_unprocessed_offence_count(3), 0);
			assert_eq!(OffenceQueueEras::<T>::get(), None);

			// Withdrawing for era 3 should be possible.
			assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(nominator), 0));
			assert_eq!(Balances::free_balance(&nominator), nominator_balance_post_withdraw_1 + 150);

			// Finally, we clear the unapplied slashes for era 5. Otherwise our try state checks
			// will fail. (Try by commenting the next line :))
			apply_pending_slashes_from_era(5);
		});
}

mod paged_slashing {
	use super::*;
	use crate::slashing::OffenceRecord;

	#[test]
	fn offence_processed_in_multi_block() {
		// Ensure each page is processed only once.
		ExtBuilder::default()
			.has_stakers(false)
			.slash_defer_duration(3)
			.build_and_execute(|| {
				let base_stake = 1000;

				// Create a validator:
				bond_validator(11, base_stake);
				assert_eq!(Validators::<T>::count(), 1);

				// Track the total exposure of 11.
				let mut exposure_counter = base_stake;

				// Exposure page size is 64, hence it creates 4 pages of exposure.
				let expected_page_count = 4;
				for i in 0..200 {
					let bond_amount = base_stake + i as Balance;
					bond_nominator(1000 + i, bond_amount, vec![11]);
					// with multi page reward payout, payout exposure is same as total exposure.
					exposure_counter += bond_amount;
				}

				Session::roll_until_active_era(2);
				let _ = staking_events_since_last_call();

				assert_eq!(
					ErasStakersOverview::<T>::get(2, 11).expect("exposure should exist"),
					PagedExposureMetadata {
						total: exposure_counter,
						own: base_stake,
						page_count: expected_page_count,
						nominator_count: 200,
					}
				);

				// report an offence for 11 in era 2.
				add_slash(11);

				// ensure offence is queued.
				assert_eq!(
					staking_events_since_last_call(),
					vec![Event::OffenceReported {
						validator: 11,
						fraction: Perbill::from_percent(10),
						offence_era: 2
					}]
				);

				// ensure offence queue has items.
				assert_eq!(
					OffenceQueue::<T>::get(2, 11).unwrap(),
					slashing::OffenceRecord {
						reporter: None,
						reported_era: 2,
						// first page to be marked for processing.
						exposure_page: expected_page_count - 1,
						slash_fraction: Perbill::from_percent(10),
						prior_slash_fraction: Perbill::zero(),
					}
				);

				// The offence era is noted in the queue.
				assert_eq!(OffenceQueueEras::<T>::get().unwrap(), vec![2]);

				// ensure Processing offence is empty yet.
				assert_eq!(ProcessingOffence::<T>::get(), None);

				// ensure no unapplied slashes for era 5 (offence_era + slash_defer_duration).
				assert_eq!(UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>().len(), 0);

				// Checkpoint 1: advancing to next block will compute the first page of slash.
				Session::roll_next();

				// ensure the last page of offence is processed.
				// (offence is processed in reverse order of pages)
				assert_eq!(
					staking_events_since_last_call().as_slice(),
					vec![Event::SlashComputed {
						offence_era: 2,
						slash_era: 5,
						offender: 11,
						page: expected_page_count - 1
					},]
				);

				// offender is removed from offence queue
				assert_eq!(OffenceQueue::<T>::get(2, 11), None);

				// offence era is removed from queue.
				assert_eq!(OffenceQueueEras::<T>::get(), None);

				// this offence is not completely processed yet, so it should be in processing.
				assert_eq!(
					ProcessingOffence::<T>::get(),
					Some((
						2,
						11,
						OffenceRecord {
							reporter: None,
							reported_era: 2,
							// page 3 is processed, next page to be processed is 2.
							exposure_page: 2,
							slash_fraction: Perbill::from_percent(10),
							prior_slash_fraction: Perbill::zero(),
						}
					))
				);

				// unapplied slashes for era 5.
				let slashes = UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>();

				// only one unapplied slash exists.
				assert_eq!(slashes.len(), 1);
				let (slash_key, unapplied_slash) = &slashes[0];

				// this is a unique key to ensure unapplied slash is not overwritten for multiple
				// offence by offender in the same era.
				assert_eq!(*slash_key, (11, Perbill::from_percent(10), expected_page_count - 1));

				// validator own stake is only included in the first page. Since this is page 3,
				// only nominators are slashed.
				assert_eq!(unapplied_slash.own, 0);
				assert_eq!(unapplied_slash.validator, 11);
				assert_eq!(unapplied_slash.others.len(), 200 % 64);

				// Checkpoint 2: advancing to next block will compute the second page of slash.
				Session::roll_next();

				// offence queue still empty
				assert_eq!(OffenceQueue::<T>::get(2, 11), None);
				assert_eq!(OffenceQueueEras::<T>::get(), None);

				// processing offence points to next page.
				assert_eq!(
					ProcessingOffence::<T>::get(),
					Some((
						2,
						11,
						OffenceRecord {
							reporter: None,
							reported_era: 2,
							// page 2 is processed, next page to be processed is 1.
							exposure_page: 1,
							slash_fraction: Perbill::from_percent(10),
							prior_slash_fraction: Perbill::zero(),
						}
					))
				);

				// there are two unapplied slashes for era 4.
				assert_eq!(UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>().len(), 2);

				// ensure the last page of offence is processed.
				// (offence is processed in reverse order of pages)
				assert_eq!(
					staking_events_since_last_call(),
					vec![Event::SlashComputed {
						offence_era: 2,
						slash_era: 5,
						offender: 11,
						page: expected_page_count - 2
					},]
				);

				// Checkpoint 3: advancing to two more blocks will complete the processing of the
				// reported offence
				Session::roll_next();
				Session::roll_next();

				// no processing offence.
				assert!(ProcessingOffence::<T>::get().is_none());
				// total of 4 unapplied slash.
				assert_eq!(UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>().len(), 4);

				// Checkpoint 4: lets verify the application of slashes in multiple blocks.
				// advance to era 4.
				Session::roll_until_active_era(5);
				// slashes are not applied just yet. From next blocks, they will be applied.
				assert_eq!(UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>().len(), 4);

				// advance to next block.
				Session::roll_next();
				// 1 slash is applied.
				assert_eq!(UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>().len(), 3);

				// advance two blocks.
				Session::roll_next();
				Session::roll_next();
				// 2 more slashes are applied.
				assert_eq!(UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>().len(), 1);

				// advance one more block.
				Session::roll_next();
				// all slashes are applied.
				assert_eq!(UnappliedSlashes::<T>::iter_prefix(&5).collect::<Vec<_>>().len(), 0);

				// ensure all stakers are slashed correctly.
				assert_eq!(asset::staked::<T>(&11), 1000 - 100);

				for i in 0..200 {
					let original_stake = 1000 + i as Balance;
					let expected_slash = Perbill::from_percent(10) * original_stake;
					assert_eq!(asset::staked::<T>(&(1000 + i)), original_stake - expected_slash);
				}
			})
	}

	#[test]
	fn offence_discarded_correctly() {
		ExtBuilder::default().slash_defer_duration(3).build_and_execute(|| {
			Session::roll_until_active_era(2);
			let _ = staking_events_since_last_call();

			// Scenario 1: 11 commits an offence in era 2.
			add_slash(11);

			// offence is queued, not processed yet.
			let queued_offence_one = OffenceQueue::<T>::get(2, 11).unwrap();
			assert_eq!(queued_offence_one.slash_fraction, Perbill::from_percent(10));
			assert_eq!(queued_offence_one.prior_slash_fraction, Perbill::zero());
			assert_eq!(OffenceQueueEras::<T>::get().unwrap(), vec![2]);

			// Scenario 1A: 11 commits a second offence in era 2 with **lower** slash fraction than
			// the previous offence.
			add_slash_with_percent(11, 5);

			// the second offence is discarded. No change in the queue.
			assert_eq!(OffenceQueue::<T>::get(2, 11).unwrap(), queued_offence_one);

			// Scenario 1B: 11 commits a second offence in era 2 with **higher** slash fraction than
			// the previous offence.
			add_slash_with_percent(11, 15);
			assert_eq!(
				staking_events_since_last_call(),
				vec![
					Event::OffenceReported {
						offence_era: 2,
						validator: 11,
						fraction: Perbill::from_percent(10)
					},
					Event::OffenceReported {
						offence_era: 2,
						validator: 11,
						fraction: Perbill::from_percent(5)
					},
					Event::OffenceReported {
						offence_era: 2,
						validator: 11,
						fraction: Perbill::from_percent(15)
					}
				]
			);

			// the second offence overwrites the first offence.
			let overwritten_offence = OffenceQueue::<T>::get(2, 11).unwrap();
			assert!(overwritten_offence.slash_fraction > queued_offence_one.slash_fraction);
			assert_eq!(overwritten_offence.slash_fraction, Perbill::from_percent(15));
			assert_eq!(overwritten_offence.prior_slash_fraction, Perbill::zero());
			assert_eq!(OffenceQueueEras::<T>::get().unwrap(), vec![2]);

			// Scenario 2: 11 commits another offence in era 2, but after the previous offence is
			// processed.
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::SlashComputed { offence_era: 2, slash_era: 5, offender: 11, page: 0 }]
			);

			assert!(OffenceQueue::<T>::get(2, 11).is_none());
			assert!(OffenceQueueEras::<T>::get().is_none());
			// unapplied slash is created for the offence.
			assert!(UnappliedSlashes::<T>::contains_key(2 + 3, (11, Perbill::from_percent(15), 0)));

			// Scenario 2A: offence has **lower** slash fraction than the previous offence.
			add_slash_with_percent(11, 14);
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::OffenceReported {
					offence_era: 2,
					validator: 11,
					fraction: Perbill::from_percent(14)
				},]
			);

			// offence is discarded.
			assert!(OffenceQueue::<T>::get(2, 11).is_none());
			assert!(OffenceQueueEras::<T>::get().is_none());

			// Scenario 2B: offence has **higher** slash fraction than the previous offence.
			add_slash_with_percent(11, 16);
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::OffenceReported {
					offence_era: 2,
					validator: 11,
					fraction: Perbill::from_percent(16)
				},]
			);

			// process offence
			Session::roll_next();
			assert_eq!(
				staking_events_since_last_call(),
				vec![Event::SlashComputed { offence_era: 2, slash_era: 5, offender: 11, page: 0 }]
			);

			// there are now two slash records for 11, for era 5, with the newer one only slashing
			// the diff between slash fractions of 16 and 15.
			let slash_one =
				UnappliedSlashes::<T>::get(2 + 3, (11, Perbill::from_percent(15), 0)).unwrap();
			let slash_two =
				UnappliedSlashes::<T>::get(2 + 3, (11, Perbill::from_percent(16), 0)).unwrap();
			assert!(slash_one.own > slash_two.own);
		});
	}

	#[test]
	fn offence_eras_queued_correctly() {
		ExtBuilder::default().build_and_execute(|| {
			// 11 and 21 are validators.
			assert_eq!(Staking::status(&11).unwrap(), StakerStatus::Validator);
			assert_eq!(Staking::status(&21).unwrap(), StakerStatus::Validator);

			Session::roll_until_active_era(2);

			// 11 and 21 commits offence in era 2.
			add_slash_in_era(11, 2, Perbill::from_percent(10));
			add_slash_in_era(21, 2, Perbill::from_percent(10));

			// 11 and 21 commits offence in era 1 but reported after the era 2 offence.
			add_slash_in_era(11, 1, Perbill::from_percent(10));
			add_slash_in_era(21, 1, Perbill::from_percent(10));

			// queued offence eras are sorted.
			assert_eq!(OffenceQueueEras::<T>::get().unwrap(), vec![1, 2]);

			// next two blocks, the offence in era 1 is processed.
			Session::roll_next();
			Session::roll_next();

			// only era 2 is left in the queue.
			assert_eq!(OffenceQueueEras::<T>::get().unwrap(), vec![2]);

			// next block, the offence in era 2 is processed.
			Session::roll_next();

			// era still exist in the queue.
			assert_eq!(OffenceQueueEras::<T>::get().unwrap(), vec![2]);

			// next block, the era 2 is processed.
			Session::roll_next();

			// queue is empty.
			assert_eq!(OffenceQueueEras::<T>::get(), None);
		});
	}

	#[test]
	fn non_deferred_slash_applied_instantly() {
		ExtBuilder::default().build_and_execute(|| {
			Session::roll_until_active_era(2);

			let validator_stake = asset::staked::<T>(&11);
			let slash_fraction = Perbill::from_percent(10);
			let expected_slash = slash_fraction * validator_stake;
			let _ = staking_events_since_last_call();

			// report an offence for 11 in era 1.
			add_slash_in_era(11, 1, slash_fraction);

			// ensure offence is queued.
			assert_eq!(
				staking_events_since_last_call().as_slice(),
				vec![Event::OffenceReported {
					validator: 11,
					fraction: Perbill::from_percent(10),
					offence_era: 1
				}]
			);

			// process offence
			Session::roll_next();

			// ensure slash is computed and applied.
			assert_eq!(
				staking_events_since_last_call().as_slice(),
				vec![
					Event::SlashComputed { offence_era: 1, slash_era: 1, offender: 11, page: 0 },
					Event::Slashed { staker: 11, amount: expected_slash },
					// this is the nominator of 11.
					Event::Slashed { staker: 101, amount: 25 },
				]
			);

			// ensure validator is slashed.
			assert_eq!(asset::staked::<T>(&11), validator_stake - expected_slash);
		});
	}

	#[test]
	fn validator_with_no_exposure_slashed() {
		ExtBuilder::default().build_and_execute(|| {
			let validator_stake = asset::staked::<T>(&11);
			let slash_fraction = Perbill::from_percent(10);
			let expected_slash = slash_fraction * validator_stake;

			// only 101 nominates 11, lets remove them.
			assert_ok!(Staking::nominate(RuntimeOrigin::signed(101), vec![21]));

			Session::roll_until_active_era(2);

			// ensure validator has no exposure.
			assert_eq!(ErasStakersOverview::<T>::get(2, 11).unwrap().page_count, 0,);

			// clear events
			let _ = staking_events_since_last_call();

			// report an offence for 11.
			add_slash_with_percent(11, 10);
			Session::roll_next();

			// ensure validator is slashed.
			assert_eq!(asset::staked::<T>(&11), validator_stake - expected_slash);
			assert_eq!(
				staking_events_since_last_call().as_slice(),
				vec![
					Event::OffenceReported {
						offence_era: 2,
						validator: 11,
						fraction: slash_fraction
					},
					Event::SlashComputed { offence_era: 2, slash_era: 2, offender: 11, page: 0 },
					Event::Slashed { staker: 11, amount: expected_slash },
				]
			);
		});
	}
}