Newer
Older
assert_eq!(Staking::ledger(10).unwrap().total, 900);
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
#[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).build_and_execute(|| {
mock::start_active_era(1);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
let exposure = Staking::eras_stakers(active_era(), 11);
let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value;
on_offence_now(
&[OffenceDetails {
offender: (11, Staking::eras_stakers(active_era(), 11)),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
// now we chill
assert_ok!(Staking::chill(RuntimeOrigin::signed(100)));
assert_ok!(Staking::unbond(RuntimeOrigin::signed(100), 500));
assert_eq!(Staking::current_era().unwrap(), 1);
assert_eq!(active_era(), 1);
assert_eq!(
Ledger::<Test>::get(100).unwrap(),
StakingLedger {
active: 0,
total: 500,
stash: 101,
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
unlocking: bounded_vec![UnlockChunk { era: 4u32, value: 500 }],
}
);
// no slash yet.
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
// no slash yet.
mock::start_active_era(2);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
assert_eq!(Staking::current_era().unwrap(), 2);
assert_eq!(active_era(), 2);
// no slash yet.
mock::start_active_era(3);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
assert_eq!(Staking::current_era().unwrap(), 3);
assert_eq!(active_era(), 3);
// and cannot yet unbond:
assert_storage_noop!(assert!(
Staking::withdraw_unbonded(RuntimeOrigin::signed(100), 0).is_ok()
));
assert_eq!(
Ledger::<Test>::get(100).unwrap().unlocking.into_inner(),
vec![UnlockChunk { era: 4u32, value: 500 as Balance }],
);
// at the start of era 4, slashes from era 1 are processed,
// after being deferred for at least 2 full eras.
mock::start_active_era(4);
assert_eq!(Balances::free_balance(11), 900);
assert_eq!(Balances::free_balance(101), 2000 - (nominated_value / 10));
// and the leftover of the funds can now be unbonded.
})
}
#[test]
fn remove_deferred() {
ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| {
mock::start_active_era(1);
assert_eq!(Balances::free_balance(11), 1000);
let exposure = Staking::eras_stakers(active_era(), 11);
assert_eq!(Balances::free_balance(101), 2000);
let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value;
on_offence_now(
&[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }],
&[Perbill::from_percent(10)],
);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
mock::start_active_era(2);
// reported later, but deferred to start of era 4 as well.
System::reset_events();
on_offence_in_era(
&[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }],
&[Perbill::from_percent(15)],
1,
DisableStrategy::WhenSlashed,
// fails if empty
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![]),
Error::<Test>::EmptyTargets
);
assert_ok!(Staking::cancel_deferred_slash(RuntimeOrigin::root(), 4, vec![0]));
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
mock::start_active_era(3);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
// at the start of era 4, slashes from era 1 are processed,
// after being deferred for at least 2 full eras.
mock::start_active_era(4);
// the first slash for 10% was cancelled, but the 15% one not.
assert!(matches!(
staking_events_since_last_call().as_slice(),
&[
Event::SlashReported { validator: 11, slash_era: 1, .. },
..,
Event::Slashed { staker: 11, amount: 50 },
Event::Slashed { staker: 101, amount: 7 }
let slash_10 = Perbill::from_percent(10);
let slash_15 = Perbill::from_percent(15);
let initial_slash = slash_10 * nominated_value;
let total_slash = slash_15 * nominated_value;
let actual_slash = total_slash - initial_slash;
// 5% slash (15 - 10) processed now.
assert_eq!(Balances::free_balance(11), 950);
assert_eq!(Balances::free_balance(101), 2000 - actual_slash);
})
}
#[test]
fn remove_multi_deferred() {
ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| {
mock::start_active_era(1);
assert_eq!(Balances::free_balance(11), 1000);
let exposure = Staking::eras_stakers(active_era(), 11);
assert_eq!(Balances::free_balance(101), 2000);
on_offence_now(
&[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }],
&[Perbill::from_percent(10)],
);
on_offence_now(
offender: (21, Staking::eras_stakers(active_era(), 21)),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
on_offence_now(
&[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }],
&[Perbill::from_percent(25)],
);
&[OffenceDetails { offender: (42, exposure.clone()), reporters: vec![] }],
&[Perbill::from_percent(25)],
);
on_offence_now(
&[OffenceDetails { offender: (69, exposure.clone()), reporters: vec![] }],
&[Perbill::from_percent(25)],
);
assert_eq!(UnappliedSlashes::<Test>::get(&4).len(), 5);
// fails if list is not sorted
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![2, 0, 4]),
Error::<Test>::NotSortedAndUnique
);
// fails if list is not unique
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![0, 2, 2]),
Error::<Test>::NotSortedAndUnique
);
// fails if bad index
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![1, 2, 3, 4, 5]),
Error::<Test>::InvalidSlashIndex
);
assert_ok!(Staking::cancel_deferred_slash(RuntimeOrigin::root(), 4, vec![0, 2, 4]));
let slashes = UnappliedSlashes::<Test>::get(&4);
assert_eq!(slashes.len(), 2);
assert_eq!(slashes[0].validator, 21);
assert_eq!(slashes[1].validator, 42);
fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_validator() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
// 100 has approval for 11 as of now
assert!(Staking::nominators(101).unwrap().targets.contains(&11));
// 11 and 21 both have the support of 100
let exposure_11 = Staking::eras_stakers(active_era(), &11);
let exposure_21 = Staking::eras_stakers(active_era(), &21);
assert_eq!(exposure_11.total, 1000 + 125);
assert_eq!(exposure_21.total, 1000 + 375);
on_offence_now(
&[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }],
&[Perbill::from_percent(10)],
);
assert_eq!(
staking_events_since_last_call(),
vec![
Event::StakersElected,
Event::EraPaid { era_index: 0, validator_payout: 11075, remainder: 33225 },
Event::Chilled { stash: 11 },
Event::ForceEra { mode: Forcing::ForceNew },
Event::SlashReported {
validator: 11,
fraction: Perbill::from_percent(10),
slash_era: 1
},
Event::Slashed { staker: 11, amount: 100 },
Event::Slashed { staker: 101, amount: 12 },
]
);
// post-slash balance
let nominator_slash_amount_11 = 125 / 10;
assert_eq!(Balances::free_balance(11), 900);
assert_eq!(Balances::free_balance(101), 2000 - nominator_slash_amount_11);
// check that validator was chilled.
assert!(Validators::<Test>::iter().all(|(stash, _)| stash != 11));
// actually re-bond the slashed validator
assert_ok!(Staking::validate(RuntimeOrigin::signed(10), Default::default()));
mock::start_active_era(2);
let exposure_11 = Staking::eras_stakers(active_era(), &11);
let exposure_21 = Staking::eras_stakers(active_era(), &21);
// 11's own expo is reduced. sum of support from 11 is less (448), which is 500
// 900 + 146
assert!(matches!(exposure_11, Exposure { own: 900, total: 1046, .. }));
// 1000 + 342
assert!(matches!(exposure_21, Exposure { own: 1000, total: 1342, .. }));
assert_eq!(500 - 146 - 342, nominator_slash_amount_11);
}
André Silva
committed
#[test]
fn non_slashable_offence_doesnt_disable_validator() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11);
let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21);
// offence with no slash associated
on_offence_now(
&[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }],
&[Perbill::zero()],
);
// it does NOT affect the nominator.
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
André Silva
committed
// offence that slashes 25% of the bond
on_offence_now(
&[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }],
&[Perbill::from_percent(25)],
);
// it DOES NOT affect the nominator.
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
assert_eq!(
staking_events_since_last_call(),
vec![
Event::StakersElected,
Event::EraPaid { era_index: 0, validator_payout: 11075, remainder: 33225 },
Event::Chilled { stash: 11 },
Event::ForceEra { mode: Forcing::ForceNew },
Event::SlashReported {
validator: 11,
fraction: Perbill::from_percent(0),
slash_era: 1
},
Event::Chilled { stash: 21 },
Event::SlashReported {
validator: 21,
fraction: Perbill::from_percent(25),
slash_era: 1
},
Event::Slashed { staker: 21, amount: 250 },
Event::Slashed { staker: 101, amount: 94 }
]
);
André Silva
committed
// the offence for validator 10 wasn't slashable so it wasn't disabled
assert!(!is_disabled(10));
// whereas validator 20 gets disabled
assert!(is_disabled(20));
});
}
#[test]
fn slashing_independent_of_disabling_validator() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11);
let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21);
let now = Staking::active_era().unwrap().index;
// offence with no slash associated, BUT disabling
on_offence_in_era(
&[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }],
&[Perbill::zero()],
now,
DisableStrategy::Always,
);
// nomination remains untouched.
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
// offence that slashes 25% of the bond, BUT not disabling
on_offence_in_era(
&[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }],
&[Perbill::from_percent(25)],
now,
DisableStrategy::Never,
);
// nomination remains untouched.
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
assert_eq!(
staking_events_since_last_call(),
vec![
Event::StakersElected,
Event::EraPaid { era_index: 0, validator_payout: 11075, remainder: 33225 },
Event::Chilled { stash: 11 },
Event::ForceEra { mode: Forcing::ForceNew },
Event::SlashReported {
validator: 11,
fraction: Perbill::from_percent(0),
slash_era: 1
},
Event::Chilled { stash: 21 },
Event::SlashReported {
validator: 21,
fraction: Perbill::from_percent(25),
slash_era: 1
},
Event::Slashed { staker: 21, amount: 250 },
Event::Slashed { staker: 101, amount: 94 }
]
);
// the offence for validator 10 was explicitly disabled
assert!(is_disabled(10));
// whereas validator 20 is explicitly not disabled
assert!(!is_disabled(20));
});
}
André Silva
committed
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
#[test]
fn offence_threshold_triggers_new_era() {
ExtBuilder::default()
.validator_count(4)
.set_status(41, StakerStatus::Validator)
.build_and_execute(|| {
mock::start_active_era(1);
assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41]);
assert_eq!(
<Test as Config>::OffendingValidatorsThreshold::get(),
Perbill::from_percent(75),
);
// we have 4 validators and an offending validator threshold of 75%,
// once the third validator commits an offence a new era should be forced
let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11);
let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21);
let exposure_31 = Staking::eras_stakers(Staking::active_era().unwrap().index, &31);
on_offence_now(
&[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }],
&[Perbill::zero()],
);
assert_eq!(ForceEra::<Test>::get(), Forcing::NotForcing);
on_offence_now(
&[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }],
&[Perbill::zero()],
);
assert_eq!(ForceEra::<Test>::get(), Forcing::NotForcing);
on_offence_now(
&[OffenceDetails { offender: (31, exposure_31.clone()), reporters: vec![] }],
&[Perbill::zero()],
);
assert_eq!(ForceEra::<Test>::get(), Forcing::ForceNew);
});
}
#[test]
fn disabled_validators_are_kept_disabled_for_whole_era() {
ExtBuilder::default()
.validator_count(4)
.set_status(41, StakerStatus::Validator)
.build_and_execute(|| {
mock::start_active_era(1);
assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41]);
assert_eq!(<Test as Config>::SessionsPerEra::get(), 3);
let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11);
let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21);
on_offence_now(
&[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }],
&[Perbill::zero()],
);
on_offence_now(
&[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }],
&[Perbill::from_percent(25)],
);
// nominations are not updated.
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
André Silva
committed
// validator 10 should not be disabled since the offence wasn't slashable
assert!(!is_disabled(10));
// validator 20 gets disabled since it got slashed
assert!(is_disabled(20));
advance_session();
// disabled validators should carry-on through all sessions in the era
assert!(!is_disabled(10));
assert!(is_disabled(20));
// validator 10 should now get disabled
on_offence_now(
&[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }],
&[Perbill::from_percent(25)],
);
// nominations are not updated.
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
André Silva
committed
advance_session();
// and both are disabled in the last session of the era
assert!(is_disabled(10));
assert!(is_disabled(20));
mock::start_active_era(2);
// when a new era starts disabled validators get cleared
assert!(!is_disabled(10));
assert!(!is_disabled(20));
});
}
#[test]
fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() {
// should check that:
// * rewards get paid until history_depth for both validators and nominators
// * an invalid era to claim doesn't update last_reward
// * double claim of one era fails
ExtBuilder::default().nominate(true).build_and_execute(|| {
// Consumed weight for all payout_stakers dispatches that fail
let err_weight = <Test as Config>::WeightInfo::payout_stakers_alive_staked(0);
let init_balance_10 = Balances::total_balance(&10);
let init_balance_100 = Balances::total_balance(&100);
let part_for_10 = Perbill::from_rational::<u32>(1000, 1125);
let part_for_100 = Perbill::from_rational::<u32>(125, 1125);
// Check state
Payee::<Test>::insert(11, RewardDestination::Controller);
Payee::<Test>::insert(101, RewardDestination::Controller);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
// 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());
mock::start_active_era(1);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
// Change total issuance in order to modify total payout
let _ = Balances::deposit_creating(&999, 1_000_000_000);
// 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);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
// Change total issuance in order to modify total payout
let _ = Balances::deposit_creating(&999, 1_000_000_000);
// Compute total payout now for whole duration as other parameter won't change
let total_payout_2 = current_total_payout_for_duration(reward_time_per_era());
assert!(total_payout_2 != total_payout_0);
assert!(total_payout_2 != total_payout_1);
mock::start_active_era(HistoryDepth::get() + 1);
// This is the latest planned era in staking, not the active era
let current_era = Staking::current_era().unwrap();
// Last kept is 1:
assert!(current_era - HistoryDepth::get() == 1);
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 0),
Error::<Test>::InvalidEraToReward.with_weight(err_weight)
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 1));
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 2));
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 2),
Error::<Test>::AlreadyClaimed.with_weight(err_weight)
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, active_era),
Error::<Test>::InvalidEraToReward.with_weight(err_weight)
// Era 0 can't be rewarded anymore and current era can't be rewarded yet
// only era 1 and 2 can be rewarded.
assert_eq!(
Balances::total_balance(&10),
init_balance_10 + part_for_10 * (total_payout_1 + total_payout_2),
);
assert_eq!(
Balances::total_balance(&100),
init_balance_100 + part_for_100 * (total_payout_1 + total_payout_2),
);
});
}
#[test]
fn zero_slash_keeps_nominators() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
assert_eq!(Balances::free_balance(11), 1000);
let exposure = Staking::eras_stakers(active_era(), 11);
assert_eq!(Balances::free_balance(101), 2000);
on_offence_now(
&[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }],
&[Perbill::from_percent(0)],
);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
// 11 is still removed..
assert!(Validators::<Test>::iter().all(|(stash, _)| stash != 11));
// but their nominations are kept.
assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]);
});
}
ExtBuilder::default().initialize_first_session(false).build_and_execute(|| {
use pallet_session::SessionManager;
let val_set = Session::validators();
let init_session = Session::current_index();
let init_active_era = active_era();
// pallet-session is delaying session by one, thus the next session to plan is +2.
assert_eq!(<Staking as SessionManager<_>>::new_session(init_session + 2), None);
assert_eq!(
<Staking as SessionManager<_>>::new_session(init_session + 3),
Some(val_set.clone())
);
assert_eq!(<Staking as SessionManager<_>>::new_session(init_session + 4), None);
assert_eq!(<Staking as SessionManager<_>>::new_session(init_session + 5), None);
assert_eq!(
<Staking as SessionManager<_>>::new_session(init_session + 6),
Some(val_set.clone())
);
<Staking as SessionManager<_>>::end_session(init_session);
<Staking as SessionManager<_>>::start_session(init_session + 1);
assert_eq!(active_era(), init_active_era);
<Staking as SessionManager<_>>::end_session(init_session + 1);
<Staking as SessionManager<_>>::start_session(init_session + 2);
assert_eq!(active_era(), init_active_era);
// Reward current era
Staking::reward_by_ids(vec![(11, 1)]);
// New active era is triggered here.
<Staking as SessionManager<_>>::end_session(init_session + 2);
<Staking as SessionManager<_>>::start_session(init_session + 3);
assert_eq!(active_era(), init_active_era + 1);
<Staking as SessionManager<_>>::end_session(init_session + 3);
<Staking as SessionManager<_>>::start_session(init_session + 4);
assert_eq!(active_era(), init_active_era + 1);
<Staking as SessionManager<_>>::end_session(init_session + 4);
<Staking as SessionManager<_>>::start_session(init_session + 5);
assert_eq!(active_era(), init_active_era + 1);
// Reward current era
Staking::reward_by_ids(vec![(21, 2)]);
// New active era is triggered here.
<Staking as SessionManager<_>>::end_session(init_session + 5);
<Staking as SessionManager<_>>::start_session(init_session + 6);
assert_eq!(active_era(), init_active_era + 2);
// That reward are correct
assert_eq!(Staking::eras_reward_points(init_active_era).total, 1);
assert_eq!(Staking::eras_reward_points(init_active_era + 1).total, 2);
});
}
#[test]
fn test_max_nominator_rewarded_per_validator_and_cant_steal_someone_else_reward() {
ExtBuilder::default().build_and_execute(|| {
for i in 0..=<<Test as Config>::MaxNominatorRewardedPerValidator as Get<_>>::get() {
let stash = 10_000 + i as AccountId;
let controller = 20_000 + i as AccountId;
let balance = 10_000 + i as Balance;
assert_ok!(Staking::bond(
controller,
balance,
RewardDestination::Stash
));
assert_ok!(Staking::nominate(RuntimeOrigin::signed(controller), vec![11]));
mock::start_active_era(1);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
// compute and ensure the reward amount is greater than zero.
let _ = current_total_payout_for_duration(reward_time_per_era());
mock::start_active_era(2);
mock::make_all_reward_payment(1);
// Assert only nominators from 1 to Max are rewarded
for i in 0..=<<Test as Config>::MaxNominatorRewardedPerValidator as Get<_>>::get() {
let stash = 10_000 + i as AccountId;
let balance = 10_000 + i as Balance;
if stash == 10_000 {
assert!(Balances::free_balance(&stash) == balance);
} else {
assert!(Balances::free_balance(&stash) > balance);
}
}
});
}
// Test that payout_stakers work in general, including that only the top
// `T::MaxNominatorRewardedPerValidator` nominators are rewarded.
ExtBuilder::default().has_stakers(false).build_and_execute(|| {
// Track the exposure of the validator and all nominators.
let mut total_exposure = balance;
// Track the exposure of the validator and the nominators that will get paid out.
let mut payout_exposure = balance;
bond_validator(11, 10, balance); // Default(64)
assert_eq!(Validators::<Test>::count(), 1);
// Create nominators, targeting stash of validators
for i in 0..100 {
let bond_amount = balance + i as Balance;
bond_nominator(1000 + i, 100 + i, bond_amount, vec![11]);
total_exposure += bond_amount;
if i >= 36 {
payout_exposure += bond_amount;
};
let payout_exposure_part = Perbill::from_rational(payout_exposure, total_exposure);
mock::start_active_era(1);
// compute and ensure the reward amount is greater than zero.
let payout = current_total_payout_for_duration(reward_time_per_era());
let actual_paid_out = payout_exposure_part * payout;
mock::start_active_era(2);
let pre_payout_total_issuance = Balances::total_issuance();
RewardOnUnbalanceWasCalled::set(false);
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 1));
assert_eq_error_rate!(
Balances::total_issuance(),
pre_payout_total_issuance + actual_paid_out,
1
);
assert!(RewardOnUnbalanceWasCalled::get());
// Top 64 nominators of validator 11 automatically paid out, including the validator
// Validator payout goes to controller.
assert!(Balances::free_balance(&10) > balance);
for i in 36..100 {
assert!(Balances::free_balance(&(100 + i)) > balance + i as Balance);
}
// The bottom 36 do not
for i in 0..36 {
assert_eq!(Balances::free_balance(&(100 + i)), balance + i as Balance);
}
// We track rewards in `claimed_rewards` vec
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
);
for i in 3..16 {
Staking::reward_by_ids(vec![(11, 1)]);
// compute and ensure the reward amount is greater than zero.
let payout = current_total_payout_for_duration(reward_time_per_era());
let actual_paid_out = payout_exposure_part * payout;
let pre_payout_total_issuance = Balances::total_issuance();
mock::start_active_era(i);
RewardOnUnbalanceWasCalled::set(false);
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, i - 1));
assert_eq_error_rate!(
Balances::total_issuance(),
pre_payout_total_issuance + actual_paid_out,
1
);
assert!(RewardOnUnbalanceWasCalled::get());
}
// We track rewards in `claimed_rewards` vec
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
claimed_rewards: (1..=14).collect::<Vec<_>>().try_into().unwrap()
let last_era = 99;
let history_depth = HistoryDepth::get();
let expected_last_reward_era = last_era - 1;
let expected_start_reward_era = last_era - history_depth;
for i in 16..=last_era {
// compute and ensure the reward amount is greater than zero.
let _ = current_total_payout_for_duration(reward_time_per_era());
mock::start_active_era(i);
}
// We clean it up as history passes
assert_ok!(Staking::payout_stakers(
RuntimeOrigin::signed(1337),
11,
expected_start_reward_era
));
assert_ok!(Staking::payout_stakers(
RuntimeOrigin::signed(1337),
11,
expected_last_reward_era
));
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
claimed_rewards: bounded_vec![expected_start_reward_era, expected_last_reward_era]
);
// Out of order claims works.
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 69));
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 23));
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 42));
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
claimed_rewards: bounded_vec![
expected_start_reward_era,
23,
42,
69,
expected_last_reward_era
]
);
});
}
#[test]
fn payout_stakers_handles_basic_errors() {
// Here we will test payouts handle all errors.
ExtBuilder::default().has_stakers(false).build_and_execute(|| {
// Consumed weight for all payout_stakers dispatches that fail
let err_weight = <Test as Config>::WeightInfo::payout_stakers_alive_staked(0);
// Same setup as the test above
let balance = 1000;
bond_validator(11, 10, balance); // Default(64)
// Create nominators, targeting stash
for i in 0..100 {
bond_nominator(1000 + i, 100 + i, balance + i as Balance, vec![11]);
mock::start_active_era(1);
// compute and ensure the reward amount is greater than zero.
let _ = current_total_payout_for_duration(reward_time_per_era());
mock::start_active_era(2);
assert_noop!(
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, 2),
Error::<Test>::InvalidEraToReward.with_weight(err_weight)
);
assert_noop!(
Staking::payout_stakers(RuntimeOrigin::signed(1337), 10, 1),
Error::<Test>::NotStash.with_weight(err_weight)
);
let last_era = 99;
for i in 3..=last_era {
// compute and ensure the reward amount is greater than zero.
let _ = current_total_payout_for_duration(reward_time_per_era());
mock::start_active_era(i);
let history_depth = HistoryDepth::get();
let expected_last_reward_era = last_era - 1;
let expected_start_reward_era = last_era - history_depth;
// We are at era last_era=99. Given history_depth=80, we should be able
// to payout era starting from expected_start_reward_era=19 through
// expected_last_reward_era=98 (80 total eras), but not 18 or 99.
assert_noop!(
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_start_reward_era - 1),
Error::<Test>::InvalidEraToReward.with_weight(err_weight)
);
assert_noop!(
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_last_reward_era + 1),
Error::<Test>::InvalidEraToReward.with_weight(err_weight)
);
assert_ok!(Staking::payout_stakers(
RuntimeOrigin::signed(1337),
11,
expected_start_reward_era
));
assert_ok!(Staking::payout_stakers(
RuntimeOrigin::signed(1337),
11,
expected_last_reward_era
));
assert_noop!(
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_start_reward_era),
Error::<Test>::AlreadyClaimed.with_weight(err_weight)
);
assert_noop!(
Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, expected_last_reward_era),
Error::<Test>::AlreadyClaimed.with_weight(err_weight)
);
});
}
#[test]
fn payout_stakers_handles_weight_refund() {
// Note: this test relies on the assumption that `payout_stakers_alive_staked` is solely used by
// `payout_stakers` to calculate the weight of each payout op.
ExtBuilder::default().has_stakers(false).build_and_execute(|| {
let max_nom_rewarded =
<<Test as Config>::MaxNominatorRewardedPerValidator as Get<_>>::get();
// Make sure the configured value is meaningful for our use.
assert!(max_nom_rewarded >= 4);
let half_max_nom_rewarded = max_nom_rewarded / 2;
// Sanity check our max and half max nominator quantities.
assert!(half_max_nom_rewarded > 0);
assert!(max_nom_rewarded > half_max_nom_rewarded);
let max_nom_rewarded_weight =
<Test as Config>::WeightInfo::payout_stakers_alive_staked(max_nom_rewarded);
let half_max_nom_rewarded_weight =
<Test as Config>::WeightInfo::payout_stakers_alive_staked(half_max_nom_rewarded);
let zero_nom_payouts_weight = <Test as Config>::WeightInfo::payout_stakers_alive_staked(0);
assert!(zero_nom_payouts_weight.any_gt(Weight::zero()));
assert!(half_max_nom_rewarded_weight.any_gt(zero_nom_payouts_weight));
assert!(max_nom_rewarded_weight.any_gt(half_max_nom_rewarded_weight));
let balance = 1000;
bond_validator(11, 10, balance);
start_active_era(1);
// Reward just the validator.
Staking::reward_by_ids(vec![(11, 1)]);
// Add some `half_max_nom_rewarded` nominators who will start backing the validator in the
// next era.
for i in 0..half_max_nom_rewarded {
bond_nominator((1000 + i).into(), (100 + i).into(), balance + i as Balance, vec![11]);
}
start_active_era(2);
// Collect payouts when there are no nominators
let call = TestCall::Staking(StakingCall::payout_stakers { validator_stash: 11, era: 1 });
let info = call.get_dispatch_info();
let result = call.dispatch(RuntimeOrigin::signed(20));
assert_ok!(result);
assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight);