Skip to content
tests.rs 162 KiB
Newer Older
					.collect::<Vec<_>>(),
				vec![(70, 3), (101, 2), (60, 1)]
			);
			assert_eq!(Staking::electing_voters(None).unwrap().len(), 3 + 3);

			// abrupt change from 4 to 3, everyone should be fine.
			MaxNominations::set(3);

			assert_eq!(
				Nominators::<Test>::iter()
					.map(|(k, n)| (k, n.targets.len()))
					.collect::<Vec<_>>(),
				vec![(70, 3), (101, 2), (60, 1)]
			);
			assert_eq!(Staking::electing_voters(None).unwrap().len(), 3 + 3);

			// abrupt change from 3 to 2, this should cause some nominators to be non-decodable, and
			// thus non-existent unless if they update.
			MaxNominations::set(2);

			assert_eq!(
				Nominators::<Test>::iter()
					.map(|(k, n)| (k, n.targets.len()))
					.collect::<Vec<_>>(),
				vec![(101, 2), (60, 1)]
			);
			// 70 is still in storage..
			assert!(Nominators::<Test>::contains_key(70));
			// but its value cannot be decoded and default is returned.
			assert!(Nominators::<Test>::get(70).is_none());

			assert_eq!(Staking::electing_voters(None).unwrap().len(), 3 + 2);
			assert!(Nominators::<Test>::contains_key(101));

			// abrupt change from 2 to 1, this should cause some nominators to be non-decodable, and
			// thus non-existent unless if they update.
			MaxNominations::set(1);

			assert_eq!(
				Nominators::<Test>::iter()
					.map(|(k, n)| (k, n.targets.len()))
					.collect::<Vec<_>>(),
				vec![(60, 1)]
			);
			assert!(Nominators::<Test>::contains_key(70));
			assert!(Nominators::<Test>::contains_key(60));
			assert!(Nominators::<Test>::get(70).is_none());
			assert!(Nominators::<Test>::get(60).is_some());
			assert_eq!(Staking::electing_voters(None).unwrap().len(), 3 + 1);

			// now one of them can revive themselves by re-nominating to a proper value.
			assert_ok!(Staking::nominate(RuntimeOrigin::signed(71), vec![1]));
			assert_eq!(
				Nominators::<Test>::iter()
					.map(|(k, n)| (k, n.targets.len()))
					.collect::<Vec<_>>(),
				vec![(70, 1), (60, 1)]
			);

			// or they can be chilled by any account.
			assert!(Nominators::<Test>::contains_key(101));
			assert!(Nominators::<Test>::get(101).is_none());
			assert_ok!(Staking::chill_other(RuntimeOrigin::signed(70), 100));
			assert!(!Nominators::<Test>::contains_key(101));
			assert!(Nominators::<Test>::get(101).is_none());
		})
}

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
			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]
			);
			assert_ok!(Staking::nominate(RuntimeOrigin::signed(100), vec![41]));
			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(10), Default::default()));

			// then counts don't change
			assert_eq!(<Test as Config>::VoterList::count(), pre_insert_voter_count);
			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(30), prefs(10)));
		assert_ok!(Staking::validate(RuntimeOrigin::signed(20), 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),
#[test]
fn proportional_slash_stop_slashing_if_remaining_zero() {
	let c = |era, value| UnlockChunk::<Balance> { era, value };
	// Given
	let mut ledger = StakingLedger::<Test> {
		stash: 123,
		total: 40,
		active: 20,
		// we have some chunks, but they are not affected.
		unlocking: bounded_vec![c(1, 10), c(2, 10)],
		claimed_rewards: vec![],
	};

	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> {
		stash: 123,
		total: 10,
		active: 10,
		unlocking: bounded_vec![],
		claimed_rewards: vec![],
	};
	assert_eq!(BondingDuration::get(), 3);

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

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

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

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

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

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

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

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

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

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

	// Tests for saturating arithmetic

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

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

	// Given
	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 - 5);
	// Then
	// The amount slashed out of `unit`
	let affected_balance = value + unit * 4;
	let ratio =
		Perquintill::from_rational_with_rounding(slash, affected_balance, Rounding::Up).unwrap();
	// `unit` after the slash is applied
	let unit_slashed = {
		unit - unit_slash
	};
	let value_slashed = {
		value - value_slash
	};
	assert_eq!(ledger.active, unit_slashed);
	assert_eq!(ledger.unlocking, vec![c(5, value_slashed)]);
	assert_eq!(ledger.total, value_slashed);
	assert_eq!(LedgerSlashPerEra::get().0, 0);
	assert_eq!(
		LedgerSlashPerEra::get().1,
		BTreeMap::from([(4, 0), (5, value_slashed), (6, 0), (7, 0)])
	);
}