Crate pallet_staking

source ·
Expand description

§Staking Pallet

The Staking pallet is used to manage funds at stake by network maintainers.


The Staking pallet 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.


  • 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 (being deprecated): 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.


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.



Almost any interaction with the Staking pallet requires a process of bonding (also known as being a staker). To become bonded, a fund-holding register known as the stash account, which holds some or all of the funds that become frozen in place as part of the staking process. The controller account, which this pallet now assigns the stash account to, issues instructions on how funds shall be used.

An account can become a bonded stash account using the bond call.

In the event stash accounts registered a unique controller account before the controller account deprecation, they can update their associated controller back to the stash account using the set_controller call.

There are three possible roles that any staked account pair can be in: Validator, Nominator and Idle (defined in StakerStatus). There are three corresponding instructions to change between roles, namely: validate, nominate, and chill.


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 call.


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 call.


Staking is closely related to elections; actual validators are chosen from among all potential validators via election by the potential validators and nominators. To reduce use of the phrase “potential validators and nominators”, we often use the term voters, who are simply the union of potential validators and nominators.

§Rewards and Slash

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 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 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 pallet.

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 for more details.


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 call.

§Session managing

The pallet 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.


§Dispatchable Functions

The dispatchable functions of the Staking pallet enable the steps needed for entities to accept and change their role, alongside some helper functions to get/set the metadata of the pallet.

§Public Functions

The Staking pallet contains many public storage items and (im)mutable functions.


§Example: Rewarding a validator by id.

use pallet_staking::{self as staking};

pub mod pallet {
  use super::*;
  use frame_support::pallet_prelude::*;
  use frame_system::pallet_prelude::*;

  pub struct Pallet<T>(_);

  pub trait Config: frame_system::Config + staking::Config {}

  impl<T: Config> Pallet<T> {
        /// Reward a validator.
        pub fn reward_myself(origin: OriginFor<T>) -> DispatchResult {
            let reported = ensure_signed(origin)?;
            <staking::Pallet<T>>::reward_by_ids(vec![(reported, 10)]);

§Implementation Details

§Era payout

The era payout is computed using yearly inflation curve defined at Config::EraPayout as such:

staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year

This payout is used to reward stakers as defined in next section

remaining_payout = max_yearly_inflation * total_tokens / era_per_year - staker_payout

Note, however, that it is possible to set a cap on the total staker_payout for the era through the MaxStakersRewards storage type. The era_payout implementor must ensure that the max_payout = remaining_payout + (staker_payout * max_stakers_rewards). The excess payout that is not allocated for stakers is the era remaining reward.

The remaining reward is send to the configurable end-point Config::RewardRemainder.

§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.

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.

Pallet implements pallet_authorship::EventHandler 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, 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 nominators that nominated the validator, proportional to the value staked behind the validator (i.e. dividing the own or others by total in 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 set_payee), to be one of the following:

  • Stash account, not increasing the staked value.
  • Stash account, also increasing the staked value.
  • Any other account, sent as free balance.

§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 call. Note that the funds are not immediately accessible. Instead, a duration denoted by Config::BondingDuration (in number of eras) must pass until the funds can actually be removed. Once the BondingDuration is over, the 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. 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.

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.


The Staking pallet depends on the GenesisConfig. The GenesisConfig is optional and allow to set some initial stakers.

  • Balances: Used to manage values at stake.
  • Session: Used to manage sessions. Also, a list of new validators is stored in the Session pallet’s Validators at the end of each era.


  • pub use weights::WeightInfo;
  • pub use __tt_error_token_1 as tt_error_token;
  • pub use __tt_default_parts_7 as tt_default_parts;
  • pub use __tt_extra_parts_7 as tt_extra_parts;
  • pub use __tt_default_parts_v2_7 as tt_default_parts_v2;


  • Default implementations of DefaultConfig, which can be used to implement Config.
  • Auto-generated docs-only module listing all defined dispatchables for this pallet.
  • A static size tracker for the election snapshot data.
  • This module expose one function P_NPoS (Payout NPoS) or compute_total_payout which returns the total payout for the era given the era duration and the staking rate in NPoS. The staking rate in NPoS is the total amount of tokens staked by nominators and validators, divided by the total token supply.
  • A Ledger implementation for stakers.
  • Storage migrations for the Staking pallet. The changelog for this is maintained at
  • A slashing implementation for NPoS systems.
  • Auto-generated docs-only module listing all (public and private) defined storage types for this pallet.
  • Autogenerated weights for pallet_staking



  • Information regarding the active era (era in used in session).
  • Adaptor to turn a PiecewiseLinear curve definition into an EraPayout impl, used for backwards compatibility.
  • 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.
  • Reward points of an era. Used to split era total payout between validators.
  • A snapshot of the stake backing a single validator in the system.
  • A typed conversion from stash account ID to the active exposure of nominators on that account.
  • Filter historical offences out and only allow those from the bonding period.
  • A nomination quota that allows up to MAX nominations for all validators.
  • Can be used to configure the genesis state of this pallet.
  • The amount of exposure for an era that an individual nominator has (susceptible to slashing).
  • A record of the nominations made by a specific account.
  • Facade struct to encapsulate PagedExposureMetadata and a single page of ExposurePage.
  • The Pallet struct, the main type that implements traits and standalone functions within the pallet.
  • The ledger of a (bonded) stash.
  • A Convert implementation that finds the stash of the given controller account, if any.
  • A mock benchmarking config for pallet-staking.
  • A pending slash record. The value of the slash has been computed but not applied yet, rather deferred for several eras.
  • Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.
  • Implementation of DisablingStrategy which disables validators from the active set up to a threshold. DISABLING_LIMIT_FACTOR is the factor of the maximum disabled validators in the active set. E.g. setting this value to 3 means no more than 1/3 of the validators in the active set can be disabled in an era. By default a factor of 3 is used which is the byzantine threshold.
  • A simple voter list implementation that does not require any additional pallets. Note, this does not provided nominators in sorted ordered. If you desire nominators in a sorted order take a look at [`pallet-bags-list].
  • A simple sorted list implementation that does not require any additional pallets. Note, this does not provide validators in sorted order. If you desire nominators in a sorted order take a look at [pallet-bags-list].
  • Preference of what happens regarding validation.


  • Contains a variant per dispatchable extrinsic that this pallet has.
  • Possible operations on the configuration values of this pallet.
  • The Error enum of this pallet.
  • The Event enum of this pallet
  • Mode of era-forcing.
  • A destination account for payment.
  • Representation of the status of a staker.


Type Aliases§

  • The active era information, it holds index and start.
  • The balance type of this pallet.
  • Map from all locked “stash” accounts to the controller account.
  • The amount of currency given to reporters of a slash event which was canceled by extraordinary circumstances (e.g. governance).
  • History of claimed paged rewards by era and validator.
  • The current era index.
  • The last planned session scheduled by the session pallet.
  • Indices of validators that have offended in the active era. The offenders are disabled for a whole era. For this reason they are kept here - only staking pallet knows about eras. The implementor of DisablingStrategy defines if a validator should be disabled which implicitly means that the implementor also controls the max number of disabled validators.
  • Rewards for the last Config::HistoryDepth eras. If reward hasn’t been set or has been removed then 0 reward is returned.
  • Exposure of validator at era.
  • Clipped Exposure of validator at era.
  • Summary of validator exposure at a given era.
  • Paginated exposure of a validator at given era.
  • The session index at which the era start for the last Config::HistoryDepth 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.
  • Similar to ErasStakers, this holds the preferences of validators.
  • The total validator era payout for the last Config::HistoryDepth eras.
  • Mode of era forcing.
  • 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.
  • Map from all (unlocked) “controller” accounts to the info regarding the staking.
  • Maximum number of nominations per nominator.
  • The maximum nominator count before we stop allowing new validators to join.
  • Maximum staked rewards, i.e. the percentage of the era inflation that is used for stake rewards. See Era payout.
  • The maximum validator count before we stop allowing new validators to join.
  • Maximum number of winners (aka. active validators), as defined in the election provider of this pallet.
  • The minimum amount of commission that validators can set.
  • The minimum active bond to become and maintain the role of a nominator.
  • The minimum active bond to become and maintain the role of a validator.
  • The minimum active nominator stake of the last successful election.
  • Minimum number of staking participants before emergency conditions are imposed.
  • ModuleDeprecated
    Type alias to Pallet, to be used by construct_runtime.
  • The map from nominator stash key to their nomination preferences, namely the validators that they wish to support.
  • Where the reward payment should be made. Keyed by stash.
  • Counter for the number of “reward” points earned by a given validator.
  • The percentage of the slash that is distributed to reporters.
  • Slashing spans for stash accounts.
  • All unapplied slashes that are queued for later.
  • The ideal number of active validators.
  • The map from (wannabe) validator stash key to the preferences of that validator.
  • Stakers whose funds are managed by other pallets.