This repository was archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathtests.rs
More file actions
5251 lines (4502 loc) · 159 KB
/
tests.rs
File metadata and controls
5251 lines (4502 loc) · 159 KB
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
// This file is part of Substrate.
// Copyright (C) 2017-2022 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.
//! Tests for the module.
use super::{ConfigOp, Event, MaxUnlockingChunks, *};
use frame_election_provider_support::{ElectionProvider, SortedListProvider, Support};
use frame_support::{
assert_noop, assert_ok, assert_storage_noop, bounded_vec,
dispatch::WithPostDispatchInfo,
pallet_prelude::*,
traits::{Currency, Get, ReservableCurrency},
weights::{extract_actual_weight, GetDispatchInfo},
};
use mock::*;
use pallet_balances::Error as BalancesError;
use sp_runtime::{
assert_eq_error_rate,
traits::{BadOrigin, Dispatchable},
Perbill, Percent,
};
use sp_staking::{
offence::{DisableStrategy, OffenceDetails, OnOffenceHandler},
SessionIndex,
};
use sp_std::prelude::*;
use substrate_test_utils::assert_eq_uvec;
#[test]
fn set_staking_configs_works() {
ExtBuilder::default().build_and_execute(|| {
// setting works
assert_ok!(Staking::set_staking_configs(
Origin::root(),
ConfigOp::Set(1_500),
ConfigOp::Set(2_000),
ConfigOp::Set(10),
ConfigOp::Set(20),
ConfigOp::Set(Percent::from_percent(75)),
ConfigOp::Set(Zero::zero())
));
assert_eq!(MinNominatorBond::<Test>::get(), 1_500);
assert_eq!(MinValidatorBond::<Test>::get(), 2_000);
assert_eq!(MaxNominatorsCount::<Test>::get(), Some(10));
assert_eq!(MaxValidatorsCount::<Test>::get(), Some(20));
assert_eq!(ChillThreshold::<Test>::get(), Some(Percent::from_percent(75)));
assert_eq!(MinCommission::<Test>::get(), Perbill::from_percent(0));
// noop does nothing
assert_storage_noop!(assert_ok!(Staking::set_staking_configs(
Origin::root(),
ConfigOp::Noop,
ConfigOp::Noop,
ConfigOp::Noop,
ConfigOp::Noop,
ConfigOp::Noop,
ConfigOp::Noop
)));
// removing works
assert_ok!(Staking::set_staking_configs(
Origin::root(),
ConfigOp::Remove,
ConfigOp::Remove,
ConfigOp::Remove,
ConfigOp::Remove,
ConfigOp::Remove,
ConfigOp::Remove
));
assert_eq!(MinNominatorBond::<Test>::get(), 0);
assert_eq!(MinValidatorBond::<Test>::get(), 0);
assert_eq!(MaxNominatorsCount::<Test>::get(), None);
assert_eq!(MaxValidatorsCount::<Test>::get(), None);
assert_eq!(ChillThreshold::<Test>::get(), None);
assert_eq!(MinCommission::<Test>::get(), Perbill::from_percent(0));
});
}
#[test]
fn force_unstake_works() {
ExtBuilder::default().build_and_execute(|| {
// Account 11 is stashed and locked, and account 10 is the controller
assert_eq!(Staking::bonded(&11), Some(10));
// Adds 2 slashing spans
add_slash(&11);
// Cant transfer
assert_noop!(
Balances::transfer(Origin::signed(11), 1, 10),
BalancesError::<Test, _>::LiquidityRestrictions
);
// Force unstake requires root.
assert_noop!(Staking::force_unstake(Origin::signed(11), 11, 2), BadOrigin);
// Force unstake needs correct number of slashing spans (for weight calculation)
assert_noop!(
Staking::force_unstake(Origin::root(), 11, 0),
Error::<Test>::IncorrectSlashingSpans
);
// We now force them to unstake
assert_ok!(Staking::force_unstake(Origin::root(), 11, 2));
// No longer bonded.
assert_eq!(Staking::bonded(&11), None);
// Transfer works.
assert_ok!(Balances::transfer(Origin::signed(11), 1, 10));
});
}
#[test]
fn kill_stash_works() {
ExtBuilder::default().build_and_execute(|| {
// Account 11 is stashed and locked, and account 10 is the controller
assert_eq!(Staking::bonded(&11), Some(10));
// Adds 2 slashing spans
add_slash(&11);
// Only can kill a stash account
assert_noop!(Staking::kill_stash(&12, 0), Error::<Test>::NotStash);
// Respects slashing span count
assert_noop!(Staking::kill_stash(&11, 0), Error::<Test>::IncorrectSlashingSpans);
// Correct inputs, everything works
assert_ok!(Staking::kill_stash(&11, 2));
// No longer bonded.
assert_eq!(Staking::bonded(&11), None);
});
}
#[test]
fn basic_setup_works() {
// Verifies initial conditions of mock
ExtBuilder::default().build_and_execute(|| {
// Account 11 is stashed and locked, and account 10 is the controller
assert_eq!(Staking::bonded(&11), Some(10));
// Account 21 is stashed and locked, and account 20 is the controller
assert_eq!(Staking::bonded(&21), Some(20));
// Account 1 is not a stashed
assert_eq!(Staking::bonded(&1), None);
// Account 10 controls the stash from account 11, which is 100 * balance_factor units
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
claimed_rewards: vec![]
})
);
// Account 20 controls the stash from account 21, which is 200 * balance_factor units
assert_eq!(
Staking::ledger(&20),
Some(StakingLedger {
stash: 21,
total: 1000,
active: 1000,
unlocking: Default::default(),
claimed_rewards: vec![]
})
);
// Account 1 does not control any stash
assert_eq!(Staking::ledger(&1), None);
// ValidatorPrefs are default
assert_eq_uvec!(
<Validators<Test>>::iter().collect::<Vec<_>>(),
vec![
(31, ValidatorPrefs::default()),
(21, ValidatorPrefs::default()),
(11, ValidatorPrefs::default())
]
);
assert_eq!(
Staking::ledger(100),
Some(StakingLedger {
stash: 101,
total: 500,
active: 500,
unlocking: Default::default(),
claimed_rewards: vec![]
})
);
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
assert_eq!(
Staking::eras_stakers(active_era(), 11),
Exposure {
total: 1125,
own: 1000,
others: vec![IndividualExposure { who: 101, value: 125 }]
},
);
assert_eq!(
Staking::eras_stakers(active_era(), 21),
Exposure {
total: 1375,
own: 1000,
others: vec![IndividualExposure { who: 101, value: 375 }]
},
);
// initial total stake = 1125 + 1375
assert_eq!(Staking::eras_total_stake(active_era()), 2500);
// The number of validators required.
assert_eq!(Staking::validator_count(), 2);
// Initial Era and session
assert_eq!(active_era(), 0);
// Account 10 has `balance_factor` free balance
assert_eq!(Balances::free_balance(10), 1);
assert_eq!(Balances::free_balance(10), 1);
// New era is not being forced
assert_eq!(Staking::force_era(), Forcing::NotForcing);
});
}
#[test]
fn change_controller_works() {
ExtBuilder::default().build_and_execute(|| {
// 10 and 11 are bonded as stash controller.
assert_eq!(Staking::bonded(&11), Some(10));
// 10 can control 11 who is initially a validator.
assert_ok!(Staking::chill(Origin::signed(10)));
// change controller
assert_ok!(Staking::set_controller(Origin::signed(11), 5));
assert_eq!(Staking::bonded(&11), Some(5));
mock::start_active_era(1);
// 10 is no longer in control.
assert_noop!(
Staking::validate(Origin::signed(10), ValidatorPrefs::default()),
Error::<Test>::NotController,
);
assert_ok!(Staking::validate(Origin::signed(5), ValidatorPrefs::default()));
})
}
#[test]
fn rewards_should_work() {
ExtBuilder::default().nominate(true).session_per_era(3).build_and_execute(|| {
let init_balance_10 = Balances::total_balance(&10);
let init_balance_11 = Balances::total_balance(&11);
let init_balance_20 = Balances::total_balance(&20);
let init_balance_21 = Balances::total_balance(&21);
let init_balance_100 = Balances::total_balance(&100);
let init_balance_101 = Balances::total_balance(&101);
// Set payees
Payee::<Test>::insert(11, RewardDestination::Controller);
Payee::<Test>::insert(21, RewardDestination::Controller);
Payee::<Test>::insert(101, RewardDestination::Controller);
Pallet::<Test>::reward_by_ids(vec![(11, 50)]);
Pallet::<Test>::reward_by_ids(vec![(11, 50)]);
// This is the second validator of the current elected set.
Pallet::<Test>::reward_by_ids(vec![(21, 50)]);
// Compute total payout now for whole duration of the session.
let total_payout_0 = current_total_payout_for_duration(reward_time_per_era());
let maximum_payout = maximum_payout_for_duration(reward_time_per_era());
start_session(1);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
assert_eq!(Balances::total_balance(&10), init_balance_10);
assert_eq!(Balances::total_balance(&11), init_balance_11);
assert_eq!(Balances::total_balance(&20), init_balance_20);
assert_eq!(Balances::total_balance(&21), init_balance_21);
assert_eq!(Balances::total_balance(&100), init_balance_100);
assert_eq!(Balances::total_balance(&101), init_balance_101);
assert_eq!(
Staking::eras_reward_points(active_era()),
EraRewardPoints {
total: 50 * 3,
individual: vec![(11, 100), (21, 50)].into_iter().collect(),
}
);
let part_for_10 = Perbill::from_rational::<u32>(1000, 1125);
let part_for_20 = Perbill::from_rational::<u32>(1000, 1375);
let part_for_100_from_10 = Perbill::from_rational::<u32>(125, 1125);
let part_for_100_from_20 = Perbill::from_rational::<u32>(375, 1375);
start_session(2);
start_session(3);
assert_eq!(active_era(), 1);
assert_eq!(
mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()),
maximum_payout - total_payout_0,
);
assert_eq!(
*mock::staking_events().last().unwrap(),
Event::EraPaid(0, total_payout_0, maximum_payout - total_payout_0)
);
mock::make_all_reward_payment(0);
assert_eq_error_rate!(
Balances::total_balance(&10),
init_balance_10 + part_for_10 * total_payout_0 * 2 / 3,
2,
);
assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2);
assert_eq_error_rate!(
Balances::total_balance(&20),
init_balance_20 + part_for_20 * total_payout_0 * 1 / 3,
2,
);
assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2);
assert_eq_error_rate!(
Balances::total_balance(&100),
init_balance_100 +
part_for_100_from_10 * total_payout_0 * 2 / 3 +
part_for_100_from_20 * total_payout_0 * 1 / 3,
2
);
assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
// Compute total payout now for whole duration as other parameter won't change
let total_payout_1 = current_total_payout_for_duration(reward_time_per_era());
mock::start_active_era(2);
assert_eq!(
mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()),
maximum_payout * 2 - total_payout_0 - total_payout_1,
);
assert_eq!(
*mock::staking_events().last().unwrap(),
Event::EraPaid(1, total_payout_1, maximum_payout - total_payout_1)
);
mock::make_all_reward_payment(1);
assert_eq_error_rate!(
Balances::total_balance(&10),
init_balance_10 + part_for_10 * (total_payout_0 * 2 / 3 + total_payout_1),
2,
);
assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2);
assert_eq_error_rate!(
Balances::total_balance(&20),
init_balance_20 + part_for_20 * total_payout_0 * 1 / 3,
2,
);
assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2);
assert_eq_error_rate!(
Balances::total_balance(&100),
init_balance_100 +
part_for_100_from_10 * (total_payout_0 * 2 / 3 + total_payout_1) +
part_for_100_from_20 * total_payout_0 * 1 / 3,
2
);
assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2);
});
}
#[test]
fn staking_should_work() {
ExtBuilder::default().nominate(false).build_and_execute(|| {
// remember + compare this along with the test.
assert_eq_uvec!(validator_controllers(), vec![20, 10]);
// put some money in account that we'll use.
for i in 1..5 {
let _ = Balances::make_free_balance_be(&i, 2000);
}
// --- Block 2:
start_session(2);
// add a new candidate for being a validator. account 3 controlled by 4.
assert_ok!(Staking::bond(Origin::signed(3), 4, 1500, RewardDestination::Controller));
assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default()));
assert_ok!(Session::set_keys(Origin::signed(4), SessionKeys { other: 4.into() }, vec![]));
// No effects will be seen so far.
assert_eq_uvec!(validator_controllers(), vec![20, 10]);
// --- Block 3:
start_session(3);
// No effects will be seen so far. Era has not been yet triggered.
assert_eq_uvec!(validator_controllers(), vec![20, 10]);
// --- Block 4: the validators will now be queued.
start_session(4);
assert_eq!(active_era(), 1);
// --- Block 5: the validators are still in queue.
start_session(5);
// --- Block 6: the validators will now be changed.
start_session(6);
assert_eq_uvec!(validator_controllers(), vec![20, 4]);
// --- Block 6: Unstake 4 as a validator, freeing up the balance stashed in 3
// 4 will chill
Staking::chill(Origin::signed(4)).unwrap();
// --- Block 7: nothing. 4 is still there.
start_session(7);
assert_eq_uvec!(validator_controllers(), vec![20, 4]);
// --- Block 8:
start_session(8);
// --- Block 9: 4 will not be a validator.
start_session(9);
assert_eq_uvec!(validator_controllers(), vec![20, 10]);
// Note: the stashed value of 4 is still lock
assert_eq!(
Staking::ledger(&4),
Some(StakingLedger {
stash: 3,
total: 1500,
active: 1500,
unlocking: Default::default(),
claimed_rewards: vec![0],
})
);
// e.g. it cannot reserve more than 500 that it has free from the total 2000
assert_noop!(Balances::reserve(&3, 501), BalancesError::<Test, _>::LiquidityRestrictions);
assert_ok!(Balances::reserve(&3, 409));
});
}
#[test]
fn blocking_and_kicking_works() {
ExtBuilder::default()
.minimum_validator_count(1)
.validator_count(4)
.nominate(true)
.build_and_execute(|| {
// block validator 10/11
assert_ok!(Staking::validate(
Origin::signed(10),
ValidatorPrefs { blocked: true, ..Default::default() }
));
// attempt to nominate from 100/101...
assert_ok!(Staking::nominate(Origin::signed(100), vec![11]));
// should have worked since we're already nominated them
assert_eq!(Nominators::<Test>::get(&101).unwrap().targets, vec![11]);
// kick the nominator
assert_ok!(Staking::kick(Origin::signed(10), vec![101]));
// should have been kicked now
assert!(Nominators::<Test>::get(&101).unwrap().targets.is_empty());
// attempt to nominate from 100/101...
assert_noop!(
Staking::nominate(Origin::signed(100), vec![11]),
Error::<Test>::BadTarget
);
});
}
#[test]
fn less_than_needed_candidates_works() {
ExtBuilder::default()
.minimum_validator_count(1)
.validator_count(4)
.nominate(false)
.build_and_execute(|| {
assert_eq!(Staking::validator_count(), 4);
assert_eq!(Staking::minimum_validator_count(), 1);
assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]);
mock::start_active_era(1);
// Previous set is selected. NO election algorithm is even executed.
assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]);
// But the exposure is updated in a simple way. No external votes exists.
// This is purely self-vote.
assert!(ErasStakers::<Test>::iter_prefix_values(active_era())
.all(|exposure| exposure.others.is_empty()));
});
}
#[test]
fn no_candidate_emergency_condition() {
ExtBuilder::default()
.minimum_validator_count(1)
.validator_count(15)
.set_status(41, StakerStatus::Validator)
.nominate(false)
.build_and_execute(|| {
// initial validators
assert_eq_uvec!(validator_controllers(), vec![10, 20, 30, 40]);
let prefs = ValidatorPrefs { commission: Perbill::one(), ..Default::default() };
<Staking as crate::Store>::Validators::insert(11, prefs.clone());
// set the minimum validator count.
<Staking as crate::Store>::MinimumValidatorCount::put(10);
// try to chill
let res = Staking::chill(Origin::signed(10));
assert_ok!(res);
let current_era = CurrentEra::<Test>::get();
// try trigger new era
mock::run_to_block(20);
assert_eq!(*staking_events().last().unwrap(), Event::StakingElectionFailed);
// No new era is created
assert_eq!(current_era, CurrentEra::<Test>::get());
// Go to far further session to see if validator have changed
mock::run_to_block(100);
// Previous ones are elected. chill is not effective in active era (as era hasn't
// changed)
assert_eq_uvec!(validator_controllers(), vec![10, 20, 30, 40]);
// The chill is still pending.
assert!(!<Staking as crate::Store>::Validators::contains_key(11));
// No new era is created.
assert_eq!(current_era, CurrentEra::<Test>::get());
});
}
#[test]
fn nominating_and_rewards_should_work() {
ExtBuilder::default()
.nominate(false)
.set_status(41, StakerStatus::Validator)
.set_status(11, StakerStatus::Idle)
.set_status(31, StakerStatus::Idle)
.build_and_execute(|| {
// initial validators.
assert_eq_uvec!(validator_controllers(), vec![40, 20]);
// re-validate with 11 and 31.
assert_ok!(Staking::validate(Origin::signed(10), Default::default()));
assert_ok!(Staking::validate(Origin::signed(30), Default::default()));
// Set payee to controller.
assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller));
assert_ok!(Staking::set_payee(Origin::signed(20), RewardDestination::Controller));
assert_ok!(Staking::set_payee(Origin::signed(30), RewardDestination::Controller));
assert_ok!(Staking::set_payee(Origin::signed(40), RewardDestination::Controller));
// give the man some money
let initial_balance = 1000;
for i in [1, 2, 3, 4, 5, 10, 11, 20, 21].iter() {
let _ = Balances::make_free_balance_be(i, initial_balance);
}
// bond two account pairs and state interest in nomination.
assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller));
assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 21, 31]));
assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller));
assert_ok!(Staking::nominate(Origin::signed(4), vec![11, 21, 41]));
// the total reward for era 0
let total_payout_0 = current_total_payout_for_duration(reward_time_per_era());
Pallet::<Test>::reward_by_ids(vec![(41, 1)]);
Pallet::<Test>::reward_by_ids(vec![(21, 1)]);
mock::start_active_era(1);
// 10 and 20 have more votes, they will be chosen.
assert_eq_uvec!(validator_controllers(), vec![20, 10]);
// old validators must have already received some rewards.
let initial_balance_40 = Balances::total_balance(&40);
let mut initial_balance_20 = Balances::total_balance(&20);
mock::make_all_reward_payment(0);
assert_eq!(Balances::total_balance(&40), initial_balance_40 + total_payout_0 / 2);
assert_eq!(Balances::total_balance(&20), initial_balance_20 + total_payout_0 / 2);
initial_balance_20 = Balances::total_balance(&20);
assert_eq!(ErasStakers::<Test>::iter_prefix_values(active_era()).count(), 2);
assert_eq!(
Staking::eras_stakers(active_era(), 11),
Exposure {
total: 1000 + 800,
own: 1000,
others: vec![
IndividualExposure { who: 1, value: 400 },
IndividualExposure { who: 3, value: 400 },
]
},
);
assert_eq!(
Staking::eras_stakers(active_era(), 21),
Exposure {
total: 1000 + 1200,
own: 1000,
others: vec![
IndividualExposure { who: 1, value: 600 },
IndividualExposure { who: 3, value: 600 },
]
},
);
// the total reward for era 1
let total_payout_1 = current_total_payout_for_duration(reward_time_per_era());
Pallet::<Test>::reward_by_ids(vec![(21, 2)]);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
mock::start_active_era(2);
// nothing else will happen, era ends and rewards are paid again, it is expected that
// nominators will also be paid. See below
mock::make_all_reward_payment(1);
let payout_for_10 = total_payout_1 / 3;
let payout_for_20 = 2 * total_payout_1 / 3;
// Nominator 2: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==>
// 2/9 + 3/11
assert_eq_error_rate!(
Balances::total_balance(&2),
initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11),
2,
);
// Nominator 4: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==>
// 2/9 + 3/11
assert_eq_error_rate!(
Balances::total_balance(&4),
initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11),
2,
);
// Validator 10: got 800 / 1800 external stake => 8/18 =? 4/9 => Validator's share = 5/9
assert_eq_error_rate!(
Balances::total_balance(&10),
initial_balance + 5 * payout_for_10 / 9,
2,
);
// Validator 20: got 1200 / 2200 external stake => 12/22 =? 6/11 => Validator's share =
// 5/11
assert_eq_error_rate!(
Balances::total_balance(&20),
initial_balance_20 + 5 * payout_for_20 / 11,
2,
);
});
}
#[test]
fn nominators_also_get_slashed_pro_rata() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
let slash_percent = Perbill::from_percent(5);
let initial_exposure = Staking::eras_stakers(active_era(), 11);
// 101 is a nominator for 11
assert_eq!(initial_exposure.others.first().unwrap().who, 101);
// staked values;
let nominator_stake = Staking::ledger(100).unwrap().active;
let nominator_balance = balances(&101).0;
let validator_stake = Staking::ledger(10).unwrap().active;
let validator_balance = balances(&11).0;
let exposed_stake = initial_exposure.total;
let exposed_validator = initial_exposure.own;
let exposed_nominator = initial_exposure.others.first().unwrap().value;
// 11 goes offline
on_offence_now(
&[OffenceDetails { offender: (11, initial_exposure.clone()), reporters: vec![] }],
&[slash_percent],
);
// both stakes must have been decreased.
assert!(Staking::ledger(100).unwrap().active < nominator_stake);
assert!(Staking::ledger(10).unwrap().active < validator_stake);
let slash_amount = slash_percent * 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(100).unwrap().active, nominator_stake - nominator_share);
assert_eq!(Staking::ledger(10).unwrap().active, validator_stake - validator_share);
assert_eq!(
balances(&101).0, // free balance
nominator_balance - nominator_share,
);
assert_eq!(
balances(&11).0, // free balance
validator_balance - validator_share,
);
// Because slashing happened.
assert!(is_disabled(10));
});
}
#[test]
fn double_staking_should_fail() {
// should test (in the same order):
// * an account already bonded as stash cannot be be stashed again.
// * an account already bonded as stash cannot nominate.
// * an account already bonded as controller can nominate.
ExtBuilder::default().build_and_execute(|| {
let arbitrary_value = 5;
// 2 = controller, 1 stashed => ok
assert_ok!(Staking::bond(
Origin::signed(1),
2,
arbitrary_value,
RewardDestination::default()
));
// 4 = not used so far, 1 stashed => not allowed.
assert_noop!(
Staking::bond(Origin::signed(1), 4, arbitrary_value, RewardDestination::default()),
Error::<Test>::AlreadyBonded,
);
// 1 = stashed => attempting to nominate should fail.
assert_noop!(Staking::nominate(Origin::signed(1), vec![1]), Error::<Test>::NotController);
// 2 = controller => nominating should work.
assert_ok!(Staking::nominate(Origin::signed(2), vec![1]));
});
}
#[test]
fn double_controlling_should_fail() {
// should test (in the same order):
// * an account already bonded as controller CANNOT be reused as the controller of another
// account.
ExtBuilder::default().build_and_execute(|| {
let arbitrary_value = 5;
// 2 = controller, 1 stashed => ok
assert_ok!(Staking::bond(
Origin::signed(1),
2,
arbitrary_value,
RewardDestination::default(),
));
// 2 = controller, 3 stashed (Note that 2 is reused.) => no-op
assert_noop!(
Staking::bond(Origin::signed(3), 2, arbitrary_value, RewardDestination::default()),
Error::<Test>::AlreadyPaired,
);
});
}
#[test]
fn session_and_eras_work_simple() {
ExtBuilder::default().period(1).build_and_execute(|| {
assert_eq!(active_era(), 0);
assert_eq!(current_era(), 0);
assert_eq!(Session::current_index(), 1);
assert_eq!(System::block_number(), 1);
// Session 1: this is basically a noop. This has already been started.
start_session(1);
assert_eq!(Session::current_index(), 1);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 1);
// Session 2: No change.
start_session(2);
assert_eq!(Session::current_index(), 2);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 2);
// Session 3: Era increment.
start_session(3);
assert_eq!(Session::current_index(), 3);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 3);
// Session 4: No change.
start_session(4);
assert_eq!(Session::current_index(), 4);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 4);
// Session 5: No change.
start_session(5);
assert_eq!(Session::current_index(), 5);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 5);
// Session 6: Era increment.
start_session(6);
assert_eq!(Session::current_index(), 6);
assert_eq!(active_era(), 2);
assert_eq!(System::block_number(), 6);
});
}
#[test]
fn session_and_eras_work_complex() {
ExtBuilder::default().period(5).build_and_execute(|| {
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 0);
assert_eq!(System::block_number(), 1);
start_session(1);
assert_eq!(Session::current_index(), 1);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 5);
start_session(2);
assert_eq!(Session::current_index(), 2);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 10);
start_session(3);
assert_eq!(Session::current_index(), 3);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 15);
start_session(4);
assert_eq!(Session::current_index(), 4);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 20);
start_session(5);
assert_eq!(Session::current_index(), 5);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 25);
start_session(6);
assert_eq!(Session::current_index(), 6);
assert_eq!(active_era(), 2);
assert_eq!(System::block_number(), 30);
});
}
#[test]
fn forcing_new_era_works() {
ExtBuilder::default().build_and_execute(|| {
// normal flow of session.
start_session(1);
assert_eq!(active_era(), 0);
start_session(2);
assert_eq!(active_era(), 0);
start_session(3);
assert_eq!(active_era(), 1);
// no era change.
ForceEra::<Test>::put(Forcing::ForceNone);
start_session(4);
assert_eq!(active_era(), 1);
start_session(5);
assert_eq!(active_era(), 1);
start_session(6);
assert_eq!(active_era(), 1);
start_session(7);
assert_eq!(active_era(), 1);
// back to normal.
// this immediately starts a new session.
ForceEra::<Test>::put(Forcing::NotForcing);
start_session(8);
assert_eq!(active_era(), 1);
start_session(9);
assert_eq!(active_era(), 2);
// forceful change
ForceEra::<Test>::put(Forcing::ForceAlways);
start_session(10);
assert_eq!(active_era(), 2);
start_session(11);
assert_eq!(active_era(), 3);
start_session(12);
assert_eq!(active_era(), 4);
// just one forceful change
ForceEra::<Test>::put(Forcing::ForceNew);
start_session(13);
assert_eq!(active_era(), 5);
assert_eq!(ForceEra::<Test>::get(), Forcing::NotForcing);
start_session(14);
assert_eq!(active_era(), 6);
start_session(15);
assert_eq!(active_era(), 6);
});
}
#[test]
fn cannot_transfer_staked_balance() {
// Tests that a stash account cannot transfer funds
ExtBuilder::default().nominate(false).build_and_execute(|| {
// Confirm account 11 is stashed
assert_eq!(Staking::bonded(&11), Some(10));
// Confirm account 11 has some free balance
assert_eq!(Balances::free_balance(11), 1000);
// Confirm account 11 (via controller 10) is totally staked
assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000);
// Confirm account 11 cannot transfer as a result
assert_noop!(
Balances::transfer(Origin::signed(11), 20, 1),
BalancesError::<Test, _>::LiquidityRestrictions
);
// Give account 11 extra free balance
let _ = Balances::make_free_balance_be(&11, 10000);
// Confirm that account 11 can now transfer some balance
assert_ok!(Balances::transfer(Origin::signed(11), 20, 1));
});
}
#[test]
fn cannot_transfer_staked_balance_2() {
// Tests that a stash account cannot transfer funds
// Same test as above but with 20, and more accurate.
// 21 has 2000 free balance but 1000 at stake
ExtBuilder::default().nominate(false).build_and_execute(|| {
// Confirm account 21 is stashed
assert_eq!(Staking::bonded(&21), Some(20));
// Confirm account 21 has some free balance
assert_eq!(Balances::free_balance(21), 2000);
// Confirm account 21 (via controller 20) is totally staked
assert_eq!(Staking::eras_stakers(active_era(), 21).total, 1000);
// Confirm account 21 can transfer at most 1000
assert_noop!(
Balances::transfer(Origin::signed(21), 20, 1001),
BalancesError::<Test, _>::LiquidityRestrictions
);
assert_ok!(Balances::transfer(Origin::signed(21), 20, 1000));
});
}
#[test]
fn cannot_reserve_staked_balance() {
// Checks that a bonded account cannot reserve balance from free balance
ExtBuilder::default().build_and_execute(|| {
// Confirm account 11 is stashed
assert_eq!(Staking::bonded(&11), Some(10));
// Confirm account 11 has some free balance
assert_eq!(Balances::free_balance(11), 1000);
// Confirm account 11 (via controller 10) is totally staked
assert_eq!(Staking::eras_stakers(active_era(), 11).own, 1000);
// Confirm account 11 cannot reserve as a result
assert_noop!(Balances::reserve(&11, 1), BalancesError::<Test, _>::LiquidityRestrictions);
// Give account 11 extra free balance
let _ = Balances::make_free_balance_be(&11, 10000);
// Confirm account 11 can now reserve balance
assert_ok!(Balances::reserve(&11, 1));
});
}
#[test]
fn reward_destination_works() {
// Rewards go to the correct destination as determined in Payee
ExtBuilder::default().nominate(false).build_and_execute(|| {
// Check that account 11 is a validator
assert!(Session::validators().contains(&11));
// Check the balance of the validator account
assert_eq!(Balances::free_balance(10), 1);
// Check the balance of the stash account
assert_eq!(Balances::free_balance(11), 1000);
// Check how much is at stake
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
claimed_rewards: vec![],
})
);
// Compute total payout now for whole duration as other parameter won't change
let total_payout_0 = current_total_payout_for_duration(reward_time_per_era());
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
mock::start_active_era(1);
mock::make_all_reward_payment(0);