mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-14 19:11:04 +00:00
[NPoS] Paging reward payouts in order to scale rewardable nominators (#1189)
helps https://github.com/paritytech/polkadot-sdk/issues/439. closes https://github.com/paritytech/polkadot-sdk/issues/473. PR link in the older substrate repository: https://github.com/paritytech/substrate/pull/13498. # Context Rewards payout is processed today in a single block and limited to `MaxNominatorRewardedPerValidator`. This number is currently 512 on both Kusama and Polkadot. This PR tries to scale the nominators payout to an unlimited count in a multi-block fashion. Exposures are stored in pages, with each page capped to a certain number (`MaxExposurePageSize`). Starting out, this number would be the same as `MaxNominatorRewardedPerValidator`, but eventually, this number can be lowered through new runtime upgrades to limit the rewardeable nominators per dispatched call instruction. The changes in the PR are backward compatible. ## How payouts would work like after this change Staking exposes two calls, 1) the existing `payout_stakers` and 2) `payout_stakers_by_page`. ### payout_stakers This remains backward compatible with no signature change. If for a given era a validator has multiple pages, they can call `payout_stakers` multiple times. The pages are executed in an ascending sequence and the runtime takes care of preventing double claims. ### payout_stakers_by_page Very similar to `payout_stakers` but also accepts an extra param `page_index`. An account can choose to payout rewards only for an explicitly passed `page_index`. **Lets look at an example scenario** Given an active validator on Kusama had 1100 nominators, `MaxExposurePageSize` set to 512 for Era e. In order to pay out rewards to all nominators, the caller would need to call `payout_stakers` 3 times. - `payout_stakers(origin, stash, e)` => will pay the first 512 nominators. - `payout_stakers(origin, stash, e)` => will pay the second set of 512 nominators. - `payout_stakers(origin, stash, e)` => will pay the last set of 76 nominators. ... - `payout_stakers(origin, stash, e)` => calling it the 4th time would return an error `InvalidPage`. The above calls can also be replaced by `payout_stakers_by_page` and passing a `page_index` explicitly. ## Commission note Validator commission is paid out in chunks across all the pages where each commission chunk is proportional to the total stake of the current page. This implies higher the total stake of a page, higher will be the commission. If all the pages of a validator's single era are paid out, the sum of commission paid to the validator across all pages should be equal to what the commission would have been if we had a non-paged exposure. ### Migration Note Strictly speaking, we did not need to bump our storage version since there is no migration of storage in this PR. But it is still useful to mark a storage upgrade for the following reasons: - New storage items are introduced in this PR while some older storage items are deprecated. - For the next `HistoryDepth` eras, the exposure would be incrementally migrated to its corresponding paged storage item. - Runtimes using staking pallet would strictly need to wait at least `HistoryDepth` eras with current upgraded version (14) for the migration to complete. At some era `E` such that `E > era_at_which_V14_gets_into_effect + HistoryDepth`, we will upgrade to version X which will remove the deprecated storage items. In other words, it is a strict requirement that E<sub>x</sub> - E<sub>14</sub> > `HistoryDepth`, where E<sub>x</sub> = Era at which deprecated storages are removed from runtime, E<sub>14</sub> = Era at which runtime is upgraded to version 14. - For Polkadot and Kusama, there is a [tracker ticket](https://github.com/paritytech/polkadot-sdk/issues/433) to clean up the deprecated storage items. ### Storage Changes #### Added - ErasStakersOverview - ClaimedRewards - ErasStakersPaged #### Deprecated The following can be cleaned up after 84 eras which is tracked [here](https://github.com/paritytech/polkadot-sdk/issues/433). - ErasStakers. - ErasStakersClipped. - StakingLedger.claimed_rewards, renamed to StakingLedger.legacy_claimed_rewards. ### Config Changes - Renamed MaxNominatorRewardedPerValidator to MaxExposurePageSize. ### TODO - [x] Tracker ticket for cleaning up the old code after 84 eras. - [x] Add companion. - [x] Redo benchmarks before merge. - [x] Add Changelog for pallet_staking. - [x] Pallet should be configurable to enable/disable paged rewards. - [x] Commission payouts are distributed across pages. - [x] Review documentation thoroughly. - [x] Rename `MaxNominatorRewardedPerValidator` -> `MaxExposurePageSize`. - [x] NMap for `ErasStakersPaged`. - [x] Deprecate ErasStakers. - [x] Integrity tests. ### Followup issues [Runtime api for deprecated ErasStakers storage item](https://github.com/paritytech/polkadot-sdk/issues/426) --------- Co-authored-by: Javier Viola <javier@parity.io> Co-authored-by: Ross Bulat <ross@parity.io> Co-authored-by: command-bot <>
This commit is contained in:
@@ -27,8 +27,8 @@ use frame_support::{
|
||||
dispatch::WithPostDispatchInfo,
|
||||
pallet_prelude::*,
|
||||
traits::{
|
||||
Currency, Defensive, DefensiveResult, EstimateNextNewSession, Get, Imbalance, OnUnbalanced,
|
||||
TryCollect, UnixTime,
|
||||
Currency, Defensive, EstimateNextNewSession, Get, Imbalance, Len, OnUnbalanced, TryCollect,
|
||||
UnixTime,
|
||||
},
|
||||
weights::Weight,
|
||||
};
|
||||
@@ -41,7 +41,7 @@ use sp_runtime::{
|
||||
use sp_staking::{
|
||||
currency_to_vote::CurrencyToVote,
|
||||
offence::{DisableStrategy, OffenceDetails, OnOffenceHandler},
|
||||
EraIndex, SessionIndex, Stake,
|
||||
EraIndex, Page, SessionIndex, Stake,
|
||||
StakingAccount::{self, Controller, Stash},
|
||||
StakingInterface,
|
||||
};
|
||||
@@ -49,9 +49,9 @@ use sp_std::prelude::*;
|
||||
|
||||
use crate::{
|
||||
election_size_tracker::StaticTracker, log, slashing, weights::WeightInfo, ActiveEraInfo,
|
||||
BalanceOf, EraPayout, Exposure, ExposureOf, Forcing, IndividualExposure, MaxNominationsOf,
|
||||
MaxWinnersOf, Nominations, NominationsQuota, PositiveImbalanceOf, RewardDestination,
|
||||
SessionInterface, StakingLedger, ValidatorPrefs,
|
||||
BalanceOf, EraInfo, EraPayout, Exposure, ExposureOf, Forcing, IndividualExposure,
|
||||
MaxNominationsOf, MaxWinnersOf, Nominations, NominationsQuota, PositiveImbalanceOf,
|
||||
RewardDestination, SessionInterface, StakingLedger, ValidatorPrefs,
|
||||
};
|
||||
|
||||
use super::pallet::*;
|
||||
@@ -158,12 +158,31 @@ impl<T: Config> Pallet<T> {
|
||||
pub(super) fn do_payout_stakers(
|
||||
validator_stash: T::AccountId,
|
||||
era: EraIndex,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
let controller = Self::bonded(&validator_stash).ok_or_else(|| {
|
||||
Error::<T>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
|
||||
})?;
|
||||
let ledger = <Ledger<T>>::get(&controller).ok_or(Error::<T>::NotController)?;
|
||||
let page = EraInfo::<T>::get_next_claimable_page(era, &validator_stash, &ledger)
|
||||
.ok_or_else(|| {
|
||||
Error::<T>::AlreadyClaimed
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
|
||||
})?;
|
||||
|
||||
Self::do_payout_stakers_by_page(validator_stash, era, page)
|
||||
}
|
||||
|
||||
pub(super) fn do_payout_stakers_by_page(
|
||||
validator_stash: T::AccountId,
|
||||
era: EraIndex,
|
||||
page: Page,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
// Validate input data
|
||||
let current_era = CurrentEra::<T>::get().ok_or_else(|| {
|
||||
Error::<T>::InvalidEraToReward
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
|
||||
})?;
|
||||
|
||||
let history_depth = T::HistoryDepth::get();
|
||||
ensure!(
|
||||
era <= current_era && era >= current_era.saturating_sub(history_depth),
|
||||
@@ -171,8 +190,13 @@ impl<T: Config> Pallet<T> {
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
|
||||
);
|
||||
|
||||
ensure!(
|
||||
page < EraInfo::<T>::get_page_count(era, &validator_stash),
|
||||
Error::<T>::InvalidPage.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
|
||||
);
|
||||
|
||||
// Note: if era has no reward to be claimed, era may be future. better not to update
|
||||
// `ledger.claimed_rewards` in this case.
|
||||
// `ledger.legacy_claimed_rewards` in this case.
|
||||
let era_payout = <ErasValidatorReward<T>>::get(&era).ok_or_else(|| {
|
||||
Error::<T>::InvalidEraToReward
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
|
||||
@@ -186,31 +210,29 @@ impl<T: Config> Pallet<T> {
|
||||
Err(Error::<T>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
|
||||
}
|
||||
})?;
|
||||
|
||||
// clean up older claimed rewards
|
||||
ledger
|
||||
.legacy_claimed_rewards
|
||||
.retain(|&x| x >= current_era.saturating_sub(history_depth));
|
||||
ledger.clone().update()?;
|
||||
|
||||
let stash = ledger.stash.clone();
|
||||
|
||||
ledger
|
||||
.claimed_rewards
|
||||
.retain(|&x| x >= current_era.saturating_sub(history_depth));
|
||||
|
||||
match ledger.claimed_rewards.binary_search(&era) {
|
||||
Ok(_) =>
|
||||
return Err(Error::<T>::AlreadyClaimed
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))),
|
||||
Err(pos) => ledger
|
||||
.claimed_rewards
|
||||
.try_insert(pos, era)
|
||||
// Since we retain era entries in `claimed_rewards` only upto
|
||||
// `HistoryDepth`, following bound is always expected to be
|
||||
// satisfied.
|
||||
.defensive_map_err(|_| Error::<T>::BoundNotMet)?,
|
||||
if EraInfo::<T>::is_rewards_claimed_with_legacy_fallback(era, &ledger, &stash, page) {
|
||||
return Err(Error::<T>::AlreadyClaimed
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
|
||||
} else {
|
||||
EraInfo::<T>::set_rewards_as_claimed(era, &stash, page);
|
||||
}
|
||||
|
||||
let exposure = <ErasStakersClipped<T>>::get(&era, &stash);
|
||||
let exposure = EraInfo::<T>::get_paged_exposure(era, &stash, page).ok_or_else(|| {
|
||||
Error::<T>::InvalidEraToReward
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
|
||||
})?;
|
||||
|
||||
// Input data seems good, no errors allowed after this point
|
||||
|
||||
ledger.update()?;
|
||||
|
||||
// Get Era reward points. It has TOTAL and INDIVIDUAL
|
||||
// Find the fraction of the era reward that belongs to the validator
|
||||
// Take that fraction of the eras rewards to split to nominator and validator
|
||||
@@ -236,15 +258,17 @@ impl<T: Config> Pallet<T> {
|
||||
// This is how much validator + nominators are entitled to.
|
||||
let validator_total_payout = validator_total_reward_part * era_payout;
|
||||
|
||||
let validator_prefs = Self::eras_validator_prefs(&era, &validator_stash);
|
||||
// Validator first gets a cut off the top.
|
||||
let validator_commission = validator_prefs.commission;
|
||||
let validator_commission_payout = validator_commission * validator_total_payout;
|
||||
let validator_commission = EraInfo::<T>::get_validator_commission(era, &ledger.stash);
|
||||
// total commission validator takes across all nominator pages
|
||||
let validator_total_commission_payout = validator_commission * validator_total_payout;
|
||||
|
||||
let validator_leftover_payout = validator_total_payout - validator_commission_payout;
|
||||
let validator_leftover_payout = validator_total_payout - validator_total_commission_payout;
|
||||
// Now let's calculate how this is split to the validator.
|
||||
let validator_exposure_part = Perbill::from_rational(exposure.own, exposure.total);
|
||||
let validator_exposure_part = Perbill::from_rational(exposure.own(), exposure.total());
|
||||
let validator_staking_payout = validator_exposure_part * validator_leftover_payout;
|
||||
let page_stake_part = Perbill::from_rational(exposure.page_total(), exposure.total());
|
||||
// validator commission is paid out in fraction across pages proportional to the page stake.
|
||||
let validator_commission_payout = page_stake_part * validator_total_commission_payout;
|
||||
|
||||
Self::deposit_event(Event::<T>::PayoutStarted {
|
||||
era_index: era,
|
||||
@@ -267,8 +291,8 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
// Lets now calculate how this is split to the nominators.
|
||||
// Reward only the clipped exposures. Note this is not necessarily sorted.
|
||||
for nominator in exposure.others.iter() {
|
||||
let nominator_exposure_part = Perbill::from_rational(nominator.value, exposure.total);
|
||||
for nominator in exposure.others().iter() {
|
||||
let nominator_exposure_part = Perbill::from_rational(nominator.value, exposure.total());
|
||||
|
||||
let nominator_reward: BalanceOf<T> =
|
||||
nominator_exposure_part * validator_leftover_payout;
|
||||
@@ -287,7 +311,8 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
|
||||
T::Reward::on_unbalanced(total_imbalance);
|
||||
debug_assert!(nominator_payout_count <= T::MaxNominatorRewardedPerValidator::get());
|
||||
debug_assert!(nominator_payout_count <= T::MaxExposurePageSize::get());
|
||||
|
||||
Ok(Some(T::WeightInfo::payout_stakers_alive_staked(nominator_payout_count)).into())
|
||||
}
|
||||
|
||||
@@ -306,6 +331,11 @@ impl<T: Config> Pallet<T> {
|
||||
stash: &T::AccountId,
|
||||
amount: BalanceOf<T>,
|
||||
) -> Option<(PositiveImbalanceOf<T>, RewardDestination<T::AccountId>)> {
|
||||
// noop if amount is zero
|
||||
if amount.is_zero() {
|
||||
return None
|
||||
}
|
||||
|
||||
let dest = Self::payee(StakingAccount::Stash(stash.clone()));
|
||||
let maybe_imbalance = match dest {
|
||||
RewardDestination::Controller => Self::bonded(stash)
|
||||
@@ -587,31 +617,24 @@ impl<T: Config> Pallet<T> {
|
||||
>,
|
||||
new_planned_era: EraIndex,
|
||||
) -> BoundedVec<T::AccountId, MaxWinnersOf<T>> {
|
||||
let elected_stashes: BoundedVec<_, MaxWinnersOf<T>> = exposures
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|(x, _)| x)
|
||||
.collect::<Vec<_>>()
|
||||
.try_into()
|
||||
.expect("since we only map through exposures, size of elected_stashes is always same as exposures; qed");
|
||||
|
||||
// Populate stakers, exposures, and the snapshot of validator prefs.
|
||||
// Populate elected stash, stakers, exposures, and the snapshot of validator prefs.
|
||||
let mut total_stake: BalanceOf<T> = Zero::zero();
|
||||
exposures.into_iter().for_each(|(stash, exposure)| {
|
||||
total_stake = total_stake.saturating_add(exposure.total);
|
||||
<ErasStakers<T>>::insert(new_planned_era, &stash, &exposure);
|
||||
let mut elected_stashes = Vec::with_capacity(exposures.len());
|
||||
|
||||
let mut exposure_clipped = exposure;
|
||||
let clipped_max_len = T::MaxNominatorRewardedPerValidator::get() as usize;
|
||||
if exposure_clipped.others.len() > clipped_max_len {
|
||||
exposure_clipped.others.sort_by(|a, b| a.value.cmp(&b.value).reverse());
|
||||
exposure_clipped.others.truncate(clipped_max_len);
|
||||
}
|
||||
<ErasStakersClipped<T>>::insert(&new_planned_era, &stash, exposure_clipped);
|
||||
exposures.into_iter().for_each(|(stash, exposure)| {
|
||||
// build elected stash
|
||||
elected_stashes.push(stash.clone());
|
||||
// accumulate total stake
|
||||
total_stake = total_stake.saturating_add(exposure.total);
|
||||
// store staker exposure for this era
|
||||
EraInfo::<T>::set_exposure(new_planned_era, &stash, exposure);
|
||||
});
|
||||
|
||||
// Insert current era staking information
|
||||
<ErasTotalStake<T>>::insert(&new_planned_era, total_stake);
|
||||
let elected_stashes: BoundedVec<_, MaxWinnersOf<T>> = elected_stashes
|
||||
.try_into()
|
||||
.expect("elected_stashes.len() always equal to exposures.len(); qed");
|
||||
|
||||
EraInfo::<T>::set_total_stake(new_planned_era, total_stake);
|
||||
|
||||
// Collect the pref of all winners.
|
||||
for stash in &elected_stashes {
|
||||
@@ -692,12 +715,21 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
/// Clear all era information for given era.
|
||||
pub(crate) fn clear_era_information(era_index: EraIndex) {
|
||||
// FIXME: We can possibly set a reasonable limit since we do this only once per era and
|
||||
// clean up state across multiple blocks.
|
||||
let mut cursor = <ErasStakers<T>>::clear_prefix(era_index, u32::MAX, None);
|
||||
debug_assert!(cursor.maybe_cursor.is_none());
|
||||
cursor = <ErasStakersClipped<T>>::clear_prefix(era_index, u32::MAX, None);
|
||||
debug_assert!(cursor.maybe_cursor.is_none());
|
||||
cursor = <ErasValidatorPrefs<T>>::clear_prefix(era_index, u32::MAX, None);
|
||||
debug_assert!(cursor.maybe_cursor.is_none());
|
||||
cursor = <ClaimedRewards<T>>::clear_prefix(era_index, u32::MAX, None);
|
||||
debug_assert!(cursor.maybe_cursor.is_none());
|
||||
cursor = <ErasStakersPaged<T>>::clear_prefix((era_index,), u32::MAX, None);
|
||||
debug_assert!(cursor.maybe_cursor.is_none());
|
||||
cursor = <ErasStakersOverview<T>>::clear_prefix(era_index, u32::MAX, None);
|
||||
debug_assert!(cursor.maybe_cursor.is_none());
|
||||
|
||||
<ErasValidatorReward<T>>::remove(era_index);
|
||||
<ErasRewardPoints<T>>::remove(era_index);
|
||||
<ErasTotalStake<T>>::remove(era_index);
|
||||
@@ -1036,6 +1068,18 @@ impl<T: Config> Pallet<T> {
|
||||
DispatchClass::Mandatory,
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns full exposure of a validator for a given era.
|
||||
///
|
||||
/// History note: This used to be a getter for old storage item `ErasStakers` deprecated in v14.
|
||||
/// Since this function is used in the codebase at various places, we kept it as a custom getter
|
||||
/// that takes care of getting the full exposure of the validator in a backward compatible way.
|
||||
pub fn eras_stakers(
|
||||
era: EraIndex,
|
||||
account: &T::AccountId,
|
||||
) -> Exposure<T::AccountId, BalanceOf<T>> {
|
||||
EraInfo::<T>::get_full_exposure(era, account)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> Pallet<T> {
|
||||
@@ -1045,6 +1089,17 @@ impl<T: Config> Pallet<T> {
|
||||
pub fn api_nominations_quota(balance: BalanceOf<T>) -> u32 {
|
||||
T::NominationsQuota::get_quota(balance)
|
||||
}
|
||||
|
||||
pub fn api_eras_stakers(
|
||||
era: EraIndex,
|
||||
account: T::AccountId,
|
||||
) -> Exposure<T::AccountId, BalanceOf<T>> {
|
||||
Self::eras_stakers(era, &account)
|
||||
}
|
||||
|
||||
pub fn api_eras_stakers_page_count(era: EraIndex, account: T::AccountId) -> Page {
|
||||
EraInfo::<T>::get_page_count(era, &account)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> ElectionDataProvider for Pallet<T> {
|
||||
@@ -1129,10 +1184,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
|
||||
panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
|
||||
});
|
||||
<Bonded<T>>::insert(voter.clone(), voter.clone());
|
||||
<Ledger<T>>::insert(
|
||||
voter.clone(),
|
||||
StakingLedger::<T>::new(voter.clone(), stake, Default::default()),
|
||||
);
|
||||
<Ledger<T>>::insert(voter.clone(), StakingLedger::<T>::new(voter.clone(), stake));
|
||||
|
||||
Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false });
|
||||
}
|
||||
@@ -1141,10 +1193,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
|
||||
fn add_target(target: T::AccountId) {
|
||||
let stake = MinValidatorBond::<T>::get() * 100u32.into();
|
||||
<Bonded<T>>::insert(target.clone(), target.clone());
|
||||
<Ledger<T>>::insert(
|
||||
target.clone(),
|
||||
StakingLedger::<T>::new(target.clone(), stake, Default::default()),
|
||||
);
|
||||
<Ledger<T>>::insert(target.clone(), StakingLedger::<T>::new(target.clone(), stake));
|
||||
Self::do_add_validator(
|
||||
&target,
|
||||
ValidatorPrefs { commission: Perbill::zero(), blocked: false },
|
||||
@@ -1176,10 +1225,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
|
||||
.and_then(|w| <BalanceOf<T>>::try_from(w).ok())
|
||||
.unwrap_or_else(|| MinNominatorBond::<T>::get() * 100u32.into());
|
||||
<Bonded<T>>::insert(v.clone(), v.clone());
|
||||
<Ledger<T>>::insert(
|
||||
v.clone(),
|
||||
StakingLedger::<T>::new(v.clone(), stake, Default::default()),
|
||||
);
|
||||
<Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
|
||||
Self::do_add_validator(
|
||||
&v,
|
||||
ValidatorPrefs { commission: Perbill::zero(), blocked: false },
|
||||
@@ -1191,10 +1237,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
|
||||
panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
|
||||
});
|
||||
<Bonded<T>>::insert(v.clone(), v.clone());
|
||||
<Ledger<T>>::insert(
|
||||
v.clone(),
|
||||
StakingLedger::<T>::new(v.clone(), stake, Default::default()),
|
||||
);
|
||||
<Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
|
||||
Self::do_add_nominator(
|
||||
&v,
|
||||
Nominations { targets: t, submitted_in: 0, suppressed: false },
|
||||
@@ -1622,31 +1665,12 @@ impl<T: Config> StakingInterface for Pallet<T> {
|
||||
MinValidatorBond::<T>::get()
|
||||
}
|
||||
|
||||
fn desired_validator_count() -> u32 {
|
||||
ValidatorCount::<T>::get()
|
||||
}
|
||||
|
||||
fn election_ongoing() -> bool {
|
||||
T::ElectionProvider::ongoing()
|
||||
}
|
||||
|
||||
fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult {
|
||||
let num_slashing_spans = Self::slashing_spans(&who).map_or(0, |s| s.iter().count() as u32);
|
||||
Self::force_unstake(RawOrigin::Root.into(), who.clone(), num_slashing_spans)
|
||||
}
|
||||
|
||||
fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError> {
|
||||
Self::ledger(Controller(controller.clone()))
|
||||
.map(|l| l.stash)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool {
|
||||
ErasStakers::<T>::iter_prefix(era).any(|(validator, exposures)| {
|
||||
validator == *who || exposures.others.iter().any(|i| i.who == *who)
|
||||
})
|
||||
}
|
||||
|
||||
fn bonding_duration() -> EraIndex {
|
||||
T::BondingDuration::get()
|
||||
}
|
||||
@@ -1707,6 +1731,24 @@ impl<T: Config> StakingInterface for Pallet<T> {
|
||||
Self::nominate(RawOrigin::Signed(ctrl).into(), targets)
|
||||
}
|
||||
|
||||
fn desired_validator_count() -> u32 {
|
||||
ValidatorCount::<T>::get()
|
||||
}
|
||||
|
||||
fn election_ongoing() -> bool {
|
||||
T::ElectionProvider::ongoing()
|
||||
}
|
||||
|
||||
fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult {
|
||||
let num_slashing_spans = Self::slashing_spans(&who).map_or(0, |s| s.iter().count() as u32);
|
||||
Self::force_unstake(RawOrigin::Root.into(), who.clone(), num_slashing_spans)
|
||||
}
|
||||
|
||||
fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool {
|
||||
ErasStakers::<T>::iter_prefix(era).any(|(validator, exposures)| {
|
||||
validator == *who || exposures.others.iter().any(|i| i.who == *who)
|
||||
})
|
||||
}
|
||||
fn status(
|
||||
who: &Self::AccountId,
|
||||
) -> Result<sp_staking::StakerStatus<Self::AccountId>, DispatchError> {
|
||||
@@ -1746,12 +1788,16 @@ impl<T: Config> StakingInterface for Pallet<T> {
|
||||
.map(|(who, value)| IndividualExposure { who: who.clone(), value: value.clone() })
|
||||
.collect::<Vec<_>>();
|
||||
let exposure = Exposure { total: Default::default(), own: Default::default(), others };
|
||||
<ErasStakers<T>>::insert(¤t_era, &stash, &exposure);
|
||||
EraInfo::<T>::set_exposure(*current_era, stash, exposure);
|
||||
}
|
||||
|
||||
fn set_current_era(era: EraIndex) {
|
||||
CurrentEra::<T>::put(era);
|
||||
}
|
||||
|
||||
fn max_exposure_page_size() -> Page {
|
||||
T::MaxExposurePageSize::get()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,8 +24,8 @@ use frame_election_provider_support::{
|
||||
use frame_support::{
|
||||
pallet_prelude::*,
|
||||
traits::{
|
||||
Currency, Defensive, DefensiveResult, DefensiveSaturating, EnsureOrigin,
|
||||
EstimateNextNewSession, Get, LockableCurrency, OnUnbalanced, TryCollect, UnixTime,
|
||||
Currency, Defensive, DefensiveSaturating, EnsureOrigin, EstimateNextNewSession, Get,
|
||||
LockableCurrency, OnUnbalanced, UnixTime,
|
||||
},
|
||||
weights::Weight,
|
||||
BoundedVec,
|
||||
@@ -35,8 +35,9 @@ use sp_runtime::{
|
||||
traits::{CheckedSub, SaturatedConversion, StaticLookup, Zero},
|
||||
ArithmeticError, Perbill, Percent,
|
||||
};
|
||||
|
||||
use sp_staking::{
|
||||
EraIndex, SessionIndex,
|
||||
EraIndex, Page, SessionIndex,
|
||||
StakingAccount::{self, Controller, Stash},
|
||||
};
|
||||
use sp_std::prelude::*;
|
||||
@@ -47,9 +48,9 @@ pub use impls::*;
|
||||
|
||||
use crate::{
|
||||
slashing, weights::WeightInfo, AccountIdLookupOf, ActiveEraInfo, BalanceOf, EraPayout,
|
||||
EraRewardPoints, Exposure, Forcing, MaxNominationsOf, NegativeImbalanceOf, Nominations,
|
||||
NominationsQuota, PositiveImbalanceOf, RewardDestination, SessionInterface, StakingLedger,
|
||||
UnappliedSlash, UnlockChunk, ValidatorPrefs,
|
||||
EraRewardPoints, Exposure, ExposurePage, Forcing, MaxNominationsOf, NegativeImbalanceOf,
|
||||
Nominations, NominationsQuota, PositiveImbalanceOf, RewardDestination, SessionInterface,
|
||||
StakingLedger, UnappliedSlash, UnlockChunk, ValidatorPrefs,
|
||||
};
|
||||
|
||||
// The speculative number of spans are used as an input of the weight annotation of
|
||||
@@ -61,12 +62,12 @@ pub(crate) const SPECULATIVE_NUM_SPANS: u32 = 32;
|
||||
pub mod pallet {
|
||||
use frame_election_provider_support::ElectionDataProvider;
|
||||
|
||||
use crate::BenchmarkingConfig;
|
||||
use crate::{BenchmarkingConfig, PagedExposureMetadata};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The current storage version.
|
||||
const STORAGE_VERSION: StorageVersion = StorageVersion::new(13);
|
||||
const STORAGE_VERSION: StorageVersion = StorageVersion::new(14);
|
||||
|
||||
#[pallet::pallet]
|
||||
#[pallet::storage_version(STORAGE_VERSION)]
|
||||
@@ -138,8 +139,8 @@ pub mod pallet {
|
||||
/// Following information is kept for eras in `[current_era -
|
||||
/// HistoryDepth, current_era]`: `ErasStakers`, `ErasStakersClipped`,
|
||||
/// `ErasValidatorPrefs`, `ErasValidatorReward`, `ErasRewardPoints`,
|
||||
/// `ErasTotalStake`, `ErasStartSessionIndex`,
|
||||
/// `StakingLedger.claimed_rewards`.
|
||||
/// `ErasTotalStake`, `ErasStartSessionIndex`, `ClaimedRewards`, `ErasStakersPaged`,
|
||||
/// `ErasStakersOverview`.
|
||||
///
|
||||
/// Must be more than the number of eras delayed by session.
|
||||
/// I.e. active era must always be in history. I.e. `active_era >
|
||||
@@ -149,7 +150,7 @@ pub mod pallet {
|
||||
/// this should be set to same value or greater as in storage.
|
||||
///
|
||||
/// Note: `HistoryDepth` is used as the upper bound for the `BoundedVec`
|
||||
/// item `StakingLedger.claimed_rewards`. Setting this value lower than
|
||||
/// item `StakingLedger.legacy_claimed_rewards`. Setting this value lower than
|
||||
/// the existing value can lead to inconsistencies in the
|
||||
/// `StakingLedger` and will need to be handled properly in a migration.
|
||||
/// The test `reducing_history_depth_abrupt` shows this effect.
|
||||
@@ -202,12 +203,19 @@ pub mod pallet {
|
||||
/// guess.
|
||||
type NextNewSession: EstimateNextNewSession<BlockNumberFor<Self>>;
|
||||
|
||||
/// The maximum number of nominators rewarded for each validator.
|
||||
/// The maximum size of each `T::ExposurePage`.
|
||||
///
|
||||
/// For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can
|
||||
/// claim their reward. This used to limit the i/o cost for the nominator payout.
|
||||
/// An `ExposurePage` is weakly bounded to a maximum of `MaxExposurePageSize`
|
||||
/// nominators.
|
||||
///
|
||||
/// For older non-paged exposure, a reward payout was restricted to the top
|
||||
/// `MaxExposurePageSize` nominators. This is to limit the i/o cost for the
|
||||
/// nominator payout.
|
||||
///
|
||||
/// Note: `MaxExposurePageSize` is used to bound `ClaimedRewards` and is unsafe to reduce
|
||||
/// without handling it in a migration.
|
||||
#[pallet::constant]
|
||||
type MaxNominatorRewardedPerValidator: Get<u32>;
|
||||
type MaxExposurePageSize: Get<u32>;
|
||||
|
||||
/// The fraction of the validator set that is safe to be offending.
|
||||
/// After the threshold is reached a new era will be forced.
|
||||
@@ -390,7 +398,7 @@ pub mod pallet {
|
||||
#[pallet::getter(fn active_era)]
|
||||
pub type ActiveEra<T> = StorageValue<_, ActiveEraInfo>;
|
||||
|
||||
/// The session index at which the era start for the last `HISTORY_DEPTH` eras.
|
||||
/// The session index at which the era start for the last [`Config::HistoryDepth`] eras.
|
||||
///
|
||||
/// Note: This tracks the starting session (i.e. session index when era start being active)
|
||||
/// for the eras in `[CurrentEra - HISTORY_DEPTH, CurrentEra]`.
|
||||
@@ -402,10 +410,11 @@ pub mod pallet {
|
||||
///
|
||||
/// This is keyed first by the era index to allow bulk deletion and then the stash account.
|
||||
///
|
||||
/// Is it removed after `HISTORY_DEPTH` eras.
|
||||
/// Is it removed after [`Config::HistoryDepth`] eras.
|
||||
/// If stakers hasn't been set or has been removed then empty exposure is returned.
|
||||
///
|
||||
/// Note: Deprecated since v14. Use `EraInfo` instead to work with exposures.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn eras_stakers)]
|
||||
#[pallet::unbounded]
|
||||
pub type ErasStakers<T: Config> = StorageDoubleMap<
|
||||
_,
|
||||
@@ -417,17 +426,45 @@ pub mod pallet {
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
/// Summary of validator exposure at a given era.
|
||||
///
|
||||
/// This contains the total stake in support of the validator and their own stake. In addition,
|
||||
/// it can also be used to get the number of nominators backing this validator and the number of
|
||||
/// exposure pages they are divided into. The page count is useful to determine the number of
|
||||
/// pages of rewards that needs to be claimed.
|
||||
///
|
||||
/// This is keyed first by the era index to allow bulk deletion and then the stash account.
|
||||
/// Should only be accessed through `EraInfo`.
|
||||
///
|
||||
/// Is it removed after [`Config::HistoryDepth`] eras.
|
||||
/// If stakers hasn't been set or has been removed then empty overview is returned.
|
||||
#[pallet::storage]
|
||||
pub type ErasStakersOverview<T: Config> = StorageDoubleMap<
|
||||
_,
|
||||
Twox64Concat,
|
||||
EraIndex,
|
||||
Twox64Concat,
|
||||
T::AccountId,
|
||||
PagedExposureMetadata<BalanceOf<T>>,
|
||||
OptionQuery,
|
||||
>;
|
||||
|
||||
/// Clipped Exposure of validator at era.
|
||||
///
|
||||
/// Note: This is deprecated, should be used as read-only and will be removed in the future.
|
||||
/// New `Exposure`s are stored in a paged manner in `ErasStakersPaged` instead.
|
||||
///
|
||||
/// This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the
|
||||
/// `T::MaxNominatorRewardedPerValidator` biggest stakers.
|
||||
/// `T::MaxExposurePageSize` biggest stakers.
|
||||
/// (Note: the field `total` and `own` of the exposure remains unchanged).
|
||||
/// This is used to limit the i/o cost for the nominator payout.
|
||||
///
|
||||
/// This is keyed fist by the era index to allow bulk deletion and then the stash account.
|
||||
///
|
||||
/// Is it removed after `HISTORY_DEPTH` eras.
|
||||
/// It is removed after [`Config::HistoryDepth`] eras.
|
||||
/// If stakers hasn't been set or has been removed then empty exposure is returned.
|
||||
///
|
||||
/// Note: Deprecated since v14. Use `EraInfo` instead to work with exposures.
|
||||
#[pallet::storage]
|
||||
#[pallet::unbounded]
|
||||
#[pallet::getter(fn eras_stakers_clipped)]
|
||||
@@ -441,11 +478,49 @@ pub mod pallet {
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
/// Paginated exposure of a validator at given era.
|
||||
///
|
||||
/// This is keyed first by the era index to allow bulk deletion, then stash account and finally
|
||||
/// the page. Should only be accessed through `EraInfo`.
|
||||
///
|
||||
/// This is cleared after [`Config::HistoryDepth`] eras.
|
||||
#[pallet::storage]
|
||||
#[pallet::unbounded]
|
||||
pub type ErasStakersPaged<T: Config> = StorageNMap<
|
||||
_,
|
||||
(
|
||||
NMapKey<Twox64Concat, EraIndex>,
|
||||
NMapKey<Twox64Concat, T::AccountId>,
|
||||
NMapKey<Twox64Concat, Page>,
|
||||
),
|
||||
ExposurePage<T::AccountId, BalanceOf<T>>,
|
||||
OptionQuery,
|
||||
>;
|
||||
|
||||
/// History of claimed paged rewards by era and validator.
|
||||
///
|
||||
/// This is keyed by era and validator stash which maps to the set of page indexes which have
|
||||
/// been claimed.
|
||||
///
|
||||
/// It is removed after [`Config::HistoryDepth`] eras.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn claimed_rewards)]
|
||||
#[pallet::unbounded]
|
||||
pub type ClaimedRewards<T: Config> = StorageDoubleMap<
|
||||
_,
|
||||
Twox64Concat,
|
||||
EraIndex,
|
||||
Twox64Concat,
|
||||
T::AccountId,
|
||||
Vec<Page>,
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
/// Similar to `ErasStakers`, this holds the preferences of validators.
|
||||
///
|
||||
/// This is keyed first by the era index to allow bulk deletion and then the stash account.
|
||||
///
|
||||
/// Is it removed after `HISTORY_DEPTH` eras.
|
||||
/// Is it removed after [`Config::HistoryDepth`] eras.
|
||||
// If prefs hasn't been set or has been removed then 0 commission is returned.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn eras_validator_prefs)]
|
||||
@@ -459,14 +534,14 @@ pub mod pallet {
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
/// The total validator era payout for the last `HISTORY_DEPTH` eras.
|
||||
/// The total validator era payout for the last [`Config::HistoryDepth`] eras.
|
||||
///
|
||||
/// Eras that haven't finished yet or has been removed doesn't have reward.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn eras_validator_reward)]
|
||||
pub type ErasValidatorReward<T: Config> = StorageMap<_, Twox64Concat, EraIndex, BalanceOf<T>>;
|
||||
|
||||
/// Rewards for the last `HISTORY_DEPTH` eras.
|
||||
/// Rewards for the last [`Config::HistoryDepth`] eras.
|
||||
/// If reward hasn't been set or has been removed then 0 reward is returned.
|
||||
#[pallet::storage]
|
||||
#[pallet::unbounded]
|
||||
@@ -474,7 +549,7 @@ pub mod pallet {
|
||||
pub type ErasRewardPoints<T: Config> =
|
||||
StorageMap<_, Twox64Concat, EraIndex, EraRewardPoints<T::AccountId>, ValueQuery>;
|
||||
|
||||
/// The total amount staked for the last `HISTORY_DEPTH` eras.
|
||||
/// The total amount staked for the last [`Config::HistoryDepth`] eras.
|
||||
/// If total hasn't been set or has been removed then 0 stake is returned.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn eras_total_stake)]
|
||||
@@ -743,6 +818,8 @@ pub mod pallet {
|
||||
NotSortedAndUnique,
|
||||
/// Rewards for this era have already been claimed for this validator.
|
||||
AlreadyClaimed,
|
||||
/// No nominators exist on this page.
|
||||
InvalidPage,
|
||||
/// Incorrect previous history depth input provided.
|
||||
IncorrectHistoryDepth,
|
||||
/// Incorrect number of slashing spans provided.
|
||||
@@ -854,23 +931,10 @@ pub mod pallet {
|
||||
|
||||
frame_system::Pallet::<T>::inc_consumers(&stash).map_err(|_| Error::<T>::BadState)?;
|
||||
|
||||
let current_era = CurrentEra::<T>::get().unwrap_or(0);
|
||||
let history_depth = T::HistoryDepth::get();
|
||||
let last_reward_era = current_era.saturating_sub(history_depth);
|
||||
|
||||
let stash_balance = T::Currency::free_balance(&stash);
|
||||
let value = value.min(stash_balance);
|
||||
Self::deposit_event(Event::<T>::Bonded { stash: stash.clone(), amount: value });
|
||||
let ledger = StakingLedger::<T>::new(
|
||||
stash.clone(),
|
||||
value,
|
||||
(last_reward_era..current_era)
|
||||
.try_collect()
|
||||
// Since last_reward_era is calculated as `current_era -
|
||||
// HistoryDepth`, following bound is always expected to be
|
||||
// satisfied.
|
||||
.defensive_map_err(|_| Error::<T>::BoundNotMet)?,
|
||||
);
|
||||
let ledger = StakingLedger::<T>::new(stash.clone(), value);
|
||||
|
||||
// You're auto-bonded forever, here. We might improve this by only bonding when
|
||||
// you actually validate/nominate and remove once you unbond __everything__.
|
||||
@@ -1463,21 +1527,21 @@ pub mod pallet {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pay out all the stakers behind a single validator for a single era.
|
||||
/// Pay out next page of the stakers behind a validator for the given era.
|
||||
///
|
||||
/// - `validator_stash` is the stash account of the validator. Their nominators, up to
|
||||
/// `T::MaxNominatorRewardedPerValidator`, will also receive their rewards.
|
||||
/// - `validator_stash` is the stash account of the validator.
|
||||
/// - `era` may be any era between `[current_era - history_depth; current_era]`.
|
||||
///
|
||||
/// The origin of this call must be _Signed_. Any account can call this function, even if
|
||||
/// it is not one of the stakers.
|
||||
///
|
||||
/// ## Complexity
|
||||
/// - At most O(MaxNominatorRewardedPerValidator).
|
||||
/// The reward payout could be paged in case there are too many nominators backing the
|
||||
/// `validator_stash`. This call will payout unpaid pages in an ascending order. To claim a
|
||||
/// specific page, use `payout_stakers_by_page`.`
|
||||
///
|
||||
/// If all pages are claimed, it returns an error `InvalidPage`.
|
||||
#[pallet::call_index(18)]
|
||||
#[pallet::weight(T::WeightInfo::payout_stakers_alive_staked(
|
||||
T::MaxNominatorRewardedPerValidator::get()
|
||||
))]
|
||||
#[pallet::weight(T::WeightInfo::payout_stakers_alive_staked(T::MaxExposurePageSize::get()))]
|
||||
pub fn payout_stakers(
|
||||
origin: OriginFor<T>,
|
||||
validator_stash: T::AccountId,
|
||||
@@ -1779,6 +1843,35 @@ pub mod pallet {
|
||||
MinCommission::<T>::put(new);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pay out a page of the stakers behind a validator for the given era and page.
|
||||
///
|
||||
/// - `validator_stash` is the stash account of the validator.
|
||||
/// - `era` may be any era between `[current_era - history_depth; current_era]`.
|
||||
/// - `page` is the page index of nominators to pay out with value between 0 and
|
||||
/// `num_nominators / T::MaxExposurePageSize`.
|
||||
///
|
||||
/// The origin of this call must be _Signed_. Any account can call this function, even if
|
||||
/// it is not one of the stakers.
|
||||
///
|
||||
/// If a validator has more than [`Config::MaxExposurePageSize`] nominators backing
|
||||
/// them, then the list of nominators is paged, with each page being capped at
|
||||
/// [`Config::MaxExposurePageSize`.] If a validator has more than one page of nominators,
|
||||
/// the call needs to be made for each page separately in order for all the nominators
|
||||
/// backing a validator to receive the reward. The nominators are not sorted across pages
|
||||
/// and so it should not be assumed the highest staker would be on the topmost page and vice
|
||||
/// versa. If rewards are not claimed in [`Config::HistoryDepth`] eras, they are lost.
|
||||
#[pallet::call_index(26)]
|
||||
#[pallet::weight(T::WeightInfo::payout_stakers_alive_staked(T::MaxExposurePageSize::get()))]
|
||||
pub fn payout_stakers_by_page(
|
||||
origin: OriginFor<T>,
|
||||
validator_stash: T::AccountId,
|
||||
era: EraIndex,
|
||||
page: Page,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
ensure_signed(origin)?;
|
||||
Self::do_payout_stakers_by_page(validator_stash, era, page)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user