mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-04-29 18:27:56 +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:
@@ -552,10 +552,10 @@ benchmarks! {
|
||||
}
|
||||
|
||||
payout_stakers_dead_controller {
|
||||
let n in 0 .. T::MaxNominatorRewardedPerValidator::get() as u32;
|
||||
let n in 0 .. T::MaxExposurePageSize::get() as u32;
|
||||
let (validator, nominators) = create_validator_with_nominators::<T>(
|
||||
n,
|
||||
T::MaxNominatorRewardedPerValidator::get() as u32,
|
||||
T::MaxExposurePageSize::get() as u32,
|
||||
true,
|
||||
true,
|
||||
RewardDestination::Controller,
|
||||
@@ -572,7 +572,7 @@ benchmarks! {
|
||||
let balance = T::Currency::free_balance(controller);
|
||||
ensure!(balance.is_zero(), "Controller has balance, but should be dead.");
|
||||
}
|
||||
}: payout_stakers(RawOrigin::Signed(caller), validator, current_era)
|
||||
}: payout_stakers_by_page(RawOrigin::Signed(caller), validator, current_era, 0)
|
||||
verify {
|
||||
let balance_after = T::Currency::free_balance(&validator_controller);
|
||||
ensure!(
|
||||
@@ -586,10 +586,10 @@ benchmarks! {
|
||||
}
|
||||
|
||||
payout_stakers_alive_staked {
|
||||
let n in 0 .. T::MaxNominatorRewardedPerValidator::get() as u32;
|
||||
let n in 0 .. T::MaxExposurePageSize::get() as u32;
|
||||
let (validator, nominators) = create_validator_with_nominators::<T>(
|
||||
n,
|
||||
T::MaxNominatorRewardedPerValidator::get() as u32,
|
||||
T::MaxExposurePageSize::get() as u32,
|
||||
false,
|
||||
true,
|
||||
RewardDestination::Staked,
|
||||
@@ -687,7 +687,6 @@ benchmarks! {
|
||||
let l = StakingLedger::<T>::new(
|
||||
stash.clone(),
|
||||
T::Currency::minimum_balance() - One::one(),
|
||||
Default::default(),
|
||||
);
|
||||
Ledger::<T>::insert(&controller, l);
|
||||
|
||||
@@ -760,7 +759,7 @@ benchmarks! {
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
let origin = RawOrigin::Signed(caller);
|
||||
let calls: Vec<_> = payout_calls_arg.iter().map(|arg|
|
||||
Call::<T>::payout_stakers { validator_stash: arg.0.clone(), era: arg.1 }.encode()
|
||||
Call::<T>::payout_stakers_by_page { validator_stash: arg.0.clone(), era: arg.1, page: 0 }.encode()
|
||||
).collect();
|
||||
}: {
|
||||
for call in calls {
|
||||
@@ -984,7 +983,7 @@ mod tests {
|
||||
|
||||
let (validator_stash, nominators) = create_validator_with_nominators::<Test>(
|
||||
n,
|
||||
<<Test as Config>::MaxNominatorRewardedPerValidator as Get<_>>::get(),
|
||||
<<Test as Config>::MaxExposurePageSize as Get<_>>::get(),
|
||||
false,
|
||||
false,
|
||||
RewardDestination::Staked,
|
||||
@@ -996,10 +995,11 @@ mod tests {
|
||||
let current_era = CurrentEra::<Test>::get().unwrap();
|
||||
|
||||
let original_free_balance = Balances::free_balance(&validator_stash);
|
||||
assert_ok!(Staking::payout_stakers(
|
||||
assert_ok!(Staking::payout_stakers_by_page(
|
||||
RuntimeOrigin::signed(1337),
|
||||
validator_stash,
|
||||
current_era
|
||||
current_era,
|
||||
0
|
||||
));
|
||||
let new_free_balance = Balances::free_balance(&validator_stash);
|
||||
|
||||
@@ -1014,7 +1014,7 @@ mod tests {
|
||||
|
||||
let (validator_stash, _nominators) = create_validator_with_nominators::<Test>(
|
||||
n,
|
||||
<<Test as Config>::MaxNominatorRewardedPerValidator as Get<_>>::get(),
|
||||
<<Test as Config>::MaxExposurePageSize as Get<_>>::get(),
|
||||
false,
|
||||
false,
|
||||
RewardDestination::Staked,
|
||||
|
||||
@@ -34,9 +34,8 @@
|
||||
use frame_support::{
|
||||
defensive,
|
||||
traits::{LockableCurrency, WithdrawReasons},
|
||||
BoundedVec,
|
||||
};
|
||||
use sp_staking::{EraIndex, StakingAccount};
|
||||
use sp_staking::StakingAccount;
|
||||
use sp_std::prelude::*;
|
||||
|
||||
use crate::{
|
||||
@@ -54,7 +53,7 @@ impl<T: Config> StakingLedger<T> {
|
||||
total: Zero::zero(),
|
||||
active: Zero::zero(),
|
||||
unlocking: Default::default(),
|
||||
claimed_rewards: Default::default(),
|
||||
legacy_claimed_rewards: Default::default(),
|
||||
controller: Some(stash),
|
||||
}
|
||||
}
|
||||
@@ -66,17 +65,13 @@ impl<T: Config> StakingLedger<T> {
|
||||
///
|
||||
/// Note: as the controller accounts are being deprecated, the stash account is the same as the
|
||||
/// controller account.
|
||||
pub fn new(
|
||||
stash: T::AccountId,
|
||||
stake: BalanceOf<T>,
|
||||
claimed_rewards: BoundedVec<EraIndex, T::HistoryDepth>,
|
||||
) -> Self {
|
||||
pub fn new(stash: T::AccountId, stake: BalanceOf<T>) -> Self {
|
||||
Self {
|
||||
stash: stash.clone(),
|
||||
active: stake,
|
||||
total: stake,
|
||||
unlocking: Default::default(),
|
||||
claimed_rewards,
|
||||
legacy_claimed_rewards: Default::default(),
|
||||
// controllers are deprecated and mapped 1-1 to stashes.
|
||||
controller: Some(stash),
|
||||
}
|
||||
@@ -240,8 +235,8 @@ pub struct StakingLedgerInspect<T: Config> {
|
||||
pub total: BalanceOf<T>,
|
||||
#[codec(compact)]
|
||||
pub active: BalanceOf<T>,
|
||||
pub unlocking: BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
|
||||
pub claimed_rewards: BoundedVec<EraIndex, T::HistoryDepth>,
|
||||
pub unlocking: frame_support::BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
|
||||
pub legacy_claimed_rewards: frame_support::BoundedVec<sp_staking::EraIndex, T::HistoryDepth>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -251,7 +246,7 @@ impl<T: Config> PartialEq<StakingLedgerInspect<T>> for StakingLedger<T> {
|
||||
self.total == other.total &&
|
||||
self.active == other.active &&
|
||||
self.unlocking == other.unlocking &&
|
||||
self.claimed_rewards == other.claimed_rewards
|
||||
self.legacy_claimed_rewards == other.legacy_claimed_rewards
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -112,11 +112,15 @@
|
||||
//! The **reward and slashing** procedure is the core of the Staking pallet, attempting to _embrace
|
||||
//! valid behavior_ while _punishing any misbehavior or lack of availability_.
|
||||
//!
|
||||
//! Rewards must be claimed for each era before it gets too old by `$HISTORY_DEPTH` using the
|
||||
//! `payout_stakers` call. Any account can call `payout_stakers`, which pays the reward to the
|
||||
//! validator as well as its nominators. Only the [`Config::MaxNominatorRewardedPerValidator`]
|
||||
//! biggest stakers can claim their reward. This is to limit the i/o cost to mutate storage for each
|
||||
//! nominator's account.
|
||||
//! Rewards must be claimed for each era before it gets too old by
|
||||
//! [`HistoryDepth`](`Config::HistoryDepth`) using the `payout_stakers` call. Any account can call
|
||||
//! `payout_stakers`, which pays the reward to the validator as well as its nominators. Only
|
||||
//! [`Config::MaxExposurePageSize`] nominator rewards can be claimed in a single call. When the
|
||||
//! number of nominators exceeds [`Config::MaxExposurePageSize`], then the exposed nominators are
|
||||
//! stored in multiple pages, with each page containing up to
|
||||
//! [`Config::MaxExposurePageSize`] nominators. To pay out all nominators, `payout_stakers` must be
|
||||
//! called once for each available page. Paging exists to limit the i/o cost to mutate storage for
|
||||
//! each nominator's account.
|
||||
//!
|
||||
//! Slashing can occur at any point in time, once misbehavior is reported. Once slashing is
|
||||
//! determined, a value is deducted from the balance of the validator and all the nominators who
|
||||
@@ -224,13 +228,13 @@
|
||||
//! The validator can declare an amount, named [`commission`](ValidatorPrefs::commission), that does
|
||||
//! not get shared with the nominators at each reward payout through its [`ValidatorPrefs`]. This
|
||||
//! value gets deducted from the total reward that is paid to the validator and its nominators. The
|
||||
//! remaining portion is split pro rata among the validator and the top
|
||||
//! [`Config::MaxNominatorRewardedPerValidator`] nominators that nominated the validator,
|
||||
//! proportional to the value staked behind the validator (_i.e._ dividing the
|
||||
//! remaining portion is split pro rata among the validator and the nominators that nominated the
|
||||
//! validator, proportional to the value staked behind the validator (_i.e._ dividing the
|
||||
//! [`own`](Exposure::own) or [`others`](Exposure::others) by [`total`](Exposure::total) in
|
||||
//! [`Exposure`]). Note that the pro rata division of rewards uses the total exposure behind the
|
||||
//! validator, *not* just the exposure of the validator and the top
|
||||
//! [`Config::MaxNominatorRewardedPerValidator`] nominators.
|
||||
//! [`Exposure`]). Note that payouts are made in pages with each page capped at
|
||||
//! [`Config::MaxExposurePageSize`] nominators. The distribution of nominators across
|
||||
//! pages may be unsorted. The total commission is paid out proportionally across pages based on the
|
||||
//! total stake of the page.
|
||||
//!
|
||||
//! All entities who receive a reward have the option to choose their reward destination through the
|
||||
//! [`Payee`] storage item (see
|
||||
@@ -303,7 +307,10 @@ mod pallet;
|
||||
|
||||
use codec::{Decode, Encode, HasCompact, MaxEncodedLen};
|
||||
use frame_support::{
|
||||
traits::{ConstU32, Currency, Defensive, Get, LockIdentifier},
|
||||
defensive, defensive_assert,
|
||||
traits::{
|
||||
ConstU32, Currency, Defensive, DefensiveMax, DefensiveSaturating, Get, LockIdentifier,
|
||||
},
|
||||
weights::Weight,
|
||||
BoundedVec, CloneNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound,
|
||||
};
|
||||
@@ -313,11 +320,12 @@ use sp_runtime::{
|
||||
traits::{AtLeast32BitUnsigned, Convert, StaticLookup, Zero},
|
||||
Perbill, Perquintill, Rounding, RuntimeDebug, Saturating,
|
||||
};
|
||||
pub use sp_staking::StakerStatus;
|
||||
use sp_staking::{
|
||||
offence::{Offence, OffenceError, ReportOffence},
|
||||
EraIndex, OnStakingUpdate, SessionIndex, StakingAccount,
|
||||
EraIndex, ExposurePage, OnStakingUpdate, Page, PagedExposureMetadata, SessionIndex,
|
||||
StakingAccount,
|
||||
};
|
||||
pub use sp_staking::{Exposure, IndividualExposure, StakerStatus};
|
||||
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
|
||||
pub use weights::WeightInfo;
|
||||
|
||||
@@ -457,21 +465,29 @@ pub struct UnlockChunk<Balance: HasCompact + MaxEncodedLen> {
|
||||
pub struct StakingLedger<T: Config> {
|
||||
/// The stash account whose balance is actually locked and at stake.
|
||||
pub stash: T::AccountId,
|
||||
|
||||
/// The total amount of the stash's balance that we are currently accounting for.
|
||||
/// It's just `active` plus all the `unlocking` balances.
|
||||
#[codec(compact)]
|
||||
pub total: BalanceOf<T>,
|
||||
|
||||
/// The total amount of the stash's balance that will be at stake in any forthcoming
|
||||
/// rounds.
|
||||
#[codec(compact)]
|
||||
pub active: BalanceOf<T>,
|
||||
|
||||
/// Any balance that is becoming free, which may eventually be transferred out of the stash
|
||||
/// (assuming it doesn't get slashed first). It is assumed that this will be treated as a first
|
||||
/// in, first out queue where the new (higher value) eras get pushed on the back.
|
||||
pub unlocking: BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
|
||||
|
||||
/// List of eras for which the stakers behind a validator have claimed rewards. Only updated
|
||||
/// for validators.
|
||||
pub claimed_rewards: BoundedVec<EraIndex, T::HistoryDepth>,
|
||||
///
|
||||
/// This is deprecated as of V14 in favor of `T::ClaimedRewards` and will be removed in future.
|
||||
/// Refer to issue <https://github.com/paritytech/polkadot-sdk/issues/433>
|
||||
pub legacy_claimed_rewards: BoundedVec<EraIndex, T::HistoryDepth>,
|
||||
|
||||
/// The controller associated with this ledger's stash.
|
||||
///
|
||||
/// This is not stored on-chain, and is only bundled when the ledger is read from storage.
|
||||
@@ -507,7 +523,7 @@ impl<T: Config> StakingLedger<T> {
|
||||
total,
|
||||
active: self.active,
|
||||
unlocking,
|
||||
claimed_rewards: self.claimed_rewards,
|
||||
legacy_claimed_rewards: self.legacy_claimed_rewards,
|
||||
controller: self.controller,
|
||||
}
|
||||
}
|
||||
@@ -708,32 +724,50 @@ pub struct Nominations<T: Config> {
|
||||
pub suppressed: bool,
|
||||
}
|
||||
|
||||
/// The amount of exposure (to slashing) than an individual nominator has.
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
pub struct IndividualExposure<AccountId, Balance: HasCompact> {
|
||||
/// The stash account of the nominator in question.
|
||||
pub who: AccountId,
|
||||
/// Amount of funds exposed.
|
||||
#[codec(compact)]
|
||||
pub value: Balance,
|
||||
/// Facade struct to encapsulate `PagedExposureMetadata` and a single page of `ExposurePage`.
|
||||
///
|
||||
/// This is useful where we need to take into account the validator's own stake and total exposure
|
||||
/// in consideration, in addition to the individual nominators backing them.
|
||||
#[derive(Encode, Decode, RuntimeDebug, TypeInfo, PartialEq, Eq)]
|
||||
struct PagedExposure<AccountId, Balance: HasCompact + codec::MaxEncodedLen> {
|
||||
exposure_metadata: PagedExposureMetadata<Balance>,
|
||||
exposure_page: ExposurePage<AccountId, Balance>,
|
||||
}
|
||||
|
||||
/// A snapshot of the stake backing a single validator in the system.
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
pub struct Exposure<AccountId, Balance: HasCompact> {
|
||||
/// The total balance backing this validator.
|
||||
#[codec(compact)]
|
||||
pub total: Balance,
|
||||
/// The validator's own stash that is exposed.
|
||||
#[codec(compact)]
|
||||
pub own: Balance,
|
||||
/// The portions of nominators stashes that are exposed.
|
||||
pub others: Vec<IndividualExposure<AccountId, Balance>>,
|
||||
}
|
||||
impl<AccountId, Balance: HasCompact + Copy + AtLeast32BitUnsigned + codec::MaxEncodedLen>
|
||||
PagedExposure<AccountId, Balance>
|
||||
{
|
||||
/// Create a new instance of `PagedExposure` from legacy clipped exposures.
|
||||
pub fn from_clipped(exposure: Exposure<AccountId, Balance>) -> Self {
|
||||
Self {
|
||||
exposure_metadata: PagedExposureMetadata {
|
||||
total: exposure.total,
|
||||
own: exposure.own,
|
||||
nominator_count: exposure.others.len() as u32,
|
||||
page_count: 1,
|
||||
},
|
||||
exposure_page: ExposurePage { page_total: exposure.total, others: exposure.others },
|
||||
}
|
||||
}
|
||||
|
||||
impl<AccountId, Balance: Default + HasCompact> Default for Exposure<AccountId, Balance> {
|
||||
fn default() -> Self {
|
||||
Self { total: Default::default(), own: Default::default(), others: vec![] }
|
||||
/// Returns total exposure of this validator across pages
|
||||
pub fn total(&self) -> Balance {
|
||||
self.exposure_metadata.total
|
||||
}
|
||||
|
||||
/// Returns total exposure of this validator for the current page
|
||||
pub fn page_total(&self) -> Balance {
|
||||
self.exposure_page.page_total + self.exposure_metadata.own
|
||||
}
|
||||
|
||||
/// Returns validator's own stake that is exposed
|
||||
pub fn own(&self) -> Balance {
|
||||
self.exposure_metadata.own
|
||||
}
|
||||
|
||||
/// Returns the portions of nominators stashes that are exposed in this page.
|
||||
pub fn others(&self) -> &Vec<IndividualExposure<AccountId, Balance>> {
|
||||
&self.exposure_page.others
|
||||
}
|
||||
}
|
||||
|
||||
@@ -985,6 +1019,195 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper struct for Era related information. It is not a pure encapsulation as these storage
|
||||
/// items can be accessed directly but nevertheless, its recommended to use `EraInfo` where we
|
||||
/// can and add more functions to it as needed.
|
||||
pub(crate) struct EraInfo<T>(sp_std::marker::PhantomData<T>);
|
||||
impl<T: Config> EraInfo<T> {
|
||||
/// Temporary function which looks at both (1) passed param `T::StakingLedger` for legacy
|
||||
/// non-paged rewards, and (2) `T::ClaimedRewards` for paged rewards. This function can be
|
||||
/// removed once `T::HistoryDepth` eras have passed and none of the older non-paged rewards
|
||||
/// are relevant/claimable.
|
||||
// Refer tracker issue for cleanup: #13034
|
||||
pub(crate) fn is_rewards_claimed_with_legacy_fallback(
|
||||
era: EraIndex,
|
||||
ledger: &StakingLedger<T>,
|
||||
validator: &T::AccountId,
|
||||
page: Page,
|
||||
) -> bool {
|
||||
ledger.legacy_claimed_rewards.binary_search(&era).is_ok() ||
|
||||
Self::is_rewards_claimed(era, validator, page)
|
||||
}
|
||||
|
||||
/// Check if the rewards for the given era and page index have been claimed.
|
||||
///
|
||||
/// This is only used for paged rewards. Once older non-paged rewards are no longer
|
||||
/// relevant, `is_rewards_claimed_with_legacy_fallback` can be removed and this function can
|
||||
/// be made public.
|
||||
fn is_rewards_claimed(era: EraIndex, validator: &T::AccountId, page: Page) -> bool {
|
||||
ClaimedRewards::<T>::get(era, validator).contains(&page)
|
||||
}
|
||||
|
||||
/// Get exposure for a validator at a given era and page.
|
||||
///
|
||||
/// This builds a paged exposure from `PagedExposureMetadata` and `ExposurePage` of the
|
||||
/// validator. For older non-paged exposure, it returns the clipped exposure directly.
|
||||
pub(crate) fn get_paged_exposure(
|
||||
era: EraIndex,
|
||||
validator: &T::AccountId,
|
||||
page: Page,
|
||||
) -> Option<PagedExposure<T::AccountId, BalanceOf<T>>> {
|
||||
let overview = <ErasStakersOverview<T>>::get(&era, validator);
|
||||
|
||||
// return clipped exposure if page zero and paged exposure does not exist
|
||||
// exists for backward compatibility and can be removed as part of #13034
|
||||
if overview.is_none() && page == 0 {
|
||||
return Some(PagedExposure::from_clipped(<ErasStakersClipped<T>>::get(era, validator)))
|
||||
}
|
||||
|
||||
// no exposure for this validator
|
||||
if overview.is_none() {
|
||||
return None
|
||||
}
|
||||
|
||||
let overview = overview.expect("checked above; qed");
|
||||
|
||||
// validator stake is added only in page zero
|
||||
let validator_stake = if page == 0 { overview.own } else { Zero::zero() };
|
||||
|
||||
// since overview is present, paged exposure will always be present except when a
|
||||
// validator has only own stake and no nominator stake.
|
||||
let exposure_page = <ErasStakersPaged<T>>::get((era, validator, page)).unwrap_or_default();
|
||||
|
||||
// build the exposure
|
||||
Some(PagedExposure {
|
||||
exposure_metadata: PagedExposureMetadata { own: validator_stake, ..overview },
|
||||
exposure_page,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get full exposure of the validator at a given era.
|
||||
pub(crate) fn get_full_exposure(
|
||||
era: EraIndex,
|
||||
validator: &T::AccountId,
|
||||
) -> Exposure<T::AccountId, BalanceOf<T>> {
|
||||
let overview = <ErasStakersOverview<T>>::get(&era, validator);
|
||||
|
||||
if overview.is_none() {
|
||||
return ErasStakers::<T>::get(era, validator)
|
||||
}
|
||||
|
||||
let overview = overview.expect("checked above; qed");
|
||||
|
||||
let mut others = Vec::with_capacity(overview.nominator_count as usize);
|
||||
for page in 0..overview.page_count {
|
||||
let nominators = <ErasStakersPaged<T>>::get((era, validator, page));
|
||||
others.append(&mut nominators.map(|n| n.others).defensive_unwrap_or_default());
|
||||
}
|
||||
|
||||
Exposure { total: overview.total, own: overview.own, others }
|
||||
}
|
||||
|
||||
/// Returns the number of pages of exposure a validator has for the given era.
|
||||
///
|
||||
/// For eras where paged exposure does not exist, this returns 1 to keep backward compatibility.
|
||||
pub(crate) fn get_page_count(era: EraIndex, validator: &T::AccountId) -> Page {
|
||||
<ErasStakersOverview<T>>::get(&era, validator)
|
||||
.map(|overview| {
|
||||
if overview.page_count == 0 && overview.own > Zero::zero() {
|
||||
// Even though there are no nominator pages, there is still validator's own
|
||||
// stake exposed which needs to be paid out in a page.
|
||||
1
|
||||
} else {
|
||||
overview.page_count
|
||||
}
|
||||
})
|
||||
// Always returns 1 page for older non-paged exposure.
|
||||
// FIXME: Can be cleaned up with issue #13034.
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
/// Returns the next page that can be claimed or `None` if nothing to claim.
|
||||
pub(crate) fn get_next_claimable_page(
|
||||
era: EraIndex,
|
||||
validator: &T::AccountId,
|
||||
ledger: &StakingLedger<T>,
|
||||
) -> Option<Page> {
|
||||
if Self::is_non_paged_exposure(era, validator) {
|
||||
return match ledger.legacy_claimed_rewards.binary_search(&era) {
|
||||
// already claimed
|
||||
Ok(_) => None,
|
||||
// Non-paged exposure is considered as a single page
|
||||
Err(_) => Some(0),
|
||||
}
|
||||
}
|
||||
|
||||
// Find next claimable page of paged exposure.
|
||||
let page_count = Self::get_page_count(era, validator);
|
||||
let all_claimable_pages: Vec<Page> = (0..page_count).collect();
|
||||
let claimed_pages = ClaimedRewards::<T>::get(era, validator);
|
||||
|
||||
all_claimable_pages.into_iter().find(|p| !claimed_pages.contains(p))
|
||||
}
|
||||
|
||||
/// Checks if exposure is paged or not.
|
||||
fn is_non_paged_exposure(era: EraIndex, validator: &T::AccountId) -> bool {
|
||||
<ErasStakersClipped<T>>::contains_key(&era, validator)
|
||||
}
|
||||
|
||||
/// Returns validator commission for this era and page.
|
||||
pub(crate) fn get_validator_commission(
|
||||
era: EraIndex,
|
||||
validator_stash: &T::AccountId,
|
||||
) -> Perbill {
|
||||
<ErasValidatorPrefs<T>>::get(&era, validator_stash).commission
|
||||
}
|
||||
|
||||
/// Creates an entry to track validator reward has been claimed for a given era and page.
|
||||
/// Noop if already claimed.
|
||||
pub(crate) fn set_rewards_as_claimed(era: EraIndex, validator: &T::AccountId, page: Page) {
|
||||
let mut claimed_pages = ClaimedRewards::<T>::get(era, validator);
|
||||
|
||||
// this should never be called if the reward has already been claimed
|
||||
if claimed_pages.contains(&page) {
|
||||
defensive!("Trying to set an already claimed reward");
|
||||
// nevertheless don't do anything since the page already exist in claimed rewards.
|
||||
return
|
||||
}
|
||||
|
||||
// add page to claimed entries
|
||||
claimed_pages.push(page);
|
||||
ClaimedRewards::<T>::insert(era, validator, claimed_pages);
|
||||
}
|
||||
|
||||
/// Store exposure for elected validators at start of an era.
|
||||
pub(crate) fn set_exposure(
|
||||
era: EraIndex,
|
||||
validator: &T::AccountId,
|
||||
exposure: Exposure<T::AccountId, BalanceOf<T>>,
|
||||
) {
|
||||
let page_size = T::MaxExposurePageSize::get().defensive_max(1);
|
||||
|
||||
let nominator_count = exposure.others.len();
|
||||
// expected page count is the number of nominators divided by the page size, rounded up.
|
||||
let expected_page_count =
|
||||
nominator_count.defensive_saturating_add(page_size as usize - 1) / page_size as usize;
|
||||
|
||||
let (exposure_metadata, exposure_pages) = exposure.into_pages(page_size);
|
||||
defensive_assert!(exposure_pages.len() == expected_page_count, "unexpected page count");
|
||||
|
||||
<ErasStakersOverview<T>>::insert(era, &validator, &exposure_metadata);
|
||||
exposure_pages.iter().enumerate().for_each(|(page, paged_exposure)| {
|
||||
<ErasStakersPaged<T>>::insert((era, &validator, page as Page), &paged_exposure);
|
||||
});
|
||||
}
|
||||
|
||||
/// Store total exposure for all the elected validators in the era.
|
||||
pub(crate) fn set_total_stake(era: EraIndex, total_stake: BalanceOf<T>) {
|
||||
<ErasTotalStake<T>>::insert(era, total_stake);
|
||||
}
|
||||
}
|
||||
|
||||
/// Configurations of the benchmarking of the pallet.
|
||||
pub trait BenchmarkingConfig {
|
||||
/// The maximum number of validators to use.
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
|
||||
//! Storage migrations for the Staking pallet.
|
||||
//! Storage migrations for the Staking pallet. The changelog for this is maintained at
|
||||
//! [CHANGELOG.md](https://github.com/paritytech/substrate/blob/master/frame/staking/CHANGELOG.md).
|
||||
|
||||
use super::*;
|
||||
use frame_election_provider_support::SortedListProvider;
|
||||
@@ -58,6 +59,49 @@ impl Default for ObsoleteReleases {
|
||||
#[storage_alias]
|
||||
type StorageVersion<T: Config> = StorageValue<Pallet<T>, ObsoleteReleases, ValueQuery>;
|
||||
|
||||
/// Migration of era exposure storage items to paged exposures.
|
||||
/// Changelog: [v14.](https://github.com/paritytech/substrate/blob/ankan/paged-rewards-rebased2/frame/staking/CHANGELOG.md#14)
|
||||
pub mod v14 {
|
||||
use super::*;
|
||||
|
||||
pub struct MigrateToV14<T>(sp_std::marker::PhantomData<T>);
|
||||
impl<T: Config> OnRuntimeUpgrade for MigrateToV14<T> {
|
||||
fn on_runtime_upgrade() -> Weight {
|
||||
let current = Pallet::<T>::current_storage_version();
|
||||
let on_chain = Pallet::<T>::on_chain_storage_version();
|
||||
|
||||
if current == 14 && on_chain == 13 {
|
||||
current.put::<Pallet<T>>();
|
||||
|
||||
log!(info, "v14 applied successfully.");
|
||||
T::DbWeight::get().reads_writes(1, 1)
|
||||
} else {
|
||||
log!(warn, "v14 not applied.");
|
||||
T::DbWeight::get().reads(1)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "try-runtime")]
|
||||
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
|
||||
frame_support::ensure!(
|
||||
Pallet::<T>::on_chain_storage_version() == 13,
|
||||
"Required v13 before upgrading to v14."
|
||||
);
|
||||
|
||||
Ok(Default::default())
|
||||
}
|
||||
|
||||
#[cfg(feature = "try-runtime")]
|
||||
fn post_upgrade(_state: Vec<u8>) -> Result<(), TryRuntimeError> {
|
||||
frame_support::ensure!(
|
||||
Pallet::<T>::on_chain_storage_version() == 14,
|
||||
"v14 not applied"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod v13 {
|
||||
use super::*;
|
||||
|
||||
@@ -113,9 +157,9 @@ pub mod v12 {
|
||||
#[storage_alias]
|
||||
type HistoryDepth<T: Config> = StorageValue<Pallet<T>, u32, ValueQuery>;
|
||||
|
||||
/// Clean up `HistoryDepth` from storage.
|
||||
/// Clean up `T::HistoryDepth` from storage.
|
||||
///
|
||||
/// We will be depending on the configurable value of `HistoryDepth` post
|
||||
/// We will be depending on the configurable value of `T::HistoryDepth` post
|
||||
/// this release.
|
||||
pub struct MigrateToV12<T>(sp_std::marker::PhantomData<T>);
|
||||
impl<T: Config> OnRuntimeUpgrade for MigrateToV12<T> {
|
||||
|
||||
@@ -25,8 +25,8 @@ use frame_election_provider_support::{
|
||||
use frame_support::{
|
||||
assert_ok, ord_parameter_types, parameter_types,
|
||||
traits::{
|
||||
ConstU32, ConstU64, Currency, EitherOfDiverse, FindAuthor, Get, Hooks, Imbalance,
|
||||
OnUnbalanced, OneSessionHandler,
|
||||
ConstU64, Currency, EitherOfDiverse, FindAuthor, Get, Hooks, Imbalance, OnUnbalanced,
|
||||
OneSessionHandler,
|
||||
},
|
||||
weights::constants::RocksDbWeight,
|
||||
};
|
||||
@@ -236,6 +236,7 @@ const THRESHOLDS: [sp_npos_elections::VoteWeight; 9] =
|
||||
parameter_types! {
|
||||
pub static BagThresholds: &'static [sp_npos_elections::VoteWeight] = &THRESHOLDS;
|
||||
pub static HistoryDepth: u32 = 80;
|
||||
pub static MaxExposurePageSize: u32 = 64;
|
||||
pub static MaxUnlockingChunks: u32 = 32;
|
||||
pub static RewardOnUnbalanceWasCalled: bool = false;
|
||||
pub static MaxWinners: u32 = 100;
|
||||
@@ -304,7 +305,7 @@ impl crate::pallet::pallet::Config for Test {
|
||||
type SessionInterface = Self;
|
||||
type EraPayout = ConvertCurve<RewardCurve>;
|
||||
type NextNewSession = Session;
|
||||
type MaxNominatorRewardedPerValidator = ConstU32<64>;
|
||||
type MaxExposurePageSize = MaxExposurePageSize;
|
||||
type OffendingValidatorsThreshold = OffendingValidatorsThreshold;
|
||||
type ElectionProvider = onchain::OnChainExecution<OnChainSeqPhragmen>;
|
||||
type GenesisElectionProvider = Self::ElectionProvider;
|
||||
@@ -760,7 +761,7 @@ pub(crate) fn on_offence_now(
|
||||
pub(crate) fn add_slash(who: &AccountId) {
|
||||
on_offence_now(
|
||||
&[OffenceDetails {
|
||||
offender: (*who, Staking::eras_stakers(active_era(), *who)),
|
||||
offender: (*who, Staking::eras_stakers(active_era(), who)),
|
||||
reporters: vec![],
|
||||
}],
|
||||
&[Perbill::from_percent(10)],
|
||||
@@ -778,7 +779,14 @@ pub(crate) fn make_all_reward_payment(era: EraIndex) {
|
||||
// reward validators
|
||||
for validator_controller in validators_with_reward.iter().filter_map(Staking::bonded) {
|
||||
let ledger = <Ledger<Test>>::get(&validator_controller).unwrap();
|
||||
assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), ledger.stash, era));
|
||||
for page in 0..EraInfo::<Test>::get_page_count(era, &ledger.stash) {
|
||||
assert_ok!(Staking::payout_stakers_by_page(
|
||||
RuntimeOrigin::signed(1337),
|
||||
ledger.stash,
|
||||
era,
|
||||
page
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1025
-384
File diff suppressed because it is too large
Load Diff
Generated
+1040
-1011
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user