pallet_staking/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Staking Pallet
19//!
20//! The Staking pallet is used to manage funds at stake by network maintainers.
21//!
22//! - [`Config`]
23//! - [`Call`]
24//! - [`Pallet`]
25//!
26//! ## Overview
27//!
28//! The Staking pallet is the means by which a set of network maintainers (known as _authorities_ in
29//! some contexts and _validators_ in others) are chosen based upon those who voluntarily place
30//! funds under deposit. Under deposit, those funds are rewarded under normal operation but are held
31//! at pain of _slash_ (expropriation) should the staked maintainer be found not to be discharging
32//! its duties properly.
33//!
34//! ### Terminology
35//! <!-- Original author of paragraph: @gavofyork -->
36//!
37//! - Staking: The process of locking up funds for some time, placing them at risk of slashing
38//!   (loss) in order to become a rewarded maintainer of the network.
39//! - Validating: The process of running a node to actively maintain the network, either by
40//!   producing blocks or guaranteeing finality of the chain.
41//! - Nominating: The process of placing staked funds behind one or more validators in order to
42//!   share in any reward, and punishment, they take.
43//! - Stash account: The account holding an owner's funds used for staking.
44//! - Controller account (being deprecated): The account that controls an owner's funds for staking.
45//! - Era: A (whole) number of sessions, which is the period that the validator set (and each
46//!   validator's active nominator set) is recalculated and where rewards are paid out.
47//! - Slash: The punishment of a staker by reducing its funds.
48//!
49//! ### Goals
50//! <!-- Original author of paragraph: @gavofyork -->
51//!
52//! The staking system in Substrate NPoS is designed to make the following possible:
53//!
54//! - Stake funds that are controlled by a cold wallet.
55//! - Withdraw some, or deposit more, funds without interrupting the role of an entity.
56//! - Switch between roles (nominator, validator, idle) with minimal overhead.
57//!
58//! ### Scenarios
59//!
60//! #### Staking
61//!
62//! Almost any interaction with the Staking pallet requires a process of _**bonding**_ (also known
63//! as being a _staker_). To become *bonded*, a fund-holding register known as the _stash account_,
64//! which holds some or all of the funds that become frozen in place as part of the staking process.
65//! The controller account, which this pallet now assigns the stash account to, issues instructions
66//! on how funds shall be used.
67//!
68//! An account can become a bonded stash account using the [`bond`](Call::bond) call.
69//!
70//! In the event stash accounts registered a unique controller account before the controller account
71//! deprecation, they can update their associated controller back to the stash account using the
72//! [`set_controller`](Call::set_controller) call.
73//!
74//! There are three possible roles that any staked account pair can be in: `Validator`, `Nominator`
75//! and `Idle` (defined in [`StakerStatus`]). There are three corresponding instructions to change
76//! between roles, namely: [`validate`](Call::validate), [`nominate`](Call::nominate), and
77//! [`chill`](Call::chill).
78//!
79//! #### Validating
80//!
81//! A **validator** takes the role of either validating blocks or ensuring their finality,
82//! maintaining the veracity of the network. A validator should avoid both any sort of malicious
83//! misbehavior and going offline. Bonded accounts that state interest in being a validator do NOT
84//! get immediately chosen as a validator. Instead, they are declared as a _candidate_ and they
85//! _might_ get elected at the _next era_ as a validator. The result of the election is determined
86//! by nominators and their votes.
87//!
88//! An account can become a validator candidate via the [`validate`](Call::validate) call.
89//!
90//! #### Nomination
91//!
92//! A **nominator** does not take any _direct_ role in maintaining the network, instead, it votes on
93//! a set of validators to be elected. Once interest in nomination is stated by an account, it takes
94//! effect at the next election round. The funds in the nominator's stash account indicate the
95//! _weight_ of its vote. Both the rewards and any punishment that a validator earns are shared
96//! between the validator and its nominators. This rule incentivizes the nominators to NOT vote for
97//! the misbehaving/offline validators as much as possible, simply because the nominators will also
98//! lose funds if they vote poorly.
99//!
100//! An account can become a nominator via the [`nominate`](Call::nominate) call.
101//!
102//! #### Voting
103//!
104//! Staking is closely related to elections; actual validators are chosen from among all potential
105//! validators via election by the potential validators and nominators. To reduce use of the phrase
106//! "potential validators and nominators", we often use the term **voters**, who are simply the
107//! union of potential validators and nominators.
108//!
109//! #### Rewards and Slash
110//!
111//! The **reward and slashing** procedure is the core of the Staking pallet, attempting to _embrace
112//! valid behavior_ while _punishing any misbehavior or lack of availability_.
113//!
114//! Rewards must be claimed for each era before it gets too old by
115//! [`HistoryDepth`](`Config::HistoryDepth`) using the `payout_stakers` call. Any account can call
116//! `payout_stakers`, which pays the reward to the validator as well as its nominators. Only
117//! [`Config::MaxExposurePageSize`] nominator rewards can be claimed in a single call. When the
118//! number of nominators exceeds [`Config::MaxExposurePageSize`], then the exposed nominators are
119//! stored in multiple pages, with each page containing up to [`Config::MaxExposurePageSize`]
120//! nominators. To pay out all nominators, `payout_stakers` must be called once for each available
121//! page. Paging exists to limit the i/o cost to mutate storage for each nominator's account.
122//!
123//! Slashing can occur at any point in time, once misbehavior is reported. Once slashing is
124//! determined, a value is deducted from the balance of the validator and all the nominators who
125//! voted for this validator (values are deducted from the _stash_ account of the slashed entity).
126//!
127//! Slashing logic is further described in the documentation of the `slashing` pallet.
128//!
129//! Similar to slashing, rewards are also shared among a validator and its associated nominators.
130//! Yet, the reward funds are not always transferred to the stash account and can be configured. See
131//! [Reward Calculation](#reward-calculation) for more details.
132//!
133//! #### Chilling
134//!
135//! Finally, any of the roles above can choose to step back temporarily and just chill for a while.
136//! This means that if they are a nominator, they will not be considered as voters anymore and if
137//! they are validators, they will no longer be a candidate for the next election.
138//!
139//! An account can step back via the [`chill`](Call::chill) call.
140//!
141//! ### Session managing
142//!
143//! The pallet implement the trait `SessionManager`. Which is the only API to query new validator
144//! set and allowing these validator set to be rewarded once their era is ended.
145//!
146//! ## Interface
147//!
148//! ### Dispatchable Functions
149//!
150//! The dispatchable functions of the Staking pallet enable the steps needed for entities to accept
151//! and change their role, alongside some helper functions to get/set the metadata of the pallet.
152//!
153//! ### Public Functions
154//!
155//! The Staking pallet contains many public storage items and (im)mutable functions.
156//!
157//! ## Usage
158//!
159//! ### Example: Rewarding a validator by id.
160//!
161//! ```
162//! use pallet_staking::{self as staking};
163//!
164//! #[frame_support::pallet(dev_mode)]
165//! pub mod pallet {
166//!   use super::*;
167//!   use frame_support::pallet_prelude::*;
168//!   use frame_system::pallet_prelude::*;
169//!
170//!   #[pallet::pallet]
171//!   pub struct Pallet<T>(_);
172//!
173//!   #[pallet::config]
174//!   pub trait Config: frame_system::Config + staking::Config {}
175//!
176//!   #[pallet::call]
177//!   impl<T: Config> Pallet<T> {
178//!         /// Reward a validator.
179//!         #[pallet::weight(0)]
180//!         pub fn reward_myself(origin: OriginFor<T>) -> DispatchResult {
181//!             let reported = ensure_signed(origin)?;
182//!             <staking::Pallet<T>>::reward_by_ids(vec![(reported, 10)]);
183//!             Ok(())
184//!         }
185//!     }
186//! }
187//! # fn main() { }
188//! ```
189//!
190//! ## Implementation Details
191//!
192//! ### Era payout
193//!
194//! The era payout is computed using yearly inflation curve defined at [`Config::EraPayout`] as
195//! such:
196//!
197//! ```nocompile
198//! staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year
199//! ```
200//! This payout is used to reward stakers as defined in next section
201//!
202//! ```nocompile
203//! remaining_payout = max_yearly_inflation * total_tokens / era_per_year - staker_payout
204//! ```
205//!
206//! Note, however, that it is possible to set a cap on the total `staker_payout` for the era through
207//! the `MaxStakersRewards` storage type. The `era_payout` implementor must ensure that the
208//! `max_payout = remaining_payout + (staker_payout * max_stakers_rewards)`. The excess payout that
209//! is not allocated for stakers is the era remaining reward.
210//!
211//! The remaining reward is send to the configurable end-point [`Config::RewardRemainder`].
212//!
213//! ### Reward Calculation
214//!
215//! Validators and nominators are rewarded at the end of each era. The total reward of an era is
216//! calculated using the era duration and the staking rate (the total amount of tokens staked by
217//! nominators and validators, divided by the total token supply). It aims to incentivize toward a
218//! defined staking rate. The full specification can be found
219//! [here](https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model).
220//!
221//! Total reward is split among validators and their nominators depending on the number of points
222//! they received during the era. Points are added to a validator using
223//! [`reward_by_ids`](Pallet::reward_by_ids).
224//!
225//! [`Pallet`] implements [`pallet_authorship::EventHandler`] to add reward points to block producer
226//! and block producer of referenced uncles.
227//!
228//! The validator and its nominator split their reward as following:
229//!
230//! The validator can declare an amount, named [`commission`](ValidatorPrefs::commission), that does
231//! not get shared with the nominators at each reward payout through its [`ValidatorPrefs`]. This
232//! value gets deducted from the total reward that is paid to the validator and its nominators. The
233//! remaining portion is split pro rata among the validator and the nominators that nominated the
234//! validator, proportional to the value staked behind the validator (_i.e._ dividing the
235//! [`own`](Exposure::own) or [`others`](Exposure::others) by [`total`](Exposure::total) in
236//! [`Exposure`]). Note that payouts are made in pages with each page capped at
237//! [`Config::MaxExposurePageSize`] nominators. The distribution of nominators across pages may be
238//! unsorted. The total commission is paid out proportionally across pages based on the total stake
239//! of the page.
240//!
241//! All entities who receive a reward have the option to choose their reward destination through the
242//! [`Payee`] storage item (see [`set_payee`](Call::set_payee)), to be one of the following:
243//!
244//! - Stash account, not increasing the staked value.
245//! - Stash account, also increasing the staked value.
246//! - Any other account, sent as free balance.
247//!
248//! ### Additional Fund Management Operations
249//!
250//! Any funds already placed into stash can be the target of the following operations:
251//!
252//! The controller account can free a portion (or all) of the funds using the
253//! [`unbond`](Call::unbond) call. Note that the funds are not immediately accessible. Instead, a
254//! duration denoted by [`Config::BondingDuration`] (in number of eras) must pass until the funds
255//! can actually be removed. Once the `BondingDuration` is over, the
256//! [`withdraw_unbonded`](Call::withdraw_unbonded) call can be used to actually withdraw the funds.
257//!
258//! Note that there is a limitation to the number of fund-chunks that can be scheduled to be
259//! unlocked in the future via [`unbond`](Call::unbond). In case this maximum
260//! (`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful
261//! call to `withdraw_unbonded` to remove some of the chunks.
262//!
263//! ### Election Algorithm
264//!
265//! The current election algorithm is implemented based on Phragmén. The reference implementation
266//! can be found [here](https://github.com/w3f/consensus/tree/master/NPoS).
267//!
268//! The election algorithm, aside from electing the validators with the most stake value and votes,
269//! tries to divide the nominator votes among candidates in an equal manner. To further assure this,
270//! an optional post-processing can be applied that iteratively normalizes the nominator staked
271//! values until the total difference among votes of a particular nominator are less than a
272//! threshold.
273//!
274//! ## GenesisConfig
275//!
276//! The Staking pallet depends on the [`GenesisConfig`]. The `GenesisConfig` is optional and allow
277//! to set some initial stakers.
278//!
279//! ## Related Modules
280//!
281//! - [Balances](../pallet_balances/index.html): Used to manage values at stake.
282//! - [Session](../pallet_session/index.html): Used to manage sessions. Also, a list of new
283//!   validators is stored in the Session pallet's `Validators` at the end of each era.
284
285#![cfg_attr(not(feature = "std"), no_std)]
286#![recursion_limit = "256"]
287
288#[cfg(feature = "runtime-benchmarks")]
289pub mod benchmarking;
290#[cfg(any(feature = "runtime-benchmarks", test))]
291pub mod testing_utils;
292
293#[cfg(test)]
294pub(crate) mod mock;
295#[cfg(test)]
296mod tests;
297
298pub mod asset;
299pub mod election_size_tracker;
300pub mod inflation;
301pub mod ledger;
302pub mod migrations;
303pub mod slashing;
304pub mod weights;
305
306mod pallet;
307
308extern crate alloc;
309
310use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec};
311use codec::{Decode, DecodeWithMemTracking, Encode, HasCompact, MaxEncodedLen};
312use frame_support::{
313	defensive, defensive_assert,
314	traits::{
315		tokens::fungible::{Credit, Debt},
316		ConstU32, Contains, Defensive, DefensiveMax, DefensiveSaturating, Get, LockIdentifier,
317	},
318	weights::Weight,
319	BoundedVec, CloneNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound,
320};
321use scale_info::TypeInfo;
322use sp_runtime::{
323	curve::PiecewiseLinear,
324	traits::{AtLeast32BitUnsigned, Convert, StaticLookup, Zero},
325	Perbill, Perquintill, Rounding, RuntimeDebug, Saturating,
326};
327use sp_staking::{
328	offence::{Offence, OffenceError, OffenceSeverity, ReportOffence},
329	EraIndex, ExposurePage, OnStakingUpdate, Page, PagedExposureMetadata, SessionIndex,
330	StakingAccount,
331};
332pub use sp_staking::{Exposure, IndividualExposure, StakerStatus};
333pub use weights::WeightInfo;
334
335pub use pallet::{pallet::*, UseNominatorsAndValidatorsMap, UseValidatorsMap};
336
337pub(crate) const STAKING_ID: LockIdentifier = *b"staking ";
338pub(crate) const LOG_TARGET: &str = "runtime::staking";
339
340// syntactic sugar for logging.
341#[macro_export]
342macro_rules! log {
343	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
344		log::$level!(
345			target: crate::LOG_TARGET,
346			concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
347		)
348	};
349}
350
351/// Maximum number of winners (aka. active validators), as defined in the election provider of this
352/// pallet.
353pub type MaxWinnersOf<T> = <<T as Config>::ElectionProvider as frame_election_provider_support::ElectionProviderBase>::MaxWinners;
354
355/// Maximum number of nominations per nominator.
356pub type MaxNominationsOf<T> =
357	<<T as Config>::NominationsQuota as NominationsQuota<BalanceOf<T>>>::MaxNominations;
358
359/// Counter for the number of "reward" points earned by a given validator.
360pub type RewardPoint = u32;
361
362/// The balance type of this pallet.
363pub type BalanceOf<T> = <T as Config>::CurrencyBalance;
364
365type PositiveImbalanceOf<T> = Debt<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
366pub type NegativeImbalanceOf<T> =
367	Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
368
369type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
370
371/// Information regarding the active era (era in used in session).
372#[derive(Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
373pub struct ActiveEraInfo {
374	/// Index of era.
375	pub index: EraIndex,
376	/// Moment of start expressed as millisecond from `$UNIX_EPOCH`.
377	///
378	/// Start can be none if start hasn't been set for the era yet,
379	/// Start is set on the first on_finalize of the era to guarantee usage of `Time`.
380	pub start: Option<u64>,
381}
382
383/// Reward points of an era. Used to split era total payout between validators.
384///
385/// This points will be used to reward validators and their respective nominators.
386#[derive(PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
387pub struct EraRewardPoints<AccountId: Ord> {
388	/// Total number of points. Equals the sum of reward points for each validator.
389	pub total: RewardPoint,
390	/// The reward points earned by a given validator.
391	pub individual: BTreeMap<AccountId, RewardPoint>,
392}
393
394impl<AccountId: Ord> Default for EraRewardPoints<AccountId> {
395	fn default() -> Self {
396		EraRewardPoints { total: Default::default(), individual: BTreeMap::new() }
397	}
398}
399
400/// A destination account for payment.
401#[derive(
402	PartialEq,
403	Eq,
404	Copy,
405	Clone,
406	Encode,
407	Decode,
408	DecodeWithMemTracking,
409	RuntimeDebug,
410	TypeInfo,
411	MaxEncodedLen,
412)]
413pub enum RewardDestination<AccountId> {
414	/// Pay into the stash account, increasing the amount at stake accordingly.
415	Staked,
416	/// Pay into the stash account, not increasing the amount at stake.
417	Stash,
418	#[deprecated(
419		note = "`Controller` will be removed after January 2024. Use `Account(controller)` instead."
420	)]
421	Controller,
422	/// Pay into a specified account.
423	Account(AccountId),
424	/// Receive no reward.
425	None,
426}
427
428/// Preference of what happens regarding validation.
429#[derive(
430	PartialEq,
431	Eq,
432	Clone,
433	Encode,
434	Decode,
435	DecodeWithMemTracking,
436	RuntimeDebug,
437	TypeInfo,
438	Default,
439	MaxEncodedLen,
440)]
441pub struct ValidatorPrefs {
442	/// Reward that validator takes up-front; only the rest is split between themselves and
443	/// nominators.
444	#[codec(compact)]
445	pub commission: Perbill,
446	/// Whether or not this validator is accepting more nominations. If `true`, then no nominator
447	/// who is not already nominating this validator may nominate them. By default, validators
448	/// are accepting nominations.
449	pub blocked: bool,
450}
451
452/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.
453#[derive(
454	PartialEq,
455	Eq,
456	Clone,
457	Encode,
458	Decode,
459	DecodeWithMemTracking,
460	RuntimeDebug,
461	TypeInfo,
462	MaxEncodedLen,
463)]
464pub struct UnlockChunk<Balance: HasCompact + MaxEncodedLen> {
465	/// Amount of funds to be unlocked.
466	#[codec(compact)]
467	value: Balance,
468	/// Era number at which point it'll be unlocked.
469	#[codec(compact)]
470	era: EraIndex,
471}
472
473/// The ledger of a (bonded) stash.
474///
475/// Note: All the reads and mutations to the [`Ledger`], [`Bonded`] and [`Payee`] storage items
476/// *MUST* be performed through the methods exposed by this struct, to ensure the consistency of
477/// ledger's data and corresponding staking lock
478///
479/// TODO: move struct definition and full implementation into `/src/ledger.rs`. Currently
480/// leaving here to enforce a clean PR diff, given how critical this logic is. Tracking issue
481/// <https://github.com/paritytech/substrate/issues/14749>.
482#[derive(
483	PartialEqNoBound,
484	EqNoBound,
485	CloneNoBound,
486	Encode,
487	Decode,
488	RuntimeDebugNoBound,
489	TypeInfo,
490	MaxEncodedLen,
491)]
492#[scale_info(skip_type_params(T))]
493pub struct StakingLedger<T: Config> {
494	/// The stash account whose balance is actually locked and at stake.
495	pub stash: T::AccountId,
496
497	/// The total amount of the stash's balance that we are currently accounting for.
498	/// It's just `active` plus all the `unlocking` balances.
499	#[codec(compact)]
500	pub total: BalanceOf<T>,
501
502	/// The total amount of the stash's balance that will be at stake in any forthcoming
503	/// rounds.
504	#[codec(compact)]
505	pub active: BalanceOf<T>,
506
507	/// Any balance that is becoming free, which may eventually be transferred out of the stash
508	/// (assuming it doesn't get slashed first). It is assumed that this will be treated as a first
509	/// in, first out queue where the new (higher value) eras get pushed on the back.
510	pub unlocking: BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
511
512	/// List of eras for which the stakers behind a validator have claimed rewards. Only updated
513	/// for validators.
514	///
515	/// This is deprecated as of V14 in favor of `T::ClaimedRewards` and will be removed in future.
516	/// Refer to issue <https://github.com/paritytech/polkadot-sdk/issues/433>
517	pub legacy_claimed_rewards: BoundedVec<EraIndex, T::HistoryDepth>,
518
519	/// The controller associated with this ledger's stash.
520	///
521	/// This is not stored on-chain, and is only bundled when the ledger is read from storage.
522	/// Use [`controller`] function to get the controller associated with the ledger.
523	#[codec(skip)]
524	controller: Option<T::AccountId>,
525}
526
527/// State of a ledger with regards with its data and metadata integrity.
528#[derive(PartialEq, Debug)]
529enum LedgerIntegrityState {
530	/// Ledger, bond and corresponding staking lock is OK.
531	Ok,
532	/// Ledger and/or bond is corrupted. This means that the bond has a ledger with a different
533	/// stash than the bonded stash.
534	Corrupted,
535	/// Ledger was corrupted and it has been killed.
536	CorruptedKilled,
537	/// Ledger and bond are OK, however the ledger's stash lock is out of sync.
538	LockCorrupted,
539}
540
541impl<T: Config> StakingLedger<T> {
542	/// Remove entries from `unlocking` that are sufficiently old and reduce the
543	/// total by the sum of their balances.
544	fn consolidate_unlocked(self, current_era: EraIndex) -> Self {
545		let mut total = self.total;
546		let unlocking: BoundedVec<_, _> = self
547			.unlocking
548			.into_iter()
549			.filter(|chunk| {
550				if chunk.era > current_era {
551					true
552				} else {
553					total = total.saturating_sub(chunk.value);
554					false
555				}
556			})
557			.collect::<Vec<_>>()
558			.try_into()
559			.expect(
560				"filtering items from a bounded vec always leaves length less than bounds. qed",
561			);
562
563		Self {
564			stash: self.stash,
565			total,
566			active: self.active,
567			unlocking,
568			legacy_claimed_rewards: self.legacy_claimed_rewards,
569			controller: self.controller,
570		}
571	}
572
573	/// Sets ledger total to the `new_total`.
574	///
575	/// Removes entries from `unlocking` upto `amount` starting from the oldest first.
576	fn update_total_stake(mut self, new_total: BalanceOf<T>) -> Self {
577		let old_total = self.total;
578		self.total = new_total;
579		debug_assert!(
580			new_total <= old_total,
581			"new_total {:?} must be <= old_total {:?}",
582			new_total,
583			old_total
584		);
585
586		let to_withdraw = old_total.defensive_saturating_sub(new_total);
587		// accumulator to keep track of how much is withdrawn.
588		// First we take out from active.
589		let mut withdrawn = BalanceOf::<T>::zero();
590
591		// first we try to remove stake from active
592		if self.active >= to_withdraw {
593			self.active -= to_withdraw;
594			return self
595		} else {
596			withdrawn += self.active;
597			self.active = BalanceOf::<T>::zero();
598		}
599
600		// start removing from the oldest chunk.
601		while let Some(last) = self.unlocking.last_mut() {
602			if withdrawn.defensive_saturating_add(last.value) <= to_withdraw {
603				withdrawn += last.value;
604				self.unlocking.pop();
605			} else {
606				let diff = to_withdraw.defensive_saturating_sub(withdrawn);
607				withdrawn += diff;
608				last.value -= diff;
609			}
610
611			if withdrawn >= to_withdraw {
612				break
613			}
614		}
615
616		self
617	}
618
619	/// Re-bond funds that were scheduled for unlocking.
620	///
621	/// Returns the updated ledger, and the amount actually rebonded.
622	fn rebond(mut self, value: BalanceOf<T>) -> (Self, BalanceOf<T>) {
623		let mut unlocking_balance = BalanceOf::<T>::zero();
624
625		while let Some(last) = self.unlocking.last_mut() {
626			if unlocking_balance.defensive_saturating_add(last.value) <= value {
627				unlocking_balance += last.value;
628				self.active += last.value;
629				self.unlocking.pop();
630			} else {
631				let diff = value.defensive_saturating_sub(unlocking_balance);
632
633				unlocking_balance += diff;
634				self.active += diff;
635				last.value -= diff;
636			}
637
638			if unlocking_balance >= value {
639				break
640			}
641		}
642
643		(self, unlocking_balance)
644	}
645
646	/// Slash the staker for a given amount of balance.
647	///
648	/// This implements a proportional slashing system, whereby we set our preference to slash as
649	/// such:
650	///
651	/// - If any unlocking chunks exist that are scheduled to be unlocked at `slash_era +
652	///   bonding_duration` and onwards, the slash is divided equally between the active ledger and
653	///   the unlocking chunks.
654	/// - If no such chunks exist, then only the active balance is slashed.
655	///
656	/// Note that the above is only a *preference*. If for any reason the active ledger, with or
657	/// without some portion of the unlocking chunks that are more justified to be slashed are not
658	/// enough, then the slashing will continue and will consume as much of the active and unlocking
659	/// chunks as needed.
660	///
661	/// This will never slash more than the given amount. If any of the chunks become dusted, the
662	/// last chunk is slashed slightly less to compensate. Returns the amount of funds actually
663	/// slashed.
664	///
665	/// `slash_era` is the era in which the slash (which is being enacted now) actually happened.
666	///
667	/// This calls `Config::OnStakingUpdate::on_slash` with information as to how the slash was
668	/// applied.
669	pub fn slash(
670		&mut self,
671		slash_amount: BalanceOf<T>,
672		minimum_balance: BalanceOf<T>,
673		slash_era: EraIndex,
674	) -> BalanceOf<T> {
675		if slash_amount.is_zero() {
676			return Zero::zero()
677		}
678
679		use sp_runtime::PerThing as _;
680		let mut remaining_slash = slash_amount;
681		let pre_slash_total = self.total;
682
683		// for a `slash_era = x`, any chunk that is scheduled to be unlocked at era `x + 28`
684		// (assuming 28 is the bonding duration) onwards should be slashed.
685		let slashable_chunks_start = slash_era.saturating_add(T::BondingDuration::get());
686
687		// `Some(ratio)` if this is proportional, with `ratio`, `None` otherwise. In both cases, we
688		// slash first the active chunk, and then `slash_chunks_priority`.
689		let (maybe_proportional, slash_chunks_priority) = {
690			if let Some(first_slashable_index) =
691				self.unlocking.iter().position(|c| c.era >= slashable_chunks_start)
692			{
693				// If there exists a chunk who's after the first_slashable_start, then this is a
694				// proportional slash, because we want to slash active and these chunks
695				// proportionally.
696
697				// The indices of the first chunk after the slash up through the most recent chunk.
698				// (The most recent chunk is at greatest from this era)
699				let affected_indices = first_slashable_index..self.unlocking.len();
700				let unbonding_affected_balance =
701					affected_indices.clone().fold(BalanceOf::<T>::zero(), |sum, i| {
702						if let Some(chunk) = self.unlocking.get(i).defensive() {
703							sum.saturating_add(chunk.value)
704						} else {
705							sum
706						}
707					});
708				let affected_balance = self.active.saturating_add(unbonding_affected_balance);
709				let ratio = Perquintill::from_rational_with_rounding(
710					slash_amount,
711					affected_balance,
712					Rounding::Up,
713				)
714				.unwrap_or_else(|_| Perquintill::one());
715				(
716					Some(ratio),
717					affected_indices.chain((0..first_slashable_index).rev()).collect::<Vec<_>>(),
718				)
719			} else {
720				// We just slash from the last chunk to the most recent one, if need be.
721				(None, (0..self.unlocking.len()).rev().collect::<Vec<_>>())
722			}
723		};
724
725		// Helper to update `target` and the ledgers total after accounting for slashing `target`.
726		log!(
727			debug,
728			"slashing {:?} for era {:?} out of {:?}, priority: {:?}, proportional = {:?}",
729			slash_amount,
730			slash_era,
731			self,
732			slash_chunks_priority,
733			maybe_proportional,
734		);
735
736		let mut slash_out_of = |target: &mut BalanceOf<T>, slash_remaining: &mut BalanceOf<T>| {
737			let mut slash_from_target = if let Some(ratio) = maybe_proportional {
738				ratio.mul_ceil(*target)
739			} else {
740				*slash_remaining
741			}
742			// this is the total that that the slash target has. We can't slash more than
743			// this anyhow!
744			.min(*target)
745			// this is the total amount that we would have wanted to slash
746			// non-proportionally, a proportional slash should never exceed this either!
747			.min(*slash_remaining);
748
749			// slash out from *target exactly `slash_from_target`.
750			*target = *target - slash_from_target;
751			if *target < minimum_balance {
752				// Slash the rest of the target if it's dust. This might cause the last chunk to be
753				// slightly under-slashed, by at most `MaxUnlockingChunks * ED`, which is not a big
754				// deal.
755				slash_from_target =
756					core::mem::replace(target, Zero::zero()).saturating_add(slash_from_target)
757			}
758
759			self.total = self.total.saturating_sub(slash_from_target);
760			*slash_remaining = slash_remaining.saturating_sub(slash_from_target);
761		};
762
763		// If this is *not* a proportional slash, the active will always wiped to 0.
764		slash_out_of(&mut self.active, &mut remaining_slash);
765
766		let mut slashed_unlocking = BTreeMap::<_, _>::new();
767		for i in slash_chunks_priority {
768			if remaining_slash.is_zero() {
769				break
770			}
771
772			if let Some(chunk) = self.unlocking.get_mut(i).defensive() {
773				slash_out_of(&mut chunk.value, &mut remaining_slash);
774				// write the new slashed value of this chunk to the map.
775				slashed_unlocking.insert(chunk.era, chunk.value);
776			} else {
777				break
778			}
779		}
780
781		// clean unlocking chunks that are set to zero.
782		self.unlocking.retain(|c| !c.value.is_zero());
783
784		let final_slashed_amount = pre_slash_total.saturating_sub(self.total);
785		T::EventListeners::on_slash(
786			&self.stash,
787			self.active,
788			&slashed_unlocking,
789			final_slashed_amount,
790		);
791		final_slashed_amount
792	}
793}
794
795/// A record of the nominations made by a specific account.
796#[derive(
797	PartialEqNoBound, EqNoBound, Clone, Encode, Decode, RuntimeDebugNoBound, TypeInfo, MaxEncodedLen,
798)]
799#[codec(mel_bound())]
800#[scale_info(skip_type_params(T))]
801pub struct Nominations<T: Config> {
802	/// The targets of nomination.
803	pub targets: BoundedVec<T::AccountId, MaxNominationsOf<T>>,
804	/// The era the nominations were submitted.
805	///
806	/// Except for initial nominations which are considered submitted at era 0.
807	pub submitted_in: EraIndex,
808	/// Whether the nominations have been suppressed. This can happen due to slashing of the
809	/// validators, or other events that might invalidate the nomination.
810	///
811	/// NOTE: this for future proofing and is thus far not used.
812	pub suppressed: bool,
813}
814
815/// Facade struct to encapsulate `PagedExposureMetadata` and a single page of `ExposurePage`.
816///
817/// This is useful where we need to take into account the validator's own stake and total exposure
818/// in consideration, in addition to the individual nominators backing them.
819#[derive(Encode, Decode, RuntimeDebug, TypeInfo, PartialEq, Eq)]
820pub struct PagedExposure<AccountId, Balance: HasCompact + codec::MaxEncodedLen> {
821	exposure_metadata: PagedExposureMetadata<Balance>,
822	exposure_page: ExposurePage<AccountId, Balance>,
823}
824
825impl<AccountId, Balance: HasCompact + Copy + AtLeast32BitUnsigned + codec::MaxEncodedLen>
826	PagedExposure<AccountId, Balance>
827{
828	/// Create a new instance of `PagedExposure` from legacy clipped exposures.
829	pub fn from_clipped(exposure: Exposure<AccountId, Balance>) -> Self {
830		Self {
831			exposure_metadata: PagedExposureMetadata {
832				total: exposure.total,
833				own: exposure.own,
834				nominator_count: exposure.others.len() as u32,
835				page_count: 1,
836			},
837			exposure_page: ExposurePage { page_total: exposure.total, others: exposure.others },
838		}
839	}
840
841	/// Returns total exposure of this validator across pages
842	pub fn total(&self) -> Balance {
843		self.exposure_metadata.total
844	}
845
846	/// Returns total exposure of this validator for the current page
847	pub fn page_total(&self) -> Balance {
848		self.exposure_page.page_total + self.exposure_metadata.own
849	}
850
851	/// Returns validator's own stake that is exposed
852	pub fn own(&self) -> Balance {
853		self.exposure_metadata.own
854	}
855
856	/// Returns the portions of nominators stashes that are exposed in this page.
857	pub fn others(&self) -> &Vec<IndividualExposure<AccountId, Balance>> {
858		&self.exposure_page.others
859	}
860}
861
862/// A pending slash record. The value of the slash has been computed but not applied yet,
863/// rather deferred for several eras.
864#[derive(Encode, Decode, RuntimeDebug, TypeInfo)]
865pub struct UnappliedSlash<AccountId, Balance: HasCompact> {
866	/// The stash ID of the offending validator.
867	validator: AccountId,
868	/// The validator's own slash.
869	own: Balance,
870	/// All other slashed stakers and amounts.
871	others: Vec<(AccountId, Balance)>,
872	/// Reporters of the offence; bounty payout recipients.
873	reporters: Vec<AccountId>,
874	/// The amount of payout.
875	payout: Balance,
876}
877
878impl<AccountId, Balance: HasCompact + Zero> UnappliedSlash<AccountId, Balance> {
879	/// Initializes the default object using the given `validator`.
880	pub fn default_from(validator: AccountId) -> Self {
881		Self {
882			validator,
883			own: Zero::zero(),
884			others: vec![],
885			reporters: vec![],
886			payout: Zero::zero(),
887		}
888	}
889}
890
891/// Something that defines the maximum number of nominations per nominator based on a curve.
892///
893/// The method `curve` implements the nomination quota curve and should not be used directly.
894/// However, `get_quota` returns the bounded maximum number of nominations based on `fn curve` and
895/// the nominator's balance.
896pub trait NominationsQuota<Balance> {
897	/// Strict maximum number of nominations that caps the nominations curve. This value can be
898	/// used as the upper bound of the number of votes per nominator.
899	type MaxNominations: Get<u32>;
900
901	/// Returns the voter's nomination quota within reasonable bounds [`min`, `max`], where `min`
902	/// is 1 and `max` is `Self::MaxNominations`.
903	fn get_quota(balance: Balance) -> u32 {
904		Self::curve(balance).clamp(1, Self::MaxNominations::get())
905	}
906
907	/// Returns the voter's nomination quota based on its balance and a curve.
908	fn curve(balance: Balance) -> u32;
909}
910
911/// A nomination quota that allows up to MAX nominations for all validators.
912pub struct FixedNominationsQuota<const MAX: u32>;
913impl<Balance, const MAX: u32> NominationsQuota<Balance> for FixedNominationsQuota<MAX> {
914	type MaxNominations = ConstU32<MAX>;
915
916	fn curve(_: Balance) -> u32 {
917		MAX
918	}
919}
920
921/// Means for interacting with a specialized version of the `session` trait.
922///
923/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Config`
924pub trait SessionInterface<AccountId> {
925	/// Report an offending validator.
926	fn report_offence(validator: AccountId, severity: OffenceSeverity);
927	/// Get the validators from session.
928	fn validators() -> Vec<AccountId>;
929	/// Prune historical session tries up to but not including the given index.
930	fn prune_historical_up_to(up_to: SessionIndex);
931}
932
933impl<T: Config> SessionInterface<<T as frame_system::Config>::AccountId> for T
934where
935	T: pallet_session::Config<ValidatorId = <T as frame_system::Config>::AccountId>,
936	T: pallet_session::historical::Config,
937	T::SessionHandler: pallet_session::SessionHandler<<T as frame_system::Config>::AccountId>,
938	T::SessionManager: pallet_session::SessionManager<<T as frame_system::Config>::AccountId>,
939	T::ValidatorIdOf: Convert<
940		<T as frame_system::Config>::AccountId,
941		Option<<T as frame_system::Config>::AccountId>,
942	>,
943{
944	fn report_offence(
945		validator: <T as frame_system::Config>::AccountId,
946		severity: OffenceSeverity,
947	) {
948		<pallet_session::Pallet<T>>::report_offence(validator, severity)
949	}
950
951	fn validators() -> Vec<<T as frame_system::Config>::AccountId> {
952		<pallet_session::Pallet<T>>::validators()
953	}
954
955	fn prune_historical_up_to(up_to: SessionIndex) {
956		<pallet_session::historical::Pallet<T>>::prune_up_to(up_to);
957	}
958}
959
960impl<AccountId> SessionInterface<AccountId> for () {
961	fn report_offence(_validator: AccountId, _severity: OffenceSeverity) {
962		()
963	}
964	fn validators() -> Vec<AccountId> {
965		Vec::new()
966	}
967	fn prune_historical_up_to(_: SessionIndex) {
968		()
969	}
970}
971
972/// Handler for determining how much of a balance should be paid out on the current era.
973pub trait EraPayout<Balance> {
974	/// Determine the payout for this era.
975	///
976	/// Returns the amount to be paid to stakers in this era, as well as whatever else should be
977	/// paid out ("the rest").
978	fn era_payout(
979		total_staked: Balance,
980		total_issuance: Balance,
981		era_duration_millis: u64,
982	) -> (Balance, Balance);
983}
984
985impl<Balance: Default> EraPayout<Balance> for () {
986	fn era_payout(
987		_total_staked: Balance,
988		_total_issuance: Balance,
989		_era_duration_millis: u64,
990	) -> (Balance, Balance) {
991		(Default::default(), Default::default())
992	}
993}
994
995/// Adaptor to turn a `PiecewiseLinear` curve definition into an `EraPayout` impl, used for
996/// backwards compatibility.
997pub struct ConvertCurve<T>(core::marker::PhantomData<T>);
998impl<Balance, T> EraPayout<Balance> for ConvertCurve<T>
999where
1000	Balance: AtLeast32BitUnsigned + Clone + Copy,
1001	T: Get<&'static PiecewiseLinear<'static>>,
1002{
1003	fn era_payout(
1004		total_staked: Balance,
1005		total_issuance: Balance,
1006		era_duration_millis: u64,
1007	) -> (Balance, Balance) {
1008		let (validator_payout, max_payout) = inflation::compute_total_payout(
1009			T::get(),
1010			total_staked,
1011			total_issuance,
1012			// Duration of era; more than u64::MAX is rewarded as u64::MAX.
1013			era_duration_millis,
1014		);
1015		let rest = max_payout.saturating_sub(validator_payout);
1016		(validator_payout, rest)
1017	}
1018}
1019
1020/// Mode of era-forcing.
1021#[derive(
1022	Copy,
1023	Clone,
1024	PartialEq,
1025	Eq,
1026	Encode,
1027	Decode,
1028	DecodeWithMemTracking,
1029	RuntimeDebug,
1030	TypeInfo,
1031	MaxEncodedLen,
1032	serde::Serialize,
1033	serde::Deserialize,
1034)]
1035pub enum Forcing {
1036	/// Not forcing anything - just let whatever happen.
1037	NotForcing,
1038	/// Force a new era, then reset to `NotForcing` as soon as it is done.
1039	/// Note that this will force to trigger an election until a new era is triggered, if the
1040	/// election failed, the next session end will trigger a new election again, until success.
1041	ForceNew,
1042	/// Avoid a new era indefinitely.
1043	ForceNone,
1044	/// Force a new era at the end of all sessions indefinitely.
1045	ForceAlways,
1046}
1047
1048impl Default for Forcing {
1049	fn default() -> Self {
1050		Forcing::NotForcing
1051	}
1052}
1053
1054/// A `Convert` implementation that finds the stash of the given controller account,
1055/// if any.
1056pub struct StashOf<T>(core::marker::PhantomData<T>);
1057
1058impl<T: Config> Convert<T::AccountId, Option<T::AccountId>> for StashOf<T> {
1059	fn convert(controller: T::AccountId) -> Option<T::AccountId> {
1060		StakingLedger::<T>::paired_account(StakingAccount::Controller(controller))
1061	}
1062}
1063
1064/// A typed conversion from stash account ID to the active exposure of nominators
1065/// on that account.
1066///
1067/// Active exposure is the exposure of the validator set currently validating, i.e. in
1068/// `active_era`. It can differ from the latest planned exposure in `current_era`.
1069pub struct ExposureOf<T>(core::marker::PhantomData<T>);
1070
1071impl<T: Config> Convert<T::AccountId, Option<Exposure<T::AccountId, BalanceOf<T>>>>
1072	for ExposureOf<T>
1073{
1074	fn convert(validator: T::AccountId) -> Option<Exposure<T::AccountId, BalanceOf<T>>> {
1075		ActiveEra::<T>::get()
1076			.map(|active_era| <Pallet<T>>::eras_stakers(active_era.index, &validator))
1077	}
1078}
1079
1080pub struct NullIdentity;
1081impl<T> Convert<T, Option<()>> for NullIdentity {
1082	fn convert(_: T) -> Option<()> {
1083		Some(())
1084	}
1085}
1086
1087/// Filter historical offences out and only allow those from the bonding period.
1088pub struct FilterHistoricalOffences<T, R> {
1089	_inner: core::marker::PhantomData<(T, R)>,
1090}
1091
1092impl<T, Reporter, Offender, R, O> ReportOffence<Reporter, Offender, O>
1093	for FilterHistoricalOffences<Pallet<T>, R>
1094where
1095	T: Config,
1096	R: ReportOffence<Reporter, Offender, O>,
1097	O: Offence<Offender>,
1098{
1099	fn report_offence(reporters: Vec<Reporter>, offence: O) -> Result<(), OffenceError> {
1100		// Disallow any slashing from before the current bonding period.
1101		let offence_session = offence.session_index();
1102		let bonded_eras = BondedEras::<T>::get();
1103
1104		if bonded_eras.first().filter(|(_, start)| offence_session >= *start).is_some() {
1105			R::report_offence(reporters, offence)
1106		} else {
1107			<Pallet<T>>::deposit_event(Event::<T>::OldSlashingReportDiscarded {
1108				session_index: offence_session,
1109			});
1110			Ok(())
1111		}
1112	}
1113
1114	fn is_known_offence(offenders: &[Offender], time_slot: &O::TimeSlot) -> bool {
1115		R::is_known_offence(offenders, time_slot)
1116	}
1117}
1118
1119/// Wrapper struct for Era related information. It is not a pure encapsulation as these storage
1120/// items can be accessed directly but nevertheless, its recommended to use `EraInfo` where we
1121/// can and add more functions to it as needed.
1122pub struct EraInfo<T>(core::marker::PhantomData<T>);
1123impl<T: Config> EraInfo<T> {
1124	/// Returns true if validator has one or more page of era rewards not claimed yet.
1125	// Also looks at legacy storage that can be cleaned up after #433.
1126	pub fn pending_rewards(era: EraIndex, validator: &T::AccountId) -> bool {
1127		let page_count = if let Some(overview) = <ErasStakersOverview<T>>::get(&era, validator) {
1128			overview.page_count
1129		} else {
1130			if <ErasStakers<T>>::contains_key(era, validator) {
1131				// this means non paged exposure, and we treat them as single paged.
1132				1
1133			} else {
1134				// if no exposure, then no rewards to claim.
1135				return false
1136			}
1137		};
1138
1139		// check if era is marked claimed in legacy storage.
1140		if <Ledger<T>>::get(validator)
1141			.map(|l| l.legacy_claimed_rewards.contains(&era))
1142			.unwrap_or_default()
1143		{
1144			return false
1145		}
1146
1147		ClaimedRewards::<T>::get(era, validator).len() < page_count as usize
1148	}
1149
1150	/// Temporary function which looks at both (1) passed param `T::StakingLedger` for legacy
1151	/// non-paged rewards, and (2) `T::ClaimedRewards` for paged rewards. This function can be
1152	/// removed once `T::HistoryDepth` eras have passed and none of the older non-paged rewards
1153	/// are relevant/claimable.
1154	// Refer tracker issue for cleanup: https://github.com/paritytech/polkadot-sdk/issues/433
1155	pub(crate) fn is_rewards_claimed_with_legacy_fallback(
1156		era: EraIndex,
1157		ledger: &StakingLedger<T>,
1158		validator: &T::AccountId,
1159		page: Page,
1160	) -> bool {
1161		ledger.legacy_claimed_rewards.binary_search(&era).is_ok() ||
1162			Self::is_rewards_claimed(era, validator, page)
1163	}
1164
1165	/// Check if the rewards for the given era and page index have been claimed.
1166	///
1167	/// This is only used for paged rewards. Once older non-paged rewards are no longer
1168	/// relevant, `is_rewards_claimed_with_legacy_fallback` can be removed and this function can
1169	/// be made public.
1170	fn is_rewards_claimed(era: EraIndex, validator: &T::AccountId, page: Page) -> bool {
1171		ClaimedRewards::<T>::get(era, validator).contains(&page)
1172	}
1173
1174	/// Get exposure for a validator at a given era and page.
1175	///
1176	/// This builds a paged exposure from `PagedExposureMetadata` and `ExposurePage` of the
1177	/// validator. For older non-paged exposure, it returns the clipped exposure directly.
1178	pub fn get_paged_exposure(
1179		era: EraIndex,
1180		validator: &T::AccountId,
1181		page: Page,
1182	) -> Option<PagedExposure<T::AccountId, BalanceOf<T>>> {
1183		let overview = <ErasStakersOverview<T>>::get(&era, validator);
1184
1185		// return clipped exposure if page zero and paged exposure does not exist
1186		// exists for backward compatibility and can be removed as part of #13034
1187		if overview.is_none() && page == 0 {
1188			return Some(PagedExposure::from_clipped(<ErasStakersClipped<T>>::get(era, validator)))
1189		}
1190
1191		// no exposure for this validator
1192		if overview.is_none() {
1193			return None
1194		}
1195
1196		let overview = overview.expect("checked above; qed");
1197
1198		// validator stake is added only in page zero
1199		let validator_stake = if page == 0 { overview.own } else { Zero::zero() };
1200
1201		// since overview is present, paged exposure will always be present except when a
1202		// validator has only own stake and no nominator stake.
1203		let exposure_page = <ErasStakersPaged<T>>::get((era, validator, page)).unwrap_or_default();
1204
1205		// build the exposure
1206		Some(PagedExposure {
1207			exposure_metadata: PagedExposureMetadata { own: validator_stake, ..overview },
1208			exposure_page,
1209		})
1210	}
1211
1212	/// Get full exposure of the validator at a given era.
1213	pub fn get_full_exposure(
1214		era: EraIndex,
1215		validator: &T::AccountId,
1216	) -> Exposure<T::AccountId, BalanceOf<T>> {
1217		let overview = <ErasStakersOverview<T>>::get(&era, validator);
1218
1219		if overview.is_none() {
1220			return ErasStakers::<T>::get(era, validator)
1221		}
1222
1223		let overview = overview.expect("checked above; qed");
1224
1225		let mut others = Vec::with_capacity(overview.nominator_count as usize);
1226		for page in 0..overview.page_count {
1227			let nominators = <ErasStakersPaged<T>>::get((era, validator, page));
1228			others.append(&mut nominators.map(|n| n.others).defensive_unwrap_or_default());
1229		}
1230
1231		Exposure { total: overview.total, own: overview.own, others }
1232	}
1233
1234	/// Returns the number of pages of exposure a validator has for the given era.
1235	///
1236	/// For eras where paged exposure does not exist, this returns 1 to keep backward compatibility.
1237	pub(crate) fn get_page_count(era: EraIndex, validator: &T::AccountId) -> Page {
1238		<ErasStakersOverview<T>>::get(&era, validator)
1239			.map(|overview| {
1240				if overview.page_count == 0 && overview.own > Zero::zero() {
1241					// Even though there are no nominator pages, there is still validator's own
1242					// stake exposed which needs to be paid out in a page.
1243					1
1244				} else {
1245					overview.page_count
1246				}
1247			})
1248			// Always returns 1 page for older non-paged exposure.
1249			// FIXME: Can be cleaned up with issue #13034.
1250			.unwrap_or(1)
1251	}
1252
1253	/// Returns the next page that can be claimed or `None` if nothing to claim.
1254	pub(crate) fn get_next_claimable_page(
1255		era: EraIndex,
1256		validator: &T::AccountId,
1257		ledger: &StakingLedger<T>,
1258	) -> Option<Page> {
1259		if Self::is_non_paged_exposure(era, validator) {
1260			return match ledger.legacy_claimed_rewards.binary_search(&era) {
1261				// already claimed
1262				Ok(_) => None,
1263				// Non-paged exposure is considered as a single page
1264				Err(_) => Some(0),
1265			}
1266		}
1267
1268		// Find next claimable page of paged exposure.
1269		let page_count = Self::get_page_count(era, validator);
1270		let all_claimable_pages: Vec<Page> = (0..page_count).collect();
1271		let claimed_pages = ClaimedRewards::<T>::get(era, validator);
1272
1273		all_claimable_pages.into_iter().find(|p| !claimed_pages.contains(p))
1274	}
1275
1276	/// Checks if exposure is paged or not.
1277	fn is_non_paged_exposure(era: EraIndex, validator: &T::AccountId) -> bool {
1278		<ErasStakersClipped<T>>::contains_key(&era, validator)
1279	}
1280
1281	/// Returns validator commission for this era and page.
1282	pub(crate) fn get_validator_commission(
1283		era: EraIndex,
1284		validator_stash: &T::AccountId,
1285	) -> Perbill {
1286		<ErasValidatorPrefs<T>>::get(&era, validator_stash).commission
1287	}
1288
1289	/// Creates an entry to track validator reward has been claimed for a given era and page.
1290	/// Noop if already claimed.
1291	pub(crate) fn set_rewards_as_claimed(era: EraIndex, validator: &T::AccountId, page: Page) {
1292		let mut claimed_pages = ClaimedRewards::<T>::get(era, validator);
1293
1294		// this should never be called if the reward has already been claimed
1295		if claimed_pages.contains(&page) {
1296			defensive!("Trying to set an already claimed reward");
1297			// nevertheless don't do anything since the page already exist in claimed rewards.
1298			return
1299		}
1300
1301		// add page to claimed entries
1302		claimed_pages.push(page);
1303		ClaimedRewards::<T>::insert(era, validator, claimed_pages);
1304	}
1305
1306	/// Store exposure for elected validators at start of an era.
1307	pub fn set_exposure(
1308		era: EraIndex,
1309		validator: &T::AccountId,
1310		exposure: Exposure<T::AccountId, BalanceOf<T>>,
1311	) {
1312		let page_size = T::MaxExposurePageSize::get().defensive_max(1);
1313
1314		let nominator_count = exposure.others.len();
1315		// expected page count is the number of nominators divided by the page size, rounded up.
1316		let expected_page_count = nominator_count
1317			.defensive_saturating_add((page_size as usize).defensive_saturating_sub(1))
1318			.saturating_div(page_size as usize);
1319
1320		let (exposure_metadata, exposure_pages) = exposure.into_pages(page_size);
1321		defensive_assert!(exposure_pages.len() == expected_page_count, "unexpected page count");
1322
1323		<ErasStakersOverview<T>>::insert(era, &validator, &exposure_metadata);
1324		exposure_pages.iter().enumerate().for_each(|(page, paged_exposure)| {
1325			<ErasStakersPaged<T>>::insert((era, &validator, page as Page), &paged_exposure);
1326		});
1327	}
1328
1329	/// Store total exposure for all the elected validators in the era.
1330	pub(crate) fn set_total_stake(era: EraIndex, total_stake: BalanceOf<T>) {
1331		<ErasTotalStake<T>>::insert(era, total_stake);
1332	}
1333}
1334
1335/// A utility struct that provides a way to check if a given account is a staker.
1336///
1337/// This struct implements the `Contains` trait, allowing it to determine whether
1338/// a particular account is currently staking by checking if the account exists in
1339/// the staking ledger.
1340pub struct AllStakers<T: Config>(core::marker::PhantomData<T>);
1341
1342impl<T: Config> Contains<T::AccountId> for AllStakers<T> {
1343	/// Checks if the given account ID corresponds to a staker.
1344	///
1345	/// # Returns
1346	/// - `true` if the account has an entry in the staking ledger (indicating it is staking).
1347	/// - `false` otherwise.
1348	fn contains(account: &T::AccountId) -> bool {
1349		Ledger::<T>::contains_key(account)
1350	}
1351}
1352
1353/// Configurations of the benchmarking of the pallet.
1354pub trait BenchmarkingConfig {
1355	/// The maximum number of validators to use.
1356	type MaxValidators: Get<u32>;
1357	/// The maximum number of nominators to use.
1358	type MaxNominators: Get<u32>;
1359}
1360
1361/// A mock benchmarking config for pallet-staking.
1362///
1363/// Should only be used for testing.
1364#[cfg(feature = "std")]
1365pub struct TestBenchmarkingConfig;
1366
1367#[cfg(feature = "std")]
1368impl BenchmarkingConfig for TestBenchmarkingConfig {
1369	type MaxValidators = frame_support::traits::ConstU32<100>;
1370	type MaxNominators = frame_support::traits::ConstU32<100>;
1371}