Newer
Older
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
#[test]
fn nomination_quota_max_changes_decoding() {
use frame_election_provider_support::ElectionDataProvider;
ExtBuilder::default()
.add_staker(60, 61, 10, StakerStatus::Nominator(vec![1]))
.add_staker(70, 71, 10, StakerStatus::Nominator(vec![1, 2, 3]))
.add_staker(30, 330, 10, StakerStatus::Nominator(vec![1, 2, 3, 4]))
.add_staker(50, 550, 10, StakerStatus::Nominator(vec![1, 2, 3, 4]))
.balance_factor(10)
.build_and_execute(|| {
// pre-condition.
assert_eq!(MaxNominationsOf::<Test>::get(), 16);
let unbonded_election = DataProviderBounds::default();
assert_eq!(
Nominators::<Test>::iter()
.map(|(k, n)| (k, n.targets.len()))
.collect::<Vec<_>>(),
vec![(70, 3), (101, 2), (50, 4), (30, 4), (60, 1)]
);
// 4 validators and 4 nominators
assert_eq!(Staking::electing_voters(unbonded_election).unwrap().len(), 4 + 4);
});
}
#[test]
fn api_nominations_quota_works() {
ExtBuilder::default().build_and_execute(|| {
assert_eq!(Staking::api_nominations_quota(10), MaxNominationsOf::<Test>::get());
assert_eq!(Staking::api_nominations_quota(333), MaxNominationsOf::<Test>::get());
assert_eq!(Staking::api_nominations_quota(222), 2);
assert_eq!(Staking::api_nominations_quota(111), 1);
})
}
mod sorted_list_provider {
use super::*;
use frame_election_provider_support::SortedListProvider;
#[test]
fn re_nominate_does_not_change_counters_or_list() {
ExtBuilder::default().nominate(true).build_and_execute(|| {
// given
Kian Paimani
committed
let pre_insert_voter_count =
(Nominators::<Test>::count() + Validators::<Test>::count()) as u32;
assert_eq!(<Test as Config>::VoterList::count(), pre_insert_voter_count);
assert_eq!(
<Test as Config>::VoterList::iter().collect::<Vec<_>>(),
vec![11, 21, 31, 101]
);
// when account 101 renominates
assert_ok!(Staking::nominate(RuntimeOrigin::signed(101), vec![41]));
// then counts don't change
Kian Paimani
committed
assert_eq!(<Test as Config>::VoterList::count(), pre_insert_voter_count);
// and the list is the same
assert_eq!(
<Test as Config>::VoterList::iter().collect::<Vec<_>>(),
vec![11, 21, 31, 101]
);
});
}
#[test]
fn re_validate_does_not_change_counters_or_list() {
ExtBuilder::default().nominate(false).build_and_execute(|| {
// given
let pre_insert_voter_count =
(Nominators::<Test>::count() + Validators::<Test>::count()) as u32;
assert_eq!(<Test as Config>::VoterList::count(), pre_insert_voter_count);
assert_eq!(<Test as Config>::VoterList::iter().collect::<Vec<_>>(), vec![11, 21, 31]);
// when account 11 re-validates
assert_ok!(Staking::validate(RuntimeOrigin::signed(11), Default::default()));
Kian Paimani
committed
// then counts don't change
assert_eq!(<Test as Config>::VoterList::count(), pre_insert_voter_count);
// and the list is the same
Kian Paimani
committed
assert_eq!(<Test as Config>::VoterList::iter().collect::<Vec<_>>(), vec![11, 21, 31]);
});
}
}
#[test]
fn force_apply_min_commission_works() {
let prefs = |c| ValidatorPrefs { commission: Perbill::from_percent(c), blocked: false };
let validators = || Validators::<Test>::iter().collect::<Vec<_>>();
ExtBuilder::default().build_and_execute(|| {
assert_ok!(Staking::validate(RuntimeOrigin::signed(31), prefs(10)));
assert_ok!(Staking::validate(RuntimeOrigin::signed(21), prefs(5)));
// Given
assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]);
MinCommission::<Test>::set(Perbill::from_percent(5));
// When applying to a commission greater than min
assert_ok!(Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 31));
// Then the commission is not changed
assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]);
// When applying to a commission that is equal to min
assert_ok!(Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 21));
// Then the commission is not changed
assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]);
// When applying to a commission that is less than the min
assert_ok!(Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 11));
// Then the commission is bumped to the min
assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(5))]);
// When applying commission to a validator that doesn't exist then storage is not altered
assert_noop!(
Staking::force_apply_min_commission(RuntimeOrigin::signed(1), 420),
Error::<Test>::NotStash
);
});
}
#[test]
fn proportional_slash_stop_slashing_if_remaining_zero() {
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::<Test>::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);
}
fn proportional_ledger_slash_works() {
let c = |era, value| UnlockChunk::<Balance> { era, value };
// Given
let mut ledger = StakingLedger::<Test>::new(123, 10);
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
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)]));
NingLin-P
committed
// 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)]));
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
// 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
),
);
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
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
* 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
NingLin-P
committed
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;
NingLin-P
committed
let ratio =
Perquintill::from_rational_with_rounding(slash, affected_balance, Rounding::Up).unwrap();
// `unit` after the slash is applied
let unit_slashed = {
NingLin-P
committed
let unit_slash = ratio.mul_ceil(unit);
unit - unit_slash
};
let value_slashed = {
NingLin-P
committed
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)])
Ankan
committed
#[test]
fn reducing_max_unlocking_chunks_abrupt() {
// Concern is on validators only
// By Default 11, 10 are stash and ctlr and 21,20
Ankan
committed
ExtBuilder::default().build_and_execute(|| {
// given a staker at era=10 and MaxUnlockChunks set to 2
MaxUnlockingChunks::set(2);
start_active_era(10);
assert_ok!(Staking::bond(RuntimeOrigin::signed(3), 300, RewardDestination::Staked));
assert!(matches!(Staking::ledger(3.into()), Ok(_)));
Ankan
committed
// when staker unbonds
assert_ok!(Staking::unbond(RuntimeOrigin::signed(3), 20));
Ankan
committed
// then an unlocking chunk is added at `current_era + bonding_duration`
// => 10 + 3 = 13
let expected_unlocking: BoundedVec<UnlockChunk<Balance>, MaxUnlockingChunks> =
bounded_vec![UnlockChunk { value: 20 as Balance, era: 13 as EraIndex }];
assert!(matches!(Staking::ledger(3.into()),
Ok(StakingLedger {
Ankan
committed
unlocking,
..
}) if unlocking==expected_unlocking));
// when staker unbonds at next era
start_active_era(11);
assert_ok!(Staking::unbond(RuntimeOrigin::signed(3), 50));
Ankan
committed
// then another unlock chunk is added
let expected_unlocking: BoundedVec<UnlockChunk<Balance>, MaxUnlockingChunks> =
bounded_vec![UnlockChunk { value: 20, era: 13 }, UnlockChunk { value: 50, era: 14 }];
assert!(matches!(Staking::ledger(3.into()),
Ok(StakingLedger {
Ankan
committed
unlocking,
..
}) if unlocking==expected_unlocking));
// when staker unbonds further
start_active_era(12);
// then further unbonding not possible
assert_noop!(Staking::unbond(RuntimeOrigin::signed(3), 20), Error::<Test>::NoMoreChunks);
Ankan
committed
// when max unlocking chunks is reduced abruptly to a low value
MaxUnlockingChunks::set(1);
// then unbond, rebond ops are blocked with ledger in corrupt state
assert_noop!(Staking::unbond(RuntimeOrigin::signed(3), 20), Error::<Test>::NotController);
assert_noop!(Staking::rebond(RuntimeOrigin::signed(3), 100), Error::<Test>::NotController);
Ankan
committed
// reset the ledger corruption
MaxUnlockingChunks::set(2);
})
}
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
#[test]
fn cannot_set_unsupported_validator_count() {
ExtBuilder::default().build_and_execute(|| {
MaxWinners::set(50);
// set validator count works
assert_ok!(Staking::set_validator_count(RuntimeOrigin::root(), 30));
assert_ok!(Staking::set_validator_count(RuntimeOrigin::root(), 50));
// setting validator count above 100 does not work
assert_noop!(
Staking::set_validator_count(RuntimeOrigin::root(), 51),
Error::<Test>::TooManyValidators,
);
})
}
#[test]
fn increase_validator_count_errors() {
ExtBuilder::default().build_and_execute(|| {
MaxWinners::set(50);
assert_ok!(Staking::set_validator_count(RuntimeOrigin::root(), 40));
// increase works
assert_ok!(Staking::increase_validator_count(RuntimeOrigin::root(), 6));
assert_eq!(ValidatorCount::<Test>::get(), 46);
// errors
assert_noop!(
Staking::increase_validator_count(RuntimeOrigin::root(), 5),
Error::<Test>::TooManyValidators,
);
})
}
#[test]
fn scale_validator_count_errors() {
ExtBuilder::default().build_and_execute(|| {
MaxWinners::set(50);
assert_ok!(Staking::set_validator_count(RuntimeOrigin::root(), 20));
// scale value works
assert_ok!(Staking::scale_validator_count(
RuntimeOrigin::root(),
Percent::from_percent(200)
));
assert_eq!(ValidatorCount::<Test>::get(), 40);
// errors
assert_noop!(
Staking::scale_validator_count(RuntimeOrigin::root(), Percent::from_percent(126)),
Error::<Test>::TooManyValidators,
);
})
}
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
#[test]
fn set_min_commission_works_with_admin_origin() {
ExtBuilder::default().build_and_execute(|| {
// no minimum commission set initially
assert_eq!(MinCommission::<Test>::get(), Zero::zero());
// root can set min commission
assert_ok!(Staking::set_min_commission(RuntimeOrigin::root(), Perbill::from_percent(10)));
assert_eq!(MinCommission::<Test>::get(), Perbill::from_percent(10));
// Non privileged origin can not set min_commission
assert_noop!(
Staking::set_min_commission(RuntimeOrigin::signed(2), Perbill::from_percent(15)),
BadOrigin
);
// Admin Origin can set min commission
assert_ok!(Staking::set_min_commission(
RuntimeOrigin::signed(1),
Perbill::from_percent(15),
));
// setting commission below min_commission fails
assert_noop!(
Staking::validate(
RuntimeOrigin::signed(11),
ValidatorPrefs { commission: Perbill::from_percent(14), blocked: false }
),
Error::<Test>::CommissionTooLow
);
// setting commission >= min_commission works
assert_ok!(Staking::validate(
RuntimeOrigin::signed(11),
ValidatorPrefs { commission: Perbill::from_percent(15), blocked: false }
));
})
}
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
#[test]
fn can_page_exposure() {
let mut others: Vec<IndividualExposure<AccountId, Balance>> = vec![];
let mut total_stake: Balance = 0;
// 19 nominators
for i in 1..20 {
let individual_stake: Balance = 100 * i as Balance;
others.push(IndividualExposure { who: i, value: individual_stake });
total_stake += individual_stake;
}
let own_stake: Balance = 500;
total_stake += own_stake;
assert_eq!(total_stake, 19_500);
// build full exposure set
let exposure: Exposure<AccountId, Balance> =
Exposure { total: total_stake, own: own_stake, others };
// when
let (exposure_metadata, exposure_page): (
PagedExposureMetadata<Balance>,
Vec<ExposurePage<AccountId, Balance>>,
) = exposure.clone().into_pages(3);
// then
// 7 pages of nominators.
assert_eq!(exposure_page.len(), 7);
assert_eq!(exposure_metadata.page_count, 7);
// first page stake = 100 + 200 + 300
assert!(matches!(exposure_page[0], ExposurePage { page_total: 600, .. }));
// second page stake = 0 + 400 + 500 + 600
assert!(matches!(exposure_page[1], ExposurePage { page_total: 1500, .. }));
// verify overview has the total
assert_eq!(exposure_metadata.total, 19_500);
// verify total stake is same as in the original exposure.
assert_eq!(
exposure_page.iter().map(|a| a.page_total).reduce(|a, b| a + b).unwrap(),
19_500 - exposure_metadata.own
);
// verify own stake is correct
assert_eq!(exposure_metadata.own, 500);
// verify number of nominators are same as in the original exposure.
assert_eq!(exposure_page.iter().map(|a| a.others.len()).reduce(|a, b| a + b).unwrap(), 19);
assert_eq!(exposure_metadata.nominator_count, 19);
}
#[test]
fn should_retain_era_info_only_upto_history_depth() {
ExtBuilder::default().build_and_execute(|| {
// remove existing exposure
Pallet::<Test>::clear_era_information(0);
let validator_stash = 10;
for era in 0..4 {
ClaimedRewards::<Test>::insert(era, &validator_stash, vec![0, 1, 2]);
for page in 0..3 {
ErasStakersPaged::<Test>::insert(
(era, &validator_stash, page),
ExposurePage { page_total: 100, others: vec![] },
);
}
}
for i in 0..4 {
// Count of entries remaining in ClaimedRewards = total - cleared_count
assert_eq!(ClaimedRewards::<Test>::iter().count(), (4 - i));
// 1 claimed_rewards entry for each era
assert_eq!(ClaimedRewards::<Test>::iter_prefix(i as EraIndex).count(), 1);
// 3 entries (pages) for each era
assert_eq!(ErasStakersPaged::<Test>::iter_prefix((i as EraIndex,)).count(), 3);
// when clear era info
Pallet::<Test>::clear_era_information(i as EraIndex);
// then all era entries are cleared
assert_eq!(ClaimedRewards::<Test>::iter_prefix(i as EraIndex).count(), 0);
assert_eq!(ErasStakersPaged::<Test>::iter_prefix((i as EraIndex,)).count(), 0);
}
});
}
#[test]
fn test_legacy_claimed_rewards_is_checked_at_reward_payout() {
ExtBuilder::default().has_stakers(false).build_and_execute(|| {
// Create a validator:
bond_validator(11, 1000);
// reward validator for next 2 eras
mock::start_active_era(1);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
mock::start_active_era(2);
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
mock::start_active_era(3);
//verify rewards are not claimed
assert_eq!(
EraInfo::<Test>::is_rewards_claimed_with_legacy_fallback(
1,
Staking::ledger(11.into()).as_ref().unwrap(),
&11,
0
),
false
);
assert_eq!(
EraInfo::<Test>::is_rewards_claimed_with_legacy_fallback(
2,
Staking::ledger(11.into()).as_ref().unwrap(),
&11,
0
),
false
);
// assume reward claim for era 1 was stored in legacy storage
Ledger::<Test>::insert(
11,
StakingLedgerInspect {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
legacy_claimed_rewards: bounded_vec![1],
},
);
// verify rewards for era 1 cannot be claimed
assert_noop!(
Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, 1, 0),
Error::<Test>::AlreadyClaimed
.with_weight(<Test as Config>::WeightInfo::payout_stakers_alive_staked(0)),
);
assert_eq!(
EraInfo::<Test>::is_rewards_claimed_with_legacy_fallback(
1,
Staking::ledger(11.into()).as_ref().unwrap(),
&11,
0
),
true
);
// verify rewards for era 2 can be claimed
assert_ok!(Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, 2, 0));
assert_eq!(
EraInfo::<Test>::is_rewards_claimed_with_legacy_fallback(
2,
Staking::ledger(11.into()).as_ref().unwrap(),
&11,
0
),
true
);
// but the new claimed rewards for era 2 is not stored in legacy storage
assert_eq!(
Ledger::<Test>::get(11).unwrap(),
StakingLedgerInspect {
stash: 11,
total: 1000,
active: 1000,
unlocking: Default::default(),
legacy_claimed_rewards: bounded_vec![1],
},
);
// instead it is kept in `ClaimedRewards`
assert_eq!(ClaimedRewards::<Test>::get(2, 11), vec![0]);
});
}
#[test]
fn test_validator_exposure_is_backward_compatible_with_non_paged_rewards_payout() {
ExtBuilder::default().has_stakers(false).build_and_execute(|| {
// case 1: exposure exist in clipped.
// set page cap to 10
MaxExposurePageSize::set(10);
bond_validator(11, 1000);
let mut expected_individual_exposures: Vec<IndividualExposure<AccountId, Balance>> = vec![];
let mut total_exposure: Balance = 0;
// 1st exposure page
for i in 0..10 {
let who = 1000 + i;
let value = 1000 + i as Balance;
bond_nominator(who, value, vec![11]);
expected_individual_exposures.push(IndividualExposure { who, value });
total_exposure += value;
}
for i in 10..15 {
let who = 1000 + i;
let value = 1000 + i as Balance;
bond_nominator(who, value, vec![11]);
expected_individual_exposures.push(IndividualExposure { who, value });
total_exposure += value;
}
mock::start_active_era(1);
// reward validator for current era
Pallet::<Test>::reward_by_ids(vec![(11, 1)]);
// start new era
mock::start_active_era(2);
// verify exposure for era 1 is stored in paged storage, that each exposure is stored in
// one and only one page, and no exposure is repeated.
let actual_exposure_page_0 = ErasStakersPaged::<Test>::get((1, 11, 0)).unwrap();
let actual_exposure_page_1 = ErasStakersPaged::<Test>::get((1, 11, 1)).unwrap();
expected_individual_exposures.iter().for_each(|exposure| {
assert!(
actual_exposure_page_0.others.contains(exposure) ||
actual_exposure_page_1.others.contains(exposure)
);
});
assert_eq!(
expected_individual_exposures.len(),
actual_exposure_page_0.others.len() + actual_exposure_page_1.others.len()
);
// verify `EraInfo` returns page from paged storage
assert_eq!(
EraInfo::<Test>::get_paged_exposure(1, &11, 0).unwrap().others(),
&actual_exposure_page_0.others
);
assert_eq!(
EraInfo::<Test>::get_paged_exposure(1, &11, 1).unwrap().others(),
&actual_exposure_page_1.others
);
assert_eq!(EraInfo::<Test>::get_page_count(1, &11), 2);
// validator is exposed
assert!(<Staking as sp_staking::StakingInterface>::is_exposed_in_era(&11, &1));
// nominators are exposed
for i in 10..15 {
let who: AccountId = 1000 + i;
assert!(<Staking as sp_staking::StakingInterface>::is_exposed_in_era(&who, &1));
}
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
// case 2: exposure exist in ErasStakers and ErasStakersClipped (legacy).
// delete paged storage and add exposure to clipped storage
<ErasStakersPaged<Test>>::remove((1, 11, 0));
<ErasStakersPaged<Test>>::remove((1, 11, 1));
<ErasStakersOverview<Test>>::remove(1, 11);
<ErasStakers<Test>>::insert(
1,
11,
Exposure {
total: total_exposure,
own: 1000,
others: expected_individual_exposures.clone(),
},
);
let mut clipped_exposure = expected_individual_exposures.clone();
clipped_exposure.sort_by(|a, b| b.who.cmp(&a.who));
clipped_exposure.truncate(10);
<ErasStakersClipped<Test>>::insert(
1,
11,
Exposure { total: total_exposure, own: 1000, others: clipped_exposure.clone() },
);
// verify `EraInfo` returns exposure from clipped storage
let actual_exposure_paged = EraInfo::<Test>::get_paged_exposure(1, &11, 0).unwrap();
assert_eq!(actual_exposure_paged.others(), &clipped_exposure);
assert_eq!(actual_exposure_paged.own(), 1000);
assert_eq!(actual_exposure_paged.exposure_metadata.page_count, 1);
let actual_exposure_full = EraInfo::<Test>::get_full_exposure(1, &11);
assert_eq!(actual_exposure_full.others, expected_individual_exposures);
assert_eq!(actual_exposure_full.own, 1000);
assert_eq!(actual_exposure_full.total, total_exposure);
// validator is exposed
assert!(<Staking as sp_staking::StakingInterface>::is_exposed_in_era(&11, &1));
// nominators are exposed
for i in 10..15 {
let who: AccountId = 1000 + i;
assert!(<Staking as sp_staking::StakingInterface>::is_exposed_in_era(&who, &1));
}
// for pages other than 0, clipped storage returns empty exposure
assert_eq!(EraInfo::<Test>::get_paged_exposure(1, &11, 1), None);
// page size is 1 for clipped storage
assert_eq!(EraInfo::<Test>::get_page_count(1, &11), 1);
// payout for page 0 works
assert_ok!(Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, 0, 0));
// payout for page 1 fails
assert_noop!(
Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, 0, 1),
Error::<Test>::InvalidPage
.with_weight(<Test as Config>::WeightInfo::payout_stakers_alive_staked(0))
);
});
}
mod staking_interface {
use frame_support::storage::with_storage_layer;
use sp_staking::StakingInterface;
use super::*;
#[test]
fn force_unstake_with_slash_works() {
ExtBuilder::default().build_and_execute(|| {
// without slash
let _ = with_storage_layer::<(), _, _>(|| {
// bond an account, can unstake
assert_eq!(Staking::bonded(&11), Some(11));
assert_ok!(<Staking as StakingInterface>::force_unstake(11));
Err(DispatchError::from("revert"))
});
// bond again and add a slash, still can unstake.
assert_eq!(Staking::bonded(&11), Some(11));
add_slash(&11);
assert_ok!(<Staking as StakingInterface>::force_unstake(11));
});
}
#[test]
fn do_withdraw_unbonded_with_wrong_slash_spans_works_as_expected() {
ExtBuilder::default().build_and_execute(|| {
on_offence_now(
&[OffenceDetails {
offender: (11, Staking::eras_stakers(active_era(), &11)),
reporters: vec![],
}],
&[Perbill::from_percent(100)],
);
assert_eq!(Staking::bonded(&11), Some(11));
Staking::withdraw_unbonded(RuntimeOrigin::signed(11), 0),
Error::<Test>::IncorrectSlashingSpans
);
let num_slashing_spans = Staking::slashing_spans(&11).map_or(0, |s| s.iter().count());
assert_ok!(Staking::withdraw_unbonded(
RuntimeOrigin::signed(11),
num_slashing_spans as u32
));
});
}
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
#[test]
fn status() {
ExtBuilder::default().build_and_execute(|| {
// stash of a validator is identified as a validator
assert_eq!(Staking::status(&11).unwrap(), StakerStatus::Validator);
// .. but not the controller.
assert!(Staking::status(&10).is_err());
// stash of nominator is identified as a nominator
assert_eq!(Staking::status(&101).unwrap(), StakerStatus::Nominator(vec![11, 21]));
// .. but not the controller.
assert!(Staking::status(&100).is_err());
// stash of chilled is identified as a chilled
assert_eq!(Staking::status(&41).unwrap(), StakerStatus::Idle);
// .. but not the controller.
assert!(Staking::status(&40).is_err());
// random other account.
assert!(Staking::status(&42).is_err());
})
}
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
mod staking_unchecked {
use sp_staking::{Stake, StakingInterface, StakingUnchecked};
use super::*;
#[test]
fn virtual_bond_does_not_lock() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
assert_eq!(Balances::free_balance(10), 1);
// 10 can bond more than its balance amount since we do not require lock for virtual
// bonding.
assert_ok!(<Staking as StakingUnchecked>::virtual_bond(&10, 100, &15));
// nothing is locked on 10.
assert_eq!(Balances::balance_locked(STAKING_ID, &10), 0);
// adding more balance does not lock anything as well.
assert_ok!(<Staking as StakingInterface>::bond_extra(&10, 1000));
// but ledger is updated correctly.
assert_eq!(
<Staking as StakingInterface>::stake(&10),
Ok(Stake { total: 1100, active: 1100 })
);
// lets try unbonding some amount.
assert_ok!(<Staking as StakingInterface>::unbond(&10, 200));
assert_eq!(
Staking::ledger(10.into()).unwrap(),
StakingLedgerInspect {
stash: 10,
total: 1100,
active: 1100 - 200,
unlocking: bounded_vec![UnlockChunk { value: 200, era: 1 + 3 }],
legacy_claimed_rewards: bounded_vec![],
}
);
assert_eq!(
<Staking as StakingInterface>::stake(&10),
Ok(Stake { total: 1100, active: 900 })
);
// still no locks.
assert_eq!(Balances::balance_locked(STAKING_ID, &10), 0);
mock::start_active_era(2);
// cannot withdraw without waiting for unbonding period.
assert_ok!(<Staking as StakingInterface>::withdraw_unbonded(10, 0));
assert_eq!(
<Staking as StakingInterface>::stake(&10),
Ok(Stake { total: 1100, active: 900 })
);
// in era 4, 10 can withdraw unlocking amount.
mock::start_active_era(4);
assert_ok!(<Staking as StakingInterface>::withdraw_unbonded(10, 0));
assert_eq!(
<Staking as StakingInterface>::stake(&10),
Ok(Stake { total: 900, active: 900 })
);
// unbond all.
assert_ok!(<Staking as StakingInterface>::unbond(&10, 900));
assert_eq!(
<Staking as StakingInterface>::stake(&10),
Ok(Stake { total: 900, active: 0 })
);
mock::start_active_era(7);
assert_ok!(<Staking as StakingInterface>::withdraw_unbonded(10, 0));
// ensure withdrawing all amount cleans up storage.
assert_eq!(Staking::ledger(10.into()), Err(Error::<Test>::NotStash));
assert_eq!(VirtualStakers::<Test>::contains_key(10), false);
})
}
#[test]
fn virtual_staker_cannot_pay_reward_to_self_account() {
ExtBuilder::default().build_and_execute(|| {
// cannot set payee to self
assert_noop!(
<Staking as StakingUnchecked>::virtual_bond(&10, 100, &10),
Error::<Test>::RewardDestinationRestricted
);
// to another account works
assert_ok!(<Staking as StakingUnchecked>::virtual_bond(&10, 100, &11));
// cannot set via set_payee as well.
assert_noop!(
<Staking as StakingInterface>::update_payee(&10, &10),
Error::<Test>::RewardDestinationRestricted
);
});
}
#[test]
fn virtual_staker_cannot_bond_again() {
ExtBuilder::default().build_and_execute(|| {
// 200 virtual bonds
bond_virtual_nominator(200, 201, 500, vec![11, 21]);
// Tries bonding again
assert_noop!(
<Staking as StakingUnchecked>::virtual_bond(&200, 200, &201),
Error::<Test>::AlreadyBonded
);
// And again with a different reward destination.
assert_noop!(
<Staking as StakingUnchecked>::virtual_bond(&200, 200, &202),
Error::<Test>::AlreadyBonded
);
// Direct bond is not allowed as well.
assert_noop!(
<Staking as StakingInterface>::bond(&200, 200, &202),
Error::<Test>::AlreadyBonded
);
});
}
#[test]
fn normal_staker_cannot_virtual_bond() {
ExtBuilder::default().build_and_execute(|| {
// 101 is a nominator trying to virtual bond
assert_noop!(
<Staking as StakingUnchecked>::virtual_bond(&101, 200, &102),
Error::<Test>::AlreadyBonded
);