// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see .
//! # Staking Module
//!
//! The Staking module is used to manage funds at stake by network maintainers.
//!
//! - [`staking::Trait`](./trait.Trait.html)
//! - [`Call`](./enum.Call.html)
//! - [`Module`](./struct.Module.html)
//!
//! ## Overview
//!
//! The Staking module is the means by which a set of network maintainers (known as _authorities_
//! in some contexts and _validators_ in others) are chosen based upon those who voluntarily place
//! funds under deposit. Under deposit, those funds are rewarded under normal operation but are
//! held at pain of _slash_ (expropriation) should the staked maintainer be found not to be
//! discharging its duties properly.
//!
//! ### Terminology
//!
//!
//! - Staking: The process of locking up funds for some time, placing them at risk of slashing
//! (loss) in order to become a rewarded maintainer of the network.
//! - Validating: The process of running a node to actively maintain the network, either by
//! producing blocks or guaranteeing finality of the chain.
//! - Nominating: The process of placing staked funds behind one or more validators in order to
//! share in any reward, and punishment, they take.
//! - Stash account: The account holding an owner's funds used for staking.
//! - Controller account: The account that controls an owner's funds for staking.
//! - Era: A (whole) number of sessions, which is the period that the validator set (and each
//! validator's active nominator set) is recalculated and where rewards are paid out.
//! - Slash: The punishment of a staker by reducing its funds.
//!
//! ### Goals
//!
//!
//! The staking system in Substrate NPoS is designed to make the following possible:
//!
//! - Stake funds that are controlled by a cold wallet.
//! - Withdraw some, or deposit more, funds without interrupting the role of an entity.
//! - Switch between roles (nominator, validator, idle) with minimal overhead.
//!
//! ### Scenarios
//!
//! #### Staking
//!
//! Almost any interaction with the Staking module requires a process of _**bonding**_ (also known
//! as being a _staker_). To become *bonded*, a fund-holding account known as the _stash account_,
//! which holds some or all of the funds that become frozen in place as part of the staking process,
//! is paired with an active **controller** account, which issues instructions on how they shall be
//! used.
//!
//! An account pair can become bonded using the [`bond`](./enum.Call.html#variant.bond) call.
//!
//! Stash accounts can change their associated controller using the
//! [`set_controller`](./enum.Call.html#variant.set_controller) call.
//!
//! There are three possible roles that any staked account pair can be in: `Validator`, `Nominator`
//! and `Idle` (defined in [`StakerStatus`](./enum.StakerStatus.html)). There are three
//! corresponding instructions to change between roles, namely:
//! [`validate`](./enum.Call.html#variant.validate),
//! [`nominate`](./enum.Call.html#variant.nominate), and [`chill`](./enum.Call.html#variant.chill).
//!
//! #### Validating
//!
//! A **validator** takes the role of either validating blocks or ensuring their finality,
//! maintaining the veracity of the network. A validator should avoid both any sort of malicious
//! misbehavior and going offline. Bonded accounts that state interest in being a validator do NOT
//! get immediately chosen as a validator. Instead, they are declared as a _candidate_ and they
//! _might_ get elected at the _next era_ as a validator. The result of the election is determined
//! by nominators and their votes.
//!
//! An account can become a validator candidate via the
//! [`validate`](./enum.Call.html#variant.validate) call.
//!
//! #### Nomination
//!
//! A **nominator** does not take any _direct_ role in maintaining the network, instead, it votes on
//! a set of validators to be elected. Once interest in nomination is stated by an account, it
//! takes effect at the next election round. The funds in the nominator's stash account indicate the
//! _weight_ of its vote. Both the rewards and any punishment that a validator earns are shared
//! between the validator and its nominators. This rule incentivizes the nominators to NOT vote for
//! the misbehaving/offline validators as much as possible, simply because the nominators will also
//! lose funds if they vote poorly.
//!
//! An account can become a nominator via the [`nominate`](enum.Call.html#variant.nominate) call.
//!
//! #### Rewards and Slash
//!
//! The **reward and slashing** procedure is the core of the Staking module, 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 [`T::MaxNominatorRewardedPerValidator`] biggest stakers can claim their reward. This
//! is 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
//! voted for this validator (values are deducted from the _stash_ account of the slashed entity).
//!
//! Slashing logic is further described in the documentation of the `slashing` module.
//!
//! Similar to slashing, rewards are also shared among a validator and its associated nominators.
//! Yet, the reward funds are not always transferred to the stash account and can be configured.
//! See [Reward Calculation](#reward-calculation) for more details.
//!
//! #### Chilling
//!
//! Finally, any of the roles above can choose to step back temporarily and just chill for a while.
//! This means that if they are a nominator, they will not be considered as voters anymore and if
//! they are validators, they will no longer be a candidate for the next election.
//!
//! An account can step back via the [`chill`](enum.Call.html#variant.chill) call.
//!
//! ### Session managing
//!
//! The module implement the trait `SessionManager`. Which is the only API to query new validator
//! set and allowing these validator set to be rewarded once their era is ended.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! The dispatchable functions of the Staking module enable the steps needed for entities to accept
//! and change their role, alongside some helper functions to get/set the metadata of the module.
//!
//! ### Public Functions
//!
//! The Staking module contains many public storage items and (im)mutable functions.
//!
//! ## Usage
//!
//! ### Example: Rewarding a validator by id.
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_system::{self as system, ensure_signed};
//! use pallet_staking::{self as staking};
//!
//! pub trait Trait: staking::Trait {}
//!
//! decl_module! {
//! pub struct Module for enum Call where origin: T::Origin {
//! /// Reward a validator.
//! #[weight = frame_support::weights::SimpleDispatchInfo::default()]
//! pub fn reward_myself(origin) -> dispatch::DispatchResult {
//! let reported = ensure_signed(origin)?;
//! >::reward_by_ids(vec![(reported, 10)]);
//! Ok(())
//! }
//! }
//! }
//! # fn main() { }
//! ```
//!
//! ## Implementation Details
//!
//! ### Reward Calculation
//!
//! Validators and nominators are rewarded at the end of each era. The total reward of an era is
//! calculated using the era duration and the staking rate (the total amount of tokens staked by
//! nominators and validators, divided by the total token supply). It aims to incentivize toward a
//! defined staking rate. The full specification can be found
//! [here](https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model).
//!
//! Total reward is split among validators and their nominators depending on the number of points
//! they received during the era. Points are added to a validator using
//! [`reward_by_ids`](./enum.Call.html#variant.reward_by_ids) or
//! [`reward_by_indices`](./enum.Call.html#variant.reward_by_indices).
//!
//! [`Module`](./struct.Module.html) implements
//! [`pallet_authorship::EventHandler`](../pallet_authorship/trait.EventHandler.html) to add reward
//! points to block producer and block producer of referenced uncles.
//!
//! The validator and its nominator split their reward as following:
//!
//! The validator can declare an amount, named
//! [`commission`](./struct.ValidatorPrefs.html#structfield.commission), that does not
//! get shared with the nominators at each reward payout through its
//! [`ValidatorPrefs`](./struct.ValidatorPrefs.html). This value gets deducted from the total reward
//! that is paid to the validator and its nominators. The remaining portion is split among the
//! validator and all of the nominators that nominated the validator, proportional to the value
//! staked behind this validator (_i.e._ dividing the
//! [`own`](./struct.Exposure.html#structfield.own) or
//! [`others`](./struct.Exposure.html#structfield.others) by
//! [`total`](./struct.Exposure.html#structfield.total) in [`Exposure`](./struct.Exposure.html)).
//!
//! All entities who receive a reward have the option to choose their reward destination
//! through the [`Payee`](./struct.Payee.html) storage item (see
//! [`set_payee`](enum.Call.html#variant.set_payee)), to be one of the following:
//!
//! - Controller account, (obviously) not increasing the staked value.
//! - Stash account, not increasing the staked value.
//! - Stash account, also increasing the staked value.
//!
//! ### Additional Fund Management Operations
//!
//! Any funds already placed into stash can be the target of the following operations:
//!
//! The controller account can free a portion (or all) of the funds using the
//! [`unbond`](enum.Call.html#variant.unbond) call. Note that the funds are not immediately
//! accessible. Instead, a duration denoted by [`BondingDuration`](./struct.BondingDuration.html)
//! (in number of eras) must pass until the funds can actually be removed. Once the
//! `BondingDuration` is over, the [`withdraw_unbonded`](./enum.Call.html#variant.withdraw_unbonded)
//! call can be used to actually withdraw the funds.
//!
//! Note that there is a limitation to the number of fund-chunks that can be scheduled to be
//! unlocked in the future via [`unbond`](enum.Call.html#variant.unbond). In case this maximum
//! (`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful
//! call to `withdraw_unbonded` to remove some of the chunks.
//!
//! ### Election Algorithm
//!
//! The current election algorithm is implemented based on Phragmén.
//! The reference implementation can be found
//! [here](https://github.com/w3f/consensus/tree/master/NPoS).
//!
//! The election algorithm, aside from electing the validators with the most stake value and votes,
//! tries to divide the nominator votes among candidates in an equal manner. To further assure this,
//! an optional post-processing can be applied that iteratively normalizes the nominator staked
//! values until the total difference among votes of a particular nominator are less than a
//! threshold.
//!
//! ## GenesisConfig
//!
//! The Staking module depends on the [`GenesisConfig`](./struct.GenesisConfig.html).
//! The `GenesisConfig` is optional and allow to set some initial stakers.
//!
//! ## Related Modules
//!
//! - [Balances](../pallet_balances/index.html): Used to manage values at stake.
//! - [Session](../pallet_session/index.html): Used to manage sessions. Also, a list of new
//! validators is stored in the Session module's `Validators` at the end of each era.
#![recursion_limit = "128"]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(feature = "testing-utils")]
pub mod testing_utils;
#[cfg(any(feature = "runtime-benchmarks", test))]
pub mod benchmarking;
pub mod slashing;
pub mod offchain_election;
pub mod inflation;
use sp_std::{
result,
prelude::*,
collections::btree_map::BTreeMap,
convert::{TryInto, From},
mem::size_of,
};
use codec::{HasCompact, Encode, Decode};
use frame_support::{
decl_module, decl_event, decl_storage, ensure, decl_error, debug,
weights::{SimpleDispatchInfo, Weight},
storage::IterableStorageMap,
dispatch::{IsSubType, DispatchResult},
traits::{
Currency, LockIdentifier, LockableCurrency, WithdrawReasons, OnUnbalanced, Imbalance, Get,
UnixTime, EstimateNextNewSession, EnsureOrigin,
}
};
use pallet_session::historical;
use sp_runtime::{
Perbill, PerU16, PerThing, RuntimeDebug,
curve::PiecewiseLinear,
traits::{
Convert, Zero, StaticLookup, CheckedSub, Saturating, SaturatedConversion, AtLeast32Bit,
Dispatchable,
},
transaction_validity::{
TransactionValidityError, TransactionValidity, ValidTransaction, InvalidTransaction,
TransactionSource, TransactionPriority,
},
};
use sp_staking::{
SessionIndex,
offence::{OnOffenceHandler, OffenceDetails, Offence, ReportOffence, OffenceError},
};
#[cfg(feature = "std")]
use sp_runtime::{Serialize, Deserialize};
use frame_system::{
self as system, ensure_signed, ensure_root, ensure_none,
offchain::SubmitUnsignedTransaction,
};
use sp_phragmen::{
ExtendedBalance, Assignment, PhragmenScore, PhragmenResult, build_support_map, evaluate_support,
elect, generate_compact_solution_type, is_score_better, VotingLimit, SupportMap,
};
const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4;
const STAKING_ID: LockIdentifier = *b"staking ";
pub const MAX_UNLOCKING_CHUNKS: usize = 32;
pub const MAX_NOMINATIONS: usize = ::LIMIT;
// syntactic sugar for logging
#[cfg(feature = "std")]
const LOG_TARGET: &'static str = "staking";
macro_rules! log {
($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
debug::native::$level!(
target: LOG_TARGET,
$patter $(, $values)*
)
};
}
/// Data type used to index nominators in the compact type
pub type NominatorIndex = u32;
/// Data type used to index validators in the compact type.
pub type ValidatorIndex = u16;
// Ensure the size of both ValidatorIndex and NominatorIndex. They both need to be well below usize.
static_assertions::const_assert!(size_of::() <= size_of::());
static_assertions::const_assert!(size_of::() <= size_of::());
/// Maximum number of stakers that can be stored in a snapshot.
pub(crate) const MAX_VALIDATORS: usize = ValidatorIndex::max_value() as usize;
pub(crate) const MAX_NOMINATORS: usize = NominatorIndex::max_value() as usize;
/// Counter for the number of eras that have passed.
pub type EraIndex = u32;
/// Counter for the number of "reward" points earned by a given validator.
pub type RewardPoint = u32;
// Note: Maximum nomination limit is set here -- 16.
generate_compact_solution_type!(pub GenericCompactAssignments, 16);
/// Information regarding the active era (era in used in session).
#[derive(Encode, Decode, RuntimeDebug)]
pub struct ActiveEraInfo {
/// Index of era.
index: EraIndex,
/// Moment of start expresed as millisecond from `$UNIX_EPOCH`.
///
/// Start can be none if start hasn't been set for the era yet,
/// Start is set on the first on_finalize of the era to guarantee usage of `Time`.
start: Option,
}
/// Accuracy used for on-chain phragmen.
pub type ChainAccuracy = Perbill;
/// Accuracy used for off-chain phragmen. This better be small.
pub type OffchainAccuracy = PerU16;
/// The balance type of this module.
pub type BalanceOf =
<::Currency as Currency<::AccountId>>::Balance;
/// The compact type for election solutions.
pub type CompactAssignments =
GenericCompactAssignments;
type PositiveImbalanceOf =
<::Currency as Currency<::AccountId>>::PositiveImbalance;
type NegativeImbalanceOf =
<::Currency as Currency<::AccountId>>::NegativeImbalance;
/// Reward points of an era. Used to split era total payout between validators.
///
/// This points will be used to reward validators and their respective nominators.
#[derive(PartialEq, Encode, Decode, Default, RuntimeDebug)]
pub struct EraRewardPoints {
/// Total number of points. Equals the sum of reward points for each validator.
total: RewardPoint,
/// The reward points earned by a given validator.
individual: BTreeMap,
}
/// Indicates the initial status of the staker.
#[derive(RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum StakerStatus {
/// Chilling.
Idle,
/// Declared desire in validating or already participating in it.
Validator,
/// Nominating for a group of other stakers.
Nominator(Vec),
}
/// A destination account for payment.
#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug)]
pub enum RewardDestination {
/// Pay into the stash account, increasing the amount at stake accordingly.
Staked,
/// Pay into the stash account, not increasing the amount at stake.
Stash,
/// Pay into the controller account.
Controller,
}
impl Default for RewardDestination {
fn default() -> Self {
RewardDestination::Staked
}
}
/// Preference of what happens regarding validation.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct ValidatorPrefs {
/// Reward that validator takes up-front; only the rest is split between themselves and
/// nominators.
#[codec(compact)]
pub commission: Perbill,
}
impl Default for ValidatorPrefs {
fn default() -> Self {
ValidatorPrefs {
commission: Default::default(),
}
}
}
/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct UnlockChunk {
/// Amount of funds to be unlocked.
#[codec(compact)]
value: Balance,
/// Era number at which point it'll be unlocked.
#[codec(compact)]
era: EraIndex,
}
/// The ledger of a (bonded) stash.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct StakingLedger {
/// The stash account whose balance is actually locked and at stake.
pub stash: 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: Balance,
/// The total amount of the stash's balance that will be at stake in any forthcoming
/// rounds.
#[codec(compact)]
pub active: Balance,
/// Any balance that is becoming free, which may eventually be transferred out
/// of the stash (assuming it doesn't get slashed first).
pub unlocking: Vec>,
/// List of eras for which the stakers behind a validator have claimed rewards. Only updated
/// for validators.
pub claimed_rewards: Vec,
}
impl<
AccountId,
Balance: HasCompact + Copy + Saturating + AtLeast32Bit,
> StakingLedger {
/// Remove entries from `unlocking` that are sufficiently old and reduce the
/// total by the sum of their balances.
fn consolidate_unlocked(self, current_era: EraIndex) -> Self {
let mut total = self.total;
let unlocking = self.unlocking.into_iter()
.filter(|chunk| if chunk.era > current_era {
true
} else {
total = total.saturating_sub(chunk.value);
false
})
.collect();
Self {
stash: self.stash,
total,
active: self.active,
unlocking,
claimed_rewards: self.claimed_rewards
}
}
/// Re-bond funds that were scheduled for unlocking.
fn rebond(mut self, value: Balance) -> Self {
let mut unlocking_balance: Balance = Zero::zero();
while let Some(last) = self.unlocking.last_mut() {
if unlocking_balance + last.value <= value {
unlocking_balance += last.value;
self.active += last.value;
self.unlocking.pop();
} else {
let diff = value - unlocking_balance;
unlocking_balance += diff;
self.active += diff;
last.value -= diff;
}
if unlocking_balance >= value {
break
}
}
self
}
}
impl StakingLedger where
Balance: AtLeast32Bit + Saturating + Copy,
{
/// Slash the validator for a given amount of balance. This can grow the value
/// of the slash in the case that the validator has less than `minimum_balance`
/// active funds. Returns the amount of funds actually slashed.
///
/// Slashes from `active` funds first, and then `unlocking`, starting with the
/// chunks that are closest to unlocking.
fn slash(
&mut self,
mut value: Balance,
minimum_balance: Balance,
) -> Balance {
let pre_total = self.total;
let total = &mut self.total;
let active = &mut self.active;
let slash_out_of = |
total_remaining: &mut Balance,
target: &mut Balance,
value: &mut Balance,
| {
let mut slash_from_target = (*value).min(*target);
if !slash_from_target.is_zero() {
*target -= slash_from_target;
// don't leave a dust balance in the staking system.
if *target <= minimum_balance {
slash_from_target += *target;
*value += sp_std::mem::replace(target, Zero::zero());
}
*total_remaining = total_remaining.saturating_sub(slash_from_target);
*value -= slash_from_target;
}
};
slash_out_of(total, active, &mut value);
let i = self.unlocking.iter_mut()
.map(|chunk| {
slash_out_of(total, &mut chunk.value, &mut value);
chunk.value
})
.take_while(|value| value.is_zero()) // take all fully-consumed chunks out.
.count();
// kill all drained chunks.
let _ = self.unlocking.drain(..i);
pre_total.saturating_sub(*total)
}
}
/// A record of the nominations made by a specific account.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct Nominations {
/// The targets of nomination.
pub targets: Vec,
/// The era the nominations were submitted.
///
/// Except for initial nominations which are considered submitted at era 0.
pub submitted_in: EraIndex,
/// Whether the nominations have been suppressed.
pub suppressed: bool,
}
/// The amount of exposure (to slashing) than an individual nominator has.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, RuntimeDebug)]
pub struct IndividualExposure {
/// The stash account of the nominator in question.
pub who: AccountId,
/// Amount of funds exposed.
#[codec(compact)]
pub value: Balance,
}
/// A snapshot of the stake backing a single validator in the system.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, Default, RuntimeDebug)]
pub struct Exposure {
/// 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>,
}
/// A pending slash record. The value of the slash has been computed but not applied yet,
/// rather deferred for several eras.
#[derive(Encode, Decode, Default, RuntimeDebug)]
pub struct UnappliedSlash {
/// The stash ID of the offending validator.
validator: AccountId,
/// The validator's own slash.
own: Balance,
/// All other slashed stakers and amounts.
others: Vec<(AccountId, Balance)>,
/// Reporters of the offence; bounty payout recipients.
reporters: Vec,
/// The amount of payout.
payout: Balance,
}
/// Indicate how an election round was computed.
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug)]
pub enum ElectionCompute {
/// Result was forcefully computed on chain at the end of the session.
OnChain,
/// Result was submitted and accepted to the chain via a signed transaction.
Signed,
/// Result was submitted and accepted to the chain via an unsigned transaction (by an
/// authority).
Unsigned,
}
/// The result of an election round.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct ElectionResult {
/// Flat list of validators who have been elected.
elected_stashes: Vec,
/// Flat list of new exposures, to be updated in the [`Exposure`] storage.
exposures: Vec<(AccountId, Exposure)>,
/// Type of the result. This is kept on chain only to track and report the best score's
/// submission type. An optimisation could remove this.
compute: ElectionCompute,
}
/// The status of the upcoming (offchain) election.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub enum ElectionStatus {
/// Nothing has and will happen for now. submission window is not open.
Closed,
/// The submission window has been open since the contained block number.
Open(BlockNumber),
}
impl ElectionStatus {
fn is_open_at(&self, n: BlockNumber) -> bool {
*self == Self::Open(n)
}
fn is_closed(&self) -> bool {
match self {
Self::Closed => true,
_ => false
}
}
fn is_open(&self) -> bool {
!self.is_closed()
}
}
impl Default for ElectionStatus {
fn default() -> Self {
Self::Closed
}
}
/// Means for interacting with a specialized version of the `session` trait.
///
/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Trait`
pub trait SessionInterface: frame_system::Trait {
/// Disable a given validator by stash ID.
///
/// Returns `true` if new era should be forced at the end of this session.
/// This allows preventing a situation where there is too many validators
/// disabled and block production stalls.
fn disable_validator(validator: &AccountId) -> Result;
/// Get the validators from session.
fn validators() -> Vec;
/// Prune historical session tries up to but not including the given index.
fn prune_historical_up_to(up_to: SessionIndex);
}
impl SessionInterface<::AccountId> for T where
T: pallet_session::Trait::AccountId>,
T: pallet_session::historical::Trait<
FullIdentification = Exposure<::AccountId, BalanceOf>,
FullIdentificationOf = ExposureOf,
>,
T::SessionHandler: pallet_session::SessionHandler<::AccountId>,
T::SessionManager: pallet_session::SessionManager<::AccountId>,
T::ValidatorIdOf:
Convert<::AccountId, Option<::AccountId>>,
{
fn disable_validator(validator: &::AccountId) -> Result {
>::disable(validator)
}
fn validators() -> Vec<::AccountId> {
>::validators()
}
fn prune_historical_up_to(up_to: SessionIndex) {
>::prune_up_to(up_to);
}
}
pub trait Trait: frame_system::Trait {
/// The staking balance.
type Currency: LockableCurrency;
/// Time used for computing era duration.
///
/// It is guaranteed to start being called from the first `on_finalize`. Thus value at genesis
/// is not used.
type UnixTime: UnixTime;
/// Convert a balance into a number used for election calculation.
/// This must fit into a `u64` but is allowed to be sensibly lossy.
/// TODO: #1377
/// The backward convert should be removed as the new Phragmen API returns ratio.
/// The post-processing needs it but will be moved to off-chain. TODO: #2908
type CurrencyToVote: Convert, u64> + Convert>;
/// Tokens have been minted and are unused for validator-reward.
type RewardRemainder: OnUnbalanced>;
/// The overarching event type.
type Event: From> + Into<::Event>;
/// Handler for the unbalanced reduction when slashing a staker.
type Slash: OnUnbalanced>;
/// Handler for the unbalanced increment when rewarding a staker.
type Reward: OnUnbalanced>;
/// Number of sessions per era.
type SessionsPerEra: Get;
/// Number of eras that staked funds must remain bonded for.
type BondingDuration: Get;
/// Number of eras that slashes are deferred by, after computation. This
/// should be less than the bonding duration. Set to 0 if slashes should be
/// applied immediately, without opportunity for intervention.
type SlashDeferDuration: Get;
/// The origin which can cancel a deferred slash. Root can always do this.
type SlashCancelOrigin: EnsureOrigin;
/// Interface for interacting with a session module.
type SessionInterface: self::SessionInterface;
/// The NPoS reward curve to use.
type RewardCurve: Get<&'static PiecewiseLinear<'static>>;
/// Something that can estimate the next session change, accurately or as a best effort guess.
type NextNewSession: EstimateNextNewSession;
/// How many blocks ahead of the era, within the last do we try to run the phragmen offchain?
/// Setting this to zero will disable the offchain compute and only on-chain seq-phragmen will
/// be used.
type ElectionLookahead: Get;
/// The overarching call type.
type Call: Dispatchable + From> + IsSubType, Self> + Clone;
/// A transaction submitter.
type SubmitTransaction: SubmitUnsignedTransaction::Call>;
/// The maximum number of nominators rewarded for each validator.
///
/// For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can claim
/// their reward. This used to limit the i/o cost for the nominator payout.
type MaxNominatorRewardedPerValidator: Get;
/// A configuration for base priority of unsigned transactions.
///
/// This is exposed so that it can be tuned for particular runtime, when
/// multiple pallets send unsigned transactions.
type UnsignedPriority: Get;
}
/// Mode of era-forcing.
#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum Forcing {
/// Not forcing anything - just let whatever happen.
NotForcing,
/// Force a new era, then reset to `NotForcing` as soon as it is done.
ForceNew,
/// Avoid a new era indefinitely.
ForceNone,
/// Force a new era at the end of all sessions indefinitely.
ForceAlways,
}
impl Default for Forcing {
fn default() -> Self { Forcing::NotForcing }
}
// A value placed in storage that represents the current version of the Staking storage.
// This value is used by the `on_runtime_upgrade` logic to determine whether we run
// storage migration logic. This should match directly with the semantic versions of the Rust crate.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)]
enum Releases {
V1_0_0Ancient,
V2_0_0,
V3_0_0,
}
impl Default for Releases {
fn default() -> Self {
Releases::V3_0_0
}
}
decl_storage! {
trait Store for Module as Staking {
/// Number of eras to keep in history.
///
/// Information is kept for eras in `[current_era - history_depth; current_era]`.
///
/// Must be more than the number of eras delayed by session otherwise.
/// I.e. active era must always be in history.
/// I.e. `active_era > current_era - history_depth` must be guaranteed.
HistoryDepth get(fn history_depth) config(): u32 = 84;
/// The ideal number of staking participants.
pub ValidatorCount get(fn validator_count) config(): u32;
/// Minimum number of staking participants before emergency conditions are imposed.
pub MinimumValidatorCount get(fn minimum_validator_count) config():
u32 = DEFAULT_MINIMUM_VALIDATOR_COUNT;
/// Any validators that may never be slashed or forcibly kicked. It's a Vec since they're
/// easy to initialize and the performance hit is minimal (we expect no more than four
/// invulnerables) and restricted to testnets.
pub Invulnerables get(fn invulnerables) config(): Vec;
/// Map from all locked "stash" accounts to the controller account.
pub Bonded get(fn bonded): map hasher(twox_64_concat) T::AccountId => Option;
/// Map from all (unlocked) "controller" accounts to the info regarding the staking.
pub Ledger get(fn ledger):
map hasher(blake2_128_concat) T::AccountId
=> Option>>;
/// Where the reward payment should be made. Keyed by stash.
pub Payee get(fn payee): map hasher(twox_64_concat) T::AccountId => RewardDestination;
/// The map from (wannabe) validator stash key to the preferences of that validator.
pub Validators get(fn validators):
map hasher(twox_64_concat) T::AccountId => ValidatorPrefs;
/// The map from nominator stash key to the set of stash keys of all validators to nominate.
pub Nominators get(fn nominators):
map hasher(twox_64_concat) T::AccountId => Option>;
/// The current era index.
///
/// This is the latest planned era, depending on how the Session pallet queues the validator
/// set, it might be active or not.
pub CurrentEra get(fn current_era): Option;
/// The active era information, it holds index and start.
///
/// The active era is the era currently rewarded.
/// Validator set of this era must be equal to `SessionInterface::validators`.
pub ActiveEra get(fn active_era): Option;
/// The session index at which the era start for the last `HISTORY_DEPTH` eras.
pub ErasStartSessionIndex get(fn eras_start_session_index):
map hasher(twox_64_concat) EraIndex => Option;
/// Exposure of validator at era.
///
/// This is keyed first by the era index to allow bulk deletion and then the stash account.
///
/// Is it removed after `HISTORY_DEPTH` eras.
/// If stakers hasn't been set or has been removed then empty exposure is returned.
pub ErasStakers get(fn eras_stakers):
double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId
=> Exposure>;
/// Clipped Exposure of validator at era.
///
/// This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the
/// `T::MaxNominatorRewardedPerValidator` 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.
/// If stakers hasn't been set or has been removed then empty exposure is returned.
pub ErasStakersClipped get(fn eras_stakers_clipped):
double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId
=> Exposure>;
/// 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.
// If prefs hasn't been set or has been removed then 0 commission is returned.
pub ErasValidatorPrefs get(fn eras_validator_prefs):
double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId
=> ValidatorPrefs;
/// The total validator era payout for the last `HISTORY_DEPTH` eras.
///
/// Eras that haven't finished yet or has been removed doesn't have reward.
pub ErasValidatorReward get(fn eras_validator_reward):
map hasher(twox_64_concat) EraIndex => Option>;
/// Rewards for the last `HISTORY_DEPTH` eras.
/// If reward hasn't been set or has been removed then 0 reward is returned.
pub ErasRewardPoints get(fn eras_reward_points):
map hasher(twox_64_concat) EraIndex => EraRewardPoints;
/// The total amount staked for the last `HISTORY_DEPTH` eras.
/// If total hasn't been set or has been removed then 0 stake is returned.
pub ErasTotalStake get(fn eras_total_stake):
map hasher(twox_64_concat) EraIndex => BalanceOf;
/// Mode of era forcing.
pub ForceEra get(fn force_era) config(): Forcing;
/// The percentage of the slash that is distributed to reporters.
///
/// The rest of the slashed value is handled by the `Slash`.
pub SlashRewardFraction get(fn slash_reward_fraction) config(): Perbill;
/// The amount of currency given to reporters of a slash event which was
/// canceled by extraordinary circumstances (e.g. governance).
pub CanceledSlashPayout get(fn canceled_payout) config(): BalanceOf;
/// All unapplied slashes that are queued for later.
pub UnappliedSlashes:
map hasher(twox_64_concat) EraIndex => Vec>>;
/// A mapping from still-bonded eras to the first session index of that era.
///
/// Must contains information for eras for the range:
/// `[active_era - bounding_duration; active_era]`
BondedEras: Vec<(EraIndex, SessionIndex)>;
/// All slashing events on validators, mapped by era to the highest slash proportion
/// and slash value of the era.
ValidatorSlashInEra:
double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId
=> Option<(Perbill, BalanceOf)>;
/// All slashing events on nominators, mapped by era to the highest slash value of the era.
NominatorSlashInEra:
double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId
=> Option>;
/// Slashing spans for stash accounts.
SlashingSpans: map hasher(twox_64_concat) T::AccountId => Option;
/// Records information about the maximum slash of a stash within a slashing span,
/// as well as how much reward has been paid out.
SpanSlash:
map hasher(twox_64_concat) (T::AccountId, slashing::SpanIndex)
=> slashing::SpanRecord>;
/// The earliest era for which we have a pending, unapplied slash.
EarliestUnappliedSlash: Option;
/// Snapshot of validators at the beginning of the current election window. This should only
/// have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
pub SnapshotValidators get(fn snapshot_validators): Option>;
/// Snapshot of nominators at the beginning of the current election window. This should only
/// have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
pub SnapshotNominators get(fn snapshot_nominators): Option>;
/// The next validator set. At the end of an era, if this is available (potentially from the
/// result of an offchain worker), it is immediately used. Otherwise, the on-chain election
/// is executed.
pub QueuedElected get(fn queued_elected): Option>>;
/// The score of the current [`QueuedElected`].
pub QueuedScore get(fn queued_score): Option;
/// Flag to control the execution of the offchain election. When `Open(_)`, we accept
/// solutions to be submitted.
pub EraElectionStatus get(fn era_election_status): ElectionStatus;
/// True if the current **planned** session is final. Note that this does not take era
/// forcing into account.
pub IsCurrentSessionFinal get(fn is_current_session_final): bool = false;
/// True if network has been upgraded to this version.
/// Storage version of the pallet.
///
/// This is set to v3.0.0 for new networks.
StorageVersion build(|_: &GenesisConfig| Releases::V3_0_0): Releases;
/// The era where we migrated from Lazy Payouts to Simple Payouts
MigrateEra: Option;
}
add_extra_genesis {
config(stakers):
Vec<(T::AccountId, T::AccountId, BalanceOf, StakerStatus)>;
build(|config: &GenesisConfig| {
for &(ref stash, ref controller, balance, ref status) in &config.stakers {
assert!(
T::Currency::free_balance(&stash) >= balance,
"Stash does not have enough balance to bond."
);
let _ = >::bond(
T::Origin::from(Some(stash.clone()).into()),
T::Lookup::unlookup(controller.clone()),
balance,
RewardDestination::Staked,
);
let _ = match status {
StakerStatus::Validator => {
>::validate(
T::Origin::from(Some(controller.clone()).into()),
Default::default(),
)
},
StakerStatus::Nominator(votes) => {
>::nominate(
T::Origin::from(Some(controller.clone()).into()),
votes.iter().map(|l| T::Lookup::unlookup(l.clone())).collect(),
)
}, _ => Ok(())
};
}
});
}
}
decl_event!(
pub enum Event where Balance = BalanceOf, ::AccountId {
/// The staker has been rewarded by this amount. `AccountId` is the stash account.
Reward(AccountId, Balance),
/// One validator (and its nominators) has been slashed by the given amount.
Slash(AccountId, Balance),
/// An old slashing report from a prior era was discarded because it could
/// not be processed.
OldSlashingReportDiscarded(SessionIndex),
/// A new set of stakers was elected with the given computation method.
StakingElection(ElectionCompute),
/// An account has bonded this amount.
///
/// NOTE: This event is only emitted when funds are bonded via a dispatchable. Notably,
/// it will not be emitted for staking rewards when they are added to stake.
Bonded(AccountId, Balance),
/// An account has unbonded this amount.
Unbonded(AccountId, Balance),
/// An account has called `withdraw_unbonded` and removed unbonding chunks worth `Balance`
/// from the unlocking queue.
Withdrawn(AccountId, Balance),
}
);
decl_error! {
/// Error for the staking module.
pub enum Error for Module {
/// Not a controller account.
NotController,
/// Not a stash account.
NotStash,
/// Stash is already bonded.
AlreadyBonded,
/// Controller is already paired.
AlreadyPaired,
/// Targets cannot be empty.
EmptyTargets,
/// Duplicate index.
DuplicateIndex,
/// Slash record index out of bounds.
InvalidSlashIndex,
/// Can not bond with value less than minimum balance.
InsufficientValue,
/// Can not schedule more unlock chunks.
NoMoreChunks,
/// Can not rebond without unlocking chunks.
NoUnlockChunk,
/// Attempting to target a stash that still has funds.
FundedTarget,
/// Invalid era to reward.
InvalidEraToReward,
/// Invalid number of nominations.
InvalidNumberOfNominations,
/// Items are not sorted and unique.
NotSortedAndUnique,
/// Rewards for this era have already been claimed for this validator.
AlreadyClaimed,
/// The submitted result is received out of the open window.
PhragmenEarlySubmission,
/// The submitted result is not as good as the one stored on chain.
PhragmenWeakSubmission,
/// The snapshot data of the current window is missing.
SnapshotUnavailable,
/// Incorrect number of winners were presented.
PhragmenBogusWinnerCount,
/// One of the submitted winners is not an active candidate on chain (index is out of range
/// in snapshot).
PhragmenBogusWinner,
/// Error while building the assignment type from the compact. This can happen if an index
/// is invalid, or if the weights _overflow_.
PhragmenBogusCompact,
/// One of the submitted nominators is not an active nominator on chain.
PhragmenBogusNominator,
/// One of the submitted nominators has an edge to which they have not voted on chain.
PhragmenBogusNomination,
/// One of the submitted nominators has an edge which is submitted before the last non-zero
/// slash of the target.
PhragmenSlashedNomination,
/// A self vote must only be originated from a validator to ONLY themselves.
PhragmenBogusSelfVote,
/// The submitted result has unknown edges that are not among the presented winners.
PhragmenBogusEdge,
/// The claimed score does not match with the one computed from the data.
PhragmenBogusScore,
/// The call is not allowed at the given time due to restrictions of election period.
CallNotAllowed,
}
}
decl_module! {
pub struct Module for enum Call where origin: T::Origin {
/// Number of sessions per era.
const SessionsPerEra: SessionIndex = T::SessionsPerEra::get();
/// Number of eras that staked funds must remain bonded for.
const BondingDuration: EraIndex = T::BondingDuration::get();
type Error = Error;
fn deposit_event() = default;
/// sets `ElectionStatus` to `Open(now)` where `now` is the block number at which the
/// election window has opened, if we are at the last session and less blocks than
/// `T::ElectionLookahead` is remaining until the next new session schedule. The offchain
/// worker, if applicable, will execute at the end of the current block, and solutions may
/// be submitted.
fn on_initialize(now: T::BlockNumber) -> Weight {
if
// if we don't have any ongoing offchain compute.
Self::era_election_status().is_closed() &&
// either current session final based on the plan, or we're forcing.
(Self::is_current_session_final() || Self::will_era_be_forced())
{
if let Some(next_session_change) = T::NextNewSession::estimate_next_new_session(now){
if let Some(remaining) = next_session_change.checked_sub(&now) {
if remaining <= T::ElectionLookahead::get() && !remaining.is_zero() {
// create snapshot.
if Self::create_stakers_snapshot() {
// Set the flag to make sure we don't waste any compute here in the same era
// after we have triggered the offline compute.
>::put(
ElectionStatus::::Open(now)
);
log!(info, "💸 Election window is Open({:?}). Snapshot created", now);
} else {
log!(warn, "💸 Failed to create snapshot at {:?}.", now);
}
}
}
} else {
log!(warn, "💸 Estimating next session change failed.");
}
}
// weight
50_000
}
/// Check if the current block number is the one at which the election window has been set
/// to open. If so, it runs the offchain worker code.
fn offchain_worker(now: T::BlockNumber) {
use offchain_election::{set_check_offchain_execution_status, compute_offchain_election};
if Self::era_election_status().is_open_at(now) {
let offchain_status = set_check_offchain_execution_status::(now);
if let Err(why) = offchain_status {
log!(debug, "skipping offchain worker in open election window due to [{}]", why);
} else {
if let Err(e) = compute_offchain_election::() {
log!(warn, "💸 Error in phragmen offchain worker: {:?}", e);
} else {
log!(debug, "Executed offchain worker thread without errors.");
}
}
}
}
fn on_finalize() {
// Set the start of the first era.
if let Some(mut active_era) = Self::active_era() {
if active_era.start.is_none() {
let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::();
active_era.start = Some(now_as_millis_u64);
ActiveEra::put(active_era);
}
}
}
fn on_runtime_upgrade() -> Weight {
// For Kusama the type hasn't actually changed as Moment was u64 and was the number of
// millisecond since unix epoch.
StorageVersion::put(Releases::V3_0_0);
Self::migrate_last_reward_to_claimed_rewards();
0
}
/// Take the origin account as a stash and lock up `value` of its balance. `controller` will
/// be the account that controls it.
///
/// `value` must be more than the `minimum_balance` specified by `T::Currency`.
///
/// The dispatch origin for this call must be _Signed_ by the stash account.
///
/// Emits `Bonded`.
///
/// #
/// - Independent of the arguments. Moderate complexity.
/// - O(1).
/// - Three extra DB entries.
///
/// NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned
/// unless the `origin` falls below _existential deposit_ and gets removed as dust.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
pub fn bond(origin,
controller: ::Source,
#[compact] value: BalanceOf,
payee: RewardDestination,
) {
let stash = ensure_signed(origin)?;
if >::contains_key(&stash) {
Err(Error::::AlreadyBonded)?
}
let controller = T::Lookup::lookup(controller)?;
if >::contains_key(&controller) {
Err(Error::::AlreadyPaired)?
}
// reject a bond which is considered to be _dust_.
if value < T::Currency::minimum_balance() {
Err(Error::::InsufficientValue)?
}
// You're auto-bonded forever, here. We might improve this by only bonding when
// you actually validate/nominate and remove once you unbond __everything__.
>::insert(&stash, &controller);
>::insert(&stash, payee);
system::Module::::inc_ref(&stash);
let current_era = CurrentEra::get().unwrap_or(0);
let history_depth = Self::history_depth();
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(RawEvent::Bonded(stash.clone(), value));
let item = StakingLedger {
stash,
total: value,
active: value,
unlocking: vec![],
claimed_rewards: (last_reward_era..current_era).collect(),
};
Self::update_ledger(&controller, &item);
}
/// Add some extra amount that have appeared in the stash `free_balance` into the balance up
/// for staking.
///
/// Use this if there are additional funds in your stash account that you wish to bond.
/// Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount
/// that can be added.
///
/// The dispatch origin for this call must be _Signed_ by the stash, not the controller and
/// it can be only called when [`EraElectionStatus`] is `Closed`.
///
/// Emits `Bonded`.
///
/// #
/// - Independent of the arguments. Insignificant complexity.
/// - O(1).
/// - One DB entry.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn bond_extra(origin, #[compact] max_additional: BalanceOf) {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
let stash = ensure_signed(origin)?;
let controller = Self::bonded(&stash).ok_or(Error::::NotStash)?;
let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
let stash_balance = T::Currency::free_balance(&stash);
if let Some(extra) = stash_balance.checked_sub(&ledger.total) {
let extra = extra.min(max_additional);
ledger.total += extra;
ledger.active += extra;
Self::deposit_event(RawEvent::Bonded(stash, extra));
Self::update_ledger(&controller, &ledger);
}
}
/// Schedule a portion of the stash to be unlocked ready for transfer out after the bond
/// period ends. If this leaves an amount actively bonded less than
/// T::Currency::minimum_balance(), then it is increased to the full amount.
///
/// Once the unlock period is done, you can call `withdraw_unbonded` to actually move
/// the funds out of management ready for transfer.
///
/// No more than a limited number of unlocking chunks (see `MAX_UNLOCKING_CHUNKS`)
/// can co-exists at the same time. In that case, [`Call::withdraw_unbonded`] need
/// to be called first to remove some of the chunks (if possible).
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
/// And, it can be only called when [`EraElectionStatus`] is `Closed`.
///
/// Emits `Unbonded`.
///
/// See also [`Call::withdraw_unbonded`].
///
/// #
/// - Independent of the arguments. Limited but potentially exploitable complexity.
/// - Contains a limited number of reads.
/// - Each call (requires the remainder of the bonded balance to be above `minimum_balance`)
/// will cause a new entry to be inserted into a vector (`Ledger.unlocking`) kept in storage.
/// The only way to clean the aforementioned storage item is also user-controlled via
/// `withdraw_unbonded`.
/// - One DB entry.
///
#[weight = SimpleDispatchInfo::FixedNormal(400_000)]
fn unbond(origin, #[compact] value: BalanceOf) {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
let controller = ensure_signed(origin)?;
let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
ensure!(
ledger.unlocking.len() < MAX_UNLOCKING_CHUNKS,
Error::::NoMoreChunks,
);
let mut value = value.min(ledger.active);
if !value.is_zero() {
ledger.active -= value;
// Avoid there being a dust balance left in the staking system.
if ledger.active < T::Currency::minimum_balance() {
value += ledger.active;
ledger.active = Zero::zero();
}
// Note: in case there is no current era it is fine to bond one era more.
let era = Self::current_era().unwrap_or(0) + T::BondingDuration::get();
ledger.unlocking.push(UnlockChunk { value, era });
Self::update_ledger(&controller, &ledger);
Self::deposit_event(RawEvent::Unbonded(ledger.stash.clone(), value));
}
}
/// Remove any unlocked chunks from the `unlocking` queue from our management.
///
/// This essentially frees up that balance to be used by the stash account to do
/// whatever it wants.
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
/// And, it can be only called when [`EraElectionStatus`] is `Closed`.
///
/// Emits `Withdrawn`.
///
/// See also [`Call::unbond`].
///
/// #
/// - Could be dependent on the `origin` argument and how much `unlocking` chunks exist.
/// It implies `consolidate_unlocked` which loops over `Ledger.unlocking`, which is
/// indirectly user-controlled. See [`unbond`] for more detail.
/// - Contains a limited number of reads, yet the size of which could be large based on `ledger`.
/// - Writes are limited to the `origin` account key.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(400_000)]
fn withdraw_unbonded(origin) {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
let controller = ensure_signed(origin)?;
let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
let (stash, old_total) = (ledger.stash.clone(), ledger.total);
if let Some(current_era) = Self::current_era() {
ledger = ledger.consolidate_unlocked(current_era)
}
if ledger.unlocking.is_empty() && ledger.active.is_zero() {
// This account must have called `unbond()` with some value that caused the active
// portion to fall below existential deposit + will have no more unlocking chunks
// left. We can now safely remove all staking-related information.
Self::kill_stash(&stash)?;
// remove the lock.
T::Currency::remove_lock(STAKING_ID, &stash);
} else {
// This was the consequence of a partial unbond. just update the ledger and move on.
Self::update_ledger(&controller, &ledger);
}
// `old_total` should never be less than the new total because
// `consolidate_unlocked` strictly subtracts balance.
if ledger.total < old_total {
// Already checked that this won't overflow by entry condition.
let value = old_total - ledger.total;
Self::deposit_event(RawEvent::Withdrawn(stash, value));
}
}
/// Declare the desire to validate for the origin controller.
///
/// Effects will be felt at the beginning of the next era.
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
/// And, it can be only called when [`EraElectionStatus`] is `Closed`.
///
/// #
/// - Independent of the arguments. Insignificant complexity.
/// - Contains a limited number of reads.
/// - Writes are limited to the `origin` account key.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
pub fn validate(origin, prefs: ValidatorPrefs) {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
let stash = &ledger.stash;
>::remove(stash);
>::insert(stash, prefs);
}
/// Declare the desire to nominate `targets` for the origin controller.
///
/// Effects will be felt at the beginning of the next era. This can only be called when
/// [`EraElectionStatus`] is `Closed`.
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
/// And, it can be only called when [`EraElectionStatus`] is `Closed`.
///
/// #
/// - The transaction's complexity is proportional to the size of `targets`,
/// which is capped at CompactAssignments::LIMIT.
/// - Both the reads and writes follow a similar pattern.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
pub fn nominate(origin, targets: Vec<::Source>) {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
let stash = &ledger.stash;
ensure!(!targets.is_empty(), Error::::EmptyTargets);
let targets = targets.into_iter()
.take(::LIMIT)
.map(|t| T::Lookup::lookup(t))
.collect::, _>>()?;
let nominations = Nominations {
targets,
// initial nominations are considered submitted at era 0. See `Nominations` doc
submitted_in: Self::current_era().unwrap_or(0),
suppressed: false,
};
>::remove(stash);
>::insert(stash, &nominations);
}
/// Declare no desire to either validate or nominate.
///
/// Effects will be felt at the beginning of the next era.
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
/// And, it can be only called when [`EraElectionStatus`] is `Closed`.
///
/// #
/// - Independent of the arguments. Insignificant complexity.
/// - Contains one read.
/// - Writes are limited to the `origin` account key.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn chill(origin) {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
Self::chill_stash(&ledger.stash);
}
/// (Re-)set the payment target for a controller.
///
/// Effects will be felt at the beginning of the next era.
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
///
/// #
/// - Independent of the arguments. Insignificant complexity.
/// - Contains a limited number of reads.
/// - Writes are limited to the `origin` account key.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn set_payee(origin, payee: RewardDestination) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
let stash = &ledger.stash;
>::insert(stash, payee);
}
/// (Re-)set the controller of a stash.
///
/// Effects will be felt at the beginning of the next era.
///
/// The dispatch origin for this call must be _Signed_ by the stash, not the controller.
///
/// #
/// - Independent of the arguments. Insignificant complexity.
/// - Contains a limited number of reads.
/// - Writes are limited to the `origin` account key.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
fn set_controller(origin, controller: ::Source) {
let stash = ensure_signed(origin)?;
let old_controller = Self::bonded(&stash).ok_or(Error::::NotStash)?;
let controller = T::Lookup::lookup(controller)?;
if >::contains_key(&controller) {
Err(Error::::AlreadyPaired)?
}
if controller != old_controller {
>::insert(&stash, &controller);
if let Some(l) = >::take(&old_controller) {
>::insert(&controller, l);
}
}
}
/// The ideal number of validators.
#[weight = SimpleDispatchInfo::FixedNormal(5_000)]
fn set_validator_count(origin, #[compact] new: u32) {
ensure_root(origin)?;
ValidatorCount::put(new);
}
/// Force there to be no new eras indefinitely.
///
/// #
/// - No arguments.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(5_000)]
fn force_no_eras(origin) {
ensure_root(origin)?;
ForceEra::put(Forcing::ForceNone);
}
/// Force there to be a new era at the end of the next session. After this, it will be
/// reset to normal (non-forced) behaviour.
///
/// #
/// - No arguments.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(5_000)]
fn force_new_era(origin) {
ensure_root(origin)?;
ForceEra::put(Forcing::ForceNew);
}
/// Set the validators who cannot be slashed (if any).
#[weight = SimpleDispatchInfo::FixedNormal(5_000)]
fn set_invulnerables(origin, validators: Vec) {
ensure_root(origin)?;
>::put(validators);
}
/// Force a current staker to become completely unstaked, immediately.
#[weight = SimpleDispatchInfo::FixedNormal(10_000)]
fn force_unstake(origin, stash: T::AccountId) {
ensure_root(origin)?;
// remove all staking-related information.
Self::kill_stash(&stash)?;
// remove the lock.
T::Currency::remove_lock(STAKING_ID, &stash);
}
/// Force there to be a new era at the end of sessions indefinitely.
///
/// #
/// - One storage write
/// #
#[weight = SimpleDispatchInfo::FixedNormal(5_000)]
fn force_new_era_always(origin) {
ensure_root(origin)?;
ForceEra::put(Forcing::ForceAlways);
}
/// Cancel enactment of a deferred slash. Can be called by either the root origin or
/// the `T::SlashCancelOrigin`.
/// passing the era and indices of the slashes for that era to kill.
///
/// #
/// - One storage write.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(1_000_000)]
fn cancel_deferred_slash(origin, era: EraIndex, slash_indices: Vec) {
T::SlashCancelOrigin::try_origin(origin)
.map(|_| ())
.or_else(ensure_root)?;
ensure!(!slash_indices.is_empty(), Error::::EmptyTargets);
ensure!(is_sorted_and_unique(&slash_indices), Error::::NotSortedAndUnique);
let mut unapplied = ::UnappliedSlashes::get(&era);
let last_item = slash_indices[slash_indices.len() - 1];
ensure!((last_item as usize) < unapplied.len(), Error::::InvalidSlashIndex);
for (removed, index) in slash_indices.into_iter().enumerate() {
let index = (index as usize) - removed;
unapplied.remove(index);
}
::UnappliedSlashes::insert(&era, &unapplied);
}
/// **This extrinsic will be removed after `MigrationEra + HistoryDepth` has passed, giving
/// opportunity for users to claim all rewards before moving to Simple Payouts. After this
/// time, you should use `payout_stakers` instead.**
///
/// Make one nominator's payout for one era.
///
/// - `who` is the controller account of the nominator to pay out.
/// - `era` may not be lower than one following the most recently paid era. If it is higher,
/// then it indicates an instruction to skip the payout of all previous eras.
/// - `validators` is the list of all validators that `who` had exposure to during `era`,
/// alongside the index of `who` in the clipped exposure of the validator.
/// I.e. each element is a tuple of
/// `(validator, index of `who` in clipped exposure of validator)`.
/// If it is incomplete, then less than the full reward will be paid out.
/// It must not exceed `MAX_NOMINATIONS`.
///
/// WARNING: once an era is payed for a validator such validator can't claim the payout of
/// previous era.
///
/// WARNING: Incorrect arguments here can result in loss of payout. Be very careful.
///
/// #
/// - Number of storage read of `O(validators)`; `validators` is the argument of the call,
/// and is bounded by `MAX_NOMINATIONS`.
/// - Each storage read is `O(N)` size and decode complexity; `N` is the maximum
/// nominations that can be given to a single validator.
/// - Computation complexity: `O(MAX_NOMINATIONS * logN)`; `MAX_NOMINATIONS` is the
/// maximum number of validators that may be nominated by a single nominator, it is
/// bounded only economically (all nominators are required to place a minimum stake).
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn payout_nominator(origin, era: EraIndex, validators: Vec<(T::AccountId, u32)>)
-> DispatchResult
{
let ctrl = ensure_signed(origin)?;
Self::do_payout_nominator(ctrl, era, validators)
}
/// **This extrinsic will be removed after `MigrationEra + HistoryDepth` has passed, giving
/// opportunity for users to claim all rewards before moving to Simple Payouts. After this
/// time, you should use `payout_stakers` instead.**
///
/// Make one validator's payout for one era.
///
/// - `who` is the controller account of the validator to pay out.
/// - `era` may not be lower than one following the most recently paid era. If it is higher,
/// then it indicates an instruction to skip the payout of all previous eras.
///
/// WARNING: once an era is payed for a validator such validator can't claim the payout of
/// previous era.
///
/// WARNING: Incorrect arguments here can result in loss of payout. Be very careful.
///
/// #
/// - Time complexity: O(1).
/// - Contains a limited number of reads and writes.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn payout_validator(origin, era: EraIndex) -> DispatchResult {
let ctrl = ensure_signed(origin)?;
Self::do_payout_validator(ctrl, era)
}
/// Pay out all the stakers behind a single validator for a single era.
///
/// - `validator_stash` is the stash account of the validator. Their nominators, up to
/// `T::MaxNominatorRewardedPerValidator`, will also receive their rewards.
/// - `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.
///
/// This can only be called when [`EraElectionStatus`] is `Closed`.
///
/// #
/// - Time complexity: at most O(MaxNominatorRewardedPerValidator).
/// - Contains a limited number of reads and writes.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn payout_stakers(origin, validator_stash: T::AccountId, era: EraIndex) -> DispatchResult {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
ensure_signed(origin)?;
Self::do_payout_stakers(validator_stash, era)
}
/// Rebond a portion of the stash scheduled to be unlocked.
///
/// The dispatch origin must be signed by the controller, and it can be only called when
/// [`EraElectionStatus`] is `Closed`.
///
/// #
/// - Time complexity: O(1). Bounded by `MAX_UNLOCKING_CHUNKS`.
/// - Storage changes: Can't increase storage, only decrease it.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn rebond(origin, #[compact] value: BalanceOf) {
ensure!(Self::era_election_status().is_closed(), Error::::CallNotAllowed);
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?;
ensure!(!ledger.unlocking.is_empty(), Error::::NoUnlockChunk);
let ledger = ledger.rebond(value);
Self::update_ledger(&controller, &ledger);
}
/// Set history_depth value.
///
/// Origin must be root.
#[weight = SimpleDispatchInfo::FixedOperational(500_000)]
fn set_history_depth(origin, #[compact] new_history_depth: EraIndex) {
ensure_root(origin)?;
if let Some(current_era) = Self::current_era() {
HistoryDepth::mutate(|history_depth| {
let last_kept = current_era.checked_sub(*history_depth).unwrap_or(0);
let new_last_kept = current_era.checked_sub(new_history_depth).unwrap_or(0);
for era_index in last_kept..new_last_kept {
Self::clear_era_information(era_index);
}
*history_depth = new_history_depth
})
}
}
/// Remove all data structure concerning a staker/stash once its balance is zero.
/// This is essentially equivalent to `withdraw_unbonded` except it can be called by anyone
/// and the target `stash` must have no funds left.
///
/// This can be called from any origin.
///
/// - `stash`: The stash account to reap. Its balance must be zero.
#[weight = frame_support::weights::SimpleDispatchInfo::default()]
fn reap_stash(_origin, stash: T::AccountId) {
ensure!(T::Currency::total_balance(&stash).is_zero(), Error::::FundedTarget);
Self::kill_stash(&stash)?;
T::Currency::remove_lock(STAKING_ID, &stash);
}
/// Submit a phragmen result to the chain. If the solution:
///
/// 1. is valid.
/// 2. has a better score than a potentially existing solution on chain.
///
/// then, it will be _put_ on chain.
///
/// A solution consists of two pieces of data:
///
/// 1. `winners`: a flat vector of all the winners of the round.
/// 2. `assignments`: the compact version of an assignment vector that encodes the edge
/// weights.
///
/// Both of which may be computed using [`phragmen`], or any other algorithm.
///
/// Additionally, the submitter must provide:
///
/// - The `score` that they claim their solution has.
///
/// Both validators and nominators will be represented by indices in the solution. The
/// indices should respect the corresponding types ([`ValidatorIndex`] and
/// [`NominatorIndex`]). Moreover, they should be valid when used to index into
/// [`SnapshotValidators`] and [`SnapshotNominators`]. Any invalid index will cause the
/// solution to be rejected. These two storage items are set during the election window and
/// may be used to determine the indices.
///
/// A solution is valid if:
///
/// 0. It is submitted when [`EraElectionStatus`] is `Open`.
/// 1. Its claimed score is equal to the score computed on-chain.
/// 2. Presents the correct number of winners.
/// 3. All indexes must be value according to the snapshot vectors. All edge values must
/// also be correct and should not overflow the granularity of the ratio type (i.e. 256
/// or billion).
/// 4. For each edge, all targets are actually nominated by the voter.
/// 5. Has correct self-votes.
///
/// A solutions score is consisted of 3 parameters:
///
/// 1. `min { support.total }` for each support of a winner. This value should be maximized.
/// 2. `sum { support.total }` for each support of a winner. This value should be minimized.
/// 3. `sum { support.total^2 }` for each support of a winner. This value should be
/// minimized (to ensure less variance)
///
/// #
/// E: number of edges. m: size of winner committee. n: number of nominators. d: edge degree
/// (16 for now) v: number of on-chain validator candidates.
///
/// NOTE: given a solution which is reduced, we can enable a new check the ensure `|E| < n +
/// m`. We don't do this _yet_, but our offchain worker code executes it nonetheless.
///
/// major steps (all done in `check_and_replace_solution`):
///
/// - Storage: O(1) read `ElectionStatus`.
/// - Storage: O(1) read `PhragmenScore`.
/// - Storage: O(1) read `ValidatorCount`.
/// - Storage: O(1) length read from `SnapshotValidators`.
///
/// - Storage: O(v) reads of `AccountId` to fetch `snapshot_validators`.
/// - Memory: O(m) iterations to map winner index to validator id.
/// - Storage: O(n) reads `AccountId` to fetch `snapshot_nominators`.
/// - Memory: O(n + m) reads to map index to `AccountId` for un-compact.
///
/// - Storage: O(e) accountid reads from `Nomination` to read correct nominations.
/// - Storage: O(e) calls into `slashable_balance_of_extended` to convert ratio to staked.
///
/// - Memory: build_support_map. O(e).
/// - Memory: evaluate_support: O(E).
///
/// - Storage: O(e) writes to `QueuedElected`.
/// - Storage: O(1) write to `QueuedScore`
///
/// The weight of this call is 1/10th of the blocks total weight.
/// #
#[weight = SimpleDispatchInfo::FixedNormal(100_000_000)]
pub fn submit_election_solution(
origin,
winners: Vec,
compact_assignments: CompactAssignments,
score: PhragmenScore,
era: EraIndex,
) {
let _who = ensure_signed(origin)?;
Self::check_and_replace_solution(
winners,
compact_assignments,
ElectionCompute::Signed,
score,
era,
)?
}
/// Unsigned version of `submit_election_solution`.
///
/// Note that this must pass the [`ValidateUnsigned`] check which only allows transactions
/// from the local node to be included. In other words, only the block author can include a
/// transaction in the block.
#[weight = SimpleDispatchInfo::FixedNormal(100_000_000)]
pub fn submit_election_solution_unsigned(
origin,
winners: Vec,
compact_assignments: CompactAssignments,
score: PhragmenScore,
era: EraIndex,
) {
ensure_none(origin)?;
Self::check_and_replace_solution(
winners,
compact_assignments,
ElectionCompute::Unsigned,
score,
era,
)?
// TODO: instead of returning an error, panic. This makes the entire produced block
// invalid.
// This ensures that block authors will not ever try and submit a solution which is not
// an improvement, since they will lose their authoring points/rewards.
}
}
}
impl Module {
/// Migrate `last_reward` to `claimed_rewards`
pub fn migrate_last_reward_to_claimed_rewards() {
use frame_support::migration::{StorageIterator, put_storage_value};
// Migrate from `last_reward` to `claimed_rewards`.
// We will construct a vector from `current_era - history_depth` to `last_reward`
// for each validator and nominator.
//
// Old Staking Ledger
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
struct OldStakingLedger {
pub stash: AccountId,
#[codec(compact)]
pub total: Balance,
#[codec(compact)]
pub active: Balance,
pub unlocking: Vec>,
pub last_reward: Option,
}
// Current era and history depth
let current_era = Self::current_era().unwrap_or(0);
let history_depth = Self::history_depth();
let last_payout_era = current_era.saturating_sub(history_depth);
// Convert all ledgers to the new format.
for (hash, old_ledger) in StorageIterator::>>::new(b"Staking", b"Ledger").drain() {
let last_reward = old_ledger.last_reward.unwrap_or(0);
let new_ledger = StakingLedger {
stash: old_ledger.stash,
total: old_ledger.total,
active: old_ledger.active,
unlocking: old_ledger.unlocking,
claimed_rewards: (last_payout_era..=last_reward).collect(),
};
put_storage_value(b"Staking", b"Ledger", &hash, new_ledger);
}
MigrateEra::put(current_era);
}
/// The total balance that can be slashed from a stash account as of right now.
pub fn slashable_balance_of(stash: &T::AccountId) -> BalanceOf {
Self::bonded(stash).and_then(Self::ledger).map(|l| l.active).unwrap_or_default()
}
/// internal impl of [`slashable_balance_of`] that returns [`ExtendedBalance`].
fn slashable_balance_of_extended(stash: &T::AccountId) -> ExtendedBalance {
, u64>>::convert(
Self::slashable_balance_of(stash)
) as ExtendedBalance
}
/// Dump the list of validators and nominators into vectors and keep them on-chain.
///
/// This data is used to efficiently evaluate election results. returns `true` if the operation
/// is successful.
fn create_stakers_snapshot() -> bool {
let validators = >::iter().map(|(v, _)| v).collect::>();
let mut nominators = >::iter().map(|(n, _)| n).collect::>();
let num_validators = validators.len();
let num_nominators = nominators.len();
if
num_validators > MAX_VALIDATORS ||
num_nominators.saturating_add(num_validators) > MAX_NOMINATORS
{
log!(
warn,
"💸 Snapshot size too big [{} <> {}][{} <> {}].",
num_validators,
MAX_VALIDATORS,
num_nominators,
MAX_NOMINATORS,
);
false
} else {
// all validators nominate themselves;
nominators.extend(validators.clone());
>::put(validators);
>::put(nominators);
true
}
}
/// Clears both snapshots of stakers.
fn kill_stakers_snapshot() {
>::kill();
>::kill();
}
fn do_payout_nominator(ctrl: T::AccountId, era: EraIndex, validators: Vec<(T::AccountId, u32)>)
-> DispatchResult
{
// validators len must not exceed `MAX_NOMINATIONS` to avoid querying more validator
// exposure than necessary.
if validators.len() > MAX_NOMINATIONS {
return Err(Error::::InvalidNumberOfNominations.into());
}
// If migrate_era is not populated, then you should use `payout_stakers`
let migrate_era = MigrateEra::get().ok_or(Error::::InvalidEraToReward)?;
// This payout mechanism will only work for eras before the migration.
// Subsequent payouts should use `payout_stakers`.
ensure!(era < migrate_era, Error::::InvalidEraToReward);
let current_era = CurrentEra::get().ok_or(Error::::InvalidEraToReward)?;
ensure!(era <= current_era, Error::::InvalidEraToReward);
let history_depth = Self::history_depth();
ensure!(era >= current_era.saturating_sub(history_depth), Error::::InvalidEraToReward);
// Note: if era has no reward to be claimed, era may be future. better not to update
// `nominator_ledger.last_reward` in this case.
let era_payout = >::get(&era)
.ok_or_else(|| Error::::InvalidEraToReward)?;
let mut nominator_ledger = >::get(&ctrl).ok_or_else(|| Error::::NotController)?;
ensure!(
Self::era_election_status().is_closed() || Self::payee(&nominator_ledger.stash) != RewardDestination::Staked,
Error::::CallNotAllowed,
);
nominator_ledger.claimed_rewards.retain(|&x| x >= current_era.saturating_sub(history_depth));
match nominator_ledger.claimed_rewards.binary_search(&era) {
Ok(_) => Err(Error::::AlreadyClaimed)?,
Err(pos) => nominator_ledger.claimed_rewards.insert(pos, era),
}
>::insert(&ctrl, &nominator_ledger);
let mut reward = Perbill::zero();
let era_reward_points = >::get(&era);
for (validator, nominator_index) in validators.into_iter() {
let commission = Self::eras_validator_prefs(&era, &validator).commission;
let validator_exposure = >::get(&era, &validator);
if let Some(nominator_exposure) = validator_exposure.others
.get(nominator_index as usize)
{
if nominator_exposure.who != nominator_ledger.stash {
continue;
}
let nominator_exposure_part = Perbill::from_rational_approximation(
nominator_exposure.value,
validator_exposure.total,
);
let validator_point = era_reward_points.individual.get(&validator)
.map(|points| *points)
.unwrap_or_else(|| Zero::zero());
let validator_point_part = Perbill::from_rational_approximation(
validator_point,
era_reward_points.total,
);
reward = reward.saturating_add(
validator_point_part
.saturating_mul(Perbill::one().saturating_sub(commission))
.saturating_mul(nominator_exposure_part)
);
}
}
if let Some(imbalance) = Self::make_payout(&nominator_ledger.stash, reward * era_payout) {
Self::deposit_event(RawEvent::Reward(ctrl, imbalance.peek()));
}
Ok(())
}
fn do_payout_validator(ctrl: T::AccountId, era: EraIndex) -> DispatchResult {
// If migrate_era is not populated, then you should use `payout_stakers`
let migrate_era = MigrateEra::get().ok_or(Error::::InvalidEraToReward)?;
// This payout mechanism will only work for eras before the migration.
// Subsequent payouts should use `payout_stakers`.
ensure!(era < migrate_era, Error::::InvalidEraToReward);
let current_era = CurrentEra::get().ok_or(Error::::InvalidEraToReward)?;
ensure!(era <= current_era, Error::::InvalidEraToReward);
let history_depth = Self::history_depth();
ensure!(era >= current_era.saturating_sub(history_depth), Error::::InvalidEraToReward);
// Note: if era has no reward to be claimed, era may be future. better not to update
// `ledger.last_reward` in this case.
let era_payout = >::get(&era)
.ok_or_else(|| Error::::InvalidEraToReward)?;
let mut ledger = >::get(&ctrl).ok_or_else(|| Error::::NotController)?;
ensure!(
Self::era_election_status().is_closed() || Self::payee(&ledger.stash) != RewardDestination::Staked,
Error::::CallNotAllowed,
);
ledger.claimed_rewards.retain(|&x| x >= current_era.saturating_sub(history_depth));
match ledger.claimed_rewards.binary_search(&era) {
Ok(_) => Err(Error::::AlreadyClaimed)?,
Err(pos) => ledger.claimed_rewards.insert(pos, era),
}
>::insert(&ctrl, &ledger);
let era_reward_points = >::get(&era);
let commission = Self::eras_validator_prefs(&era, &ledger.stash).commission;
let exposure = >::get(&era, &ledger.stash);
let exposure_part = Perbill::from_rational_approximation(
exposure.own,
exposure.total,
);
let validator_point = era_reward_points.individual.get(&ledger.stash)
.map(|points| *points)
.unwrap_or_else(|| Zero::zero());
let validator_point_part = Perbill::from_rational_approximation(
validator_point,
era_reward_points.total,
);
let reward = validator_point_part.saturating_mul(
commission.saturating_add(
Perbill::one().saturating_sub(commission).saturating_mul(exposure_part)
)
);
if let Some(imbalance) = Self::make_payout(&ledger.stash, reward * era_payout) {
Self::deposit_event(RawEvent::Reward(ctrl, imbalance.peek()));
}
Ok(())
}
fn do_payout_stakers(
validator_stash: T::AccountId,
era: EraIndex,
) -> DispatchResult {
// Validate input data
let current_era = CurrentEra::get().ok_or(Error::::InvalidEraToReward)?;
ensure!(era <= current_era, Error::::InvalidEraToReward);
let history_depth = Self::history_depth();
ensure!(era >= current_era.saturating_sub(history_depth), Error::::InvalidEraToReward);
// If there was no migration, then this function is always valid.
if let Some(migrate_era) = MigrateEra::get() {
// This payout mechanism will only work for eras on and after the migration.
// Payouts before then should use `payout_nominator`/`payout_validator`.
ensure!(migrate_era <= era, Error::::InvalidEraToReward);
}
// Note: if era has no reward to be claimed, era may be future. better not to update
// `ledger.claimed_rewards` in this case.
let era_payout = >::get(&era)
.ok_or_else(|| Error::::InvalidEraToReward)?;
let controller = Self::bonded(&validator_stash).ok_or(Error::::NotStash)?;
let mut ledger = >::get(&controller).ok_or_else(|| Error::::NotController)?;
ledger.claimed_rewards.retain(|&x| x >= current_era.saturating_sub(history_depth));
match ledger.claimed_rewards.binary_search(&era) {
Ok(_) => Err(Error::::AlreadyClaimed)?,
Err(pos) => ledger.claimed_rewards.insert(pos, era),
}
let exposure = >::get(&era, &ledger.stash);
/* Input data seems good, no errors allowed after this point */
>::insert(&controller, &ledger);
// 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
//
// Then look at the validator, figure out the proportion of their reward
// which goes to them and each of their nominators.
let era_reward_points = >::get(&era);
let total_reward_points = era_reward_points.total;
let validator_reward_points = era_reward_points.individual.get(&ledger.stash)
.map(|points| *points)
.unwrap_or_else(|| Zero::zero());
// Nothing to do if they have no reward points.
if validator_reward_points.is_zero() { return Ok(())}
// This is the fraction of the total reward that the validator and the
// nominators will get.
let validator_total_reward_part = Perbill::from_rational_approximation(
validator_reward_points,
total_reward_points,
);
// 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_leftover_payout = validator_total_payout - validator_commission_payout;
// Now let's calculate how this is split to the validator.
let validator_exposure_part = Perbill::from_rational_approximation(
exposure.own,
exposure.total,
);
let validator_staking_payout = validator_exposure_part * validator_leftover_payout;
// We can now make total validator payout:
if let Some(imbalance) = Self::make_payout(
&ledger.stash,
validator_staking_payout + validator_commission_payout
) {
Self::deposit_event(RawEvent::Reward(ledger.stash, imbalance.peek()));
}
// Lets now calculate how this is split to the nominators.
// Sort nominators by highest to lowest exposure, but only keep `max_nominator_payouts` of them.
for nominator in exposure.others.iter() {
let nominator_exposure_part = Perbill::from_rational_approximation(
nominator.value,
exposure.total,
);
let nominator_reward: BalanceOf = nominator_exposure_part * validator_leftover_payout;
// We can now make nominator payout:
if let Some(imbalance) = Self::make_payout(&nominator.who, nominator_reward) {
Self::deposit_event(RawEvent::Reward(nominator.who.clone(), imbalance.peek()));
}
}
Ok(())
}
/// Update the ledger for a controller. This will also update the stash lock. The lock will
/// will lock the entire funds except paying for further transactions.
fn update_ledger(
controller: &T::AccountId,
ledger: &StakingLedger>
) {
T::Currency::set_lock(
STAKING_ID,
&ledger.stash,
ledger.total,
WithdrawReasons::all(),
);
>::insert(controller, ledger);
}
/// Chill a stash account.
fn chill_stash(stash: &T::AccountId) {
>::remove(stash);
>::remove(stash);
}
/// Actually make a payment to a staker. This uses the currency's reward function
/// to pay the right payee for the given staker account.
fn make_payout(stash: &T::AccountId, amount: BalanceOf) -> Option> {
let dest = Self::payee(stash);
match dest {
RewardDestination::Controller => Self::bonded(stash)
.and_then(|controller|
T::Currency::deposit_into_existing(&controller, amount).ok()
),
RewardDestination::Stash =>
T::Currency::deposit_into_existing(stash, amount).ok(),
RewardDestination::Staked => Self::bonded(stash)
.and_then(|c| Self::ledger(&c).map(|l| (c, l)))
.and_then(|(controller, mut l)| {
l.active += amount;
l.total += amount;
let r = T::Currency::deposit_into_existing(stash, amount).ok();
Self::update_ledger(&controller, &l);
r
}),
}
}
/// Plan a new session potentially trigger a new era.
fn new_session(session_index: SessionIndex) -> Option> {
if let Some(current_era) = Self::current_era() {
// Initial era has been set.
let current_era_start_session_index = Self::eras_start_session_index(current_era)
.unwrap_or_else(|| {
frame_support::print("Error: start_session_index must be set for current_era");
0
});
let era_length = session_index.checked_sub(current_era_start_session_index)
.unwrap_or(0); // Must never happen.
match ForceEra::get() {
Forcing::ForceNew => ForceEra::kill(),
Forcing::ForceAlways => (),
Forcing::NotForcing if era_length >= T::SessionsPerEra::get() => (),
_ => {
// not forcing, not a new era either. If final, set the flag.
if era_length + 1 >= T::SessionsPerEra::get() {
IsCurrentSessionFinal::put(true);
}
return None
},
}
// new era.
IsCurrentSessionFinal::put(false);
Self::new_era(session_index)
} else {
// Set initial era
Self::new_era(session_index)
}
}
/// Basic and cheap checks that we perform in validate unsigned, and in the execution.
pub fn pre_dispatch_checks(score: PhragmenScore, era: EraIndex) -> Result<(), Error> {
// discard solutions that are not in-time
// check window open
ensure!(
Self::era_election_status().is_open(),
Error::::PhragmenEarlySubmission,
);
// check current era.
if let Some(current_era) = Self::active_era().map(|e| e.index) {
ensure!(
current_era == era,
Error::