referrerpolicy=no-referrer-when-downgrade

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//! use frame_support::traits::RewardsReporter;
164//!
165//! #[frame_support::pallet(dev_mode)]
166//! pub mod pallet {
167//!   use super::*;
168//!   use frame_support::pallet_prelude::*;
169//!   use frame_system::pallet_prelude::*;
170//!   # use frame_support::traits::RewardsReporter;
171//!
172//!   #[pallet::pallet]
173//!   pub struct Pallet<T>(_);
174//!
175//!   #[pallet::config]
176//!   pub trait Config: frame_system::Config + staking::Config {}
177//!
178//!   #[pallet::call]
179//!   impl<T: Config> Pallet<T> {
180//!         /// Reward a validator.
181//!         #[pallet::weight(0)]
182//!         pub fn reward_myself(origin: OriginFor<T>) -> DispatchResult {
183//!             let reported = ensure_signed(origin)?;
184//!             <staking::Pallet<T>>::reward_by_ids(vec![(reported, 10)]);
185//!             Ok(())
186//!         }
187//!     }
188//! }
189//! # fn main() { }
190//! ```
191//!
192//! ## Implementation Details
193//!
194//! ### Era payout
195//!
196//! The era payout is computed using yearly inflation curve defined at [`Config::EraPayout`] as
197//! such:
198//!
199//! ```nocompile
200//! staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year
201//! ```
202//! This payout is used to reward stakers as defined in next section
203//!
204//! ```nocompile
205//! remaining_payout = max_yearly_inflation * total_tokens / era_per_year - staker_payout
206//! ```
207//!
208//! Note, however, that it is possible to set a cap on the total `staker_payout` for the era through
209//! the `MaxStakersRewards` storage type. The `era_payout` implementor must ensure that the
210//! `max_payout = remaining_payout + (staker_payout * max_stakers_rewards)`. The excess payout that
211//! is not allocated for stakers is the era remaining reward.
212//!
213//! The remaining reward is send to the configurable end-point [`Config::RewardRemainder`].
214//!
215//! ### Reward Calculation
216//!
217//! Validators and nominators are rewarded at the end of each era. The total reward of an era is
218//! calculated using the era duration and the staking rate (the total amount of tokens staked by
219//! nominators and validators, divided by the total token supply). It aims to incentivize toward a
220//! defined staking rate. The full specification can be found
221//! [here](https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model).
222//!
223//! Total reward is split among validators and their nominators depending on the number of points
224//! they received during the era. Points are added to a validator using the method
225//! [`frame_support::traits::RewardsReporter::reward_by_ids`] implemented by the [`Pallet`].
226//!
227//! [`Pallet`] implements [`pallet_authorship::EventHandler`] to add reward points to block producer
228//! and block producer of referenced uncles.
229//!
230//! The validator and its nominator split their reward as following:
231//!
232//! The validator can declare an amount, named [`commission`](ValidatorPrefs::commission), that does
233//! not get shared with the nominators at each reward payout through its [`ValidatorPrefs`]. This
234//! value gets deducted from the total reward that is paid to the validator and its nominators. The
235//! remaining portion is split pro rata among the validator and the nominators that nominated the
236//! validator, proportional to the value staked behind the validator (_i.e._ dividing the
237//! [`own`](Exposure::own) or [`others`](Exposure::others) by [`total`](Exposure::total) in
238//! [`Exposure`]). Note that payouts are made in pages with each page capped at
239//! [`Config::MaxExposurePageSize`] nominators. The distribution of nominators across pages may be
240//! unsorted. The total commission is paid out proportionally across pages based on the total stake
241//! of the page.
242//!
243//! All entities who receive a reward have the option to choose their reward destination through the
244//! [`Payee`] storage item (see [`set_payee`](Call::set_payee)), to be one of the following:
245//!
246//! - Stash account, not increasing the staked value.
247//! - Stash account, also increasing the staked value.
248//! - Any other account, sent as free balance.
249//!
250//! ### Additional Fund Management Operations
251//!
252//! Any funds already placed into stash can be the target of the following operations:
253//!
254//! The controller account can free a portion (or all) of the funds using the
255//! [`unbond`](Call::unbond) call. Note that the funds are not immediately accessible. Instead, a
256//! duration denoted by [`Config::BondingDuration`] (in number of eras) must pass until the funds
257//! can actually be removed. Once the `BondingDuration` is over, the
258//! [`withdraw_unbonded`](Call::withdraw_unbonded) call can be used to actually withdraw the funds.
259//!
260//! Note that there is a limitation to the number of fund-chunks that can be scheduled to be
261//! unlocked in the future via [`unbond`](Call::unbond). In case this maximum
262//! (`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful
263//! call to `withdraw_unbonded` to remove some of the chunks.
264//!
265//! ### Election Algorithm
266//!
267//! The current election algorithm is implemented based on Phragmén. The reference implementation
268//! can be found [here](https://github.com/w3f/consensus/tree/master/NPoS).
269//!
270//! The election algorithm, aside from electing the validators with the most stake value and votes,
271//! tries to divide the nominator votes among candidates in an equal manner. To further assure this,
272//! an optional post-processing can be applied that iteratively normalizes the nominator staked
273//! values until the total difference among votes of a particular nominator are less than a
274//! threshold.
275//!
276//! ## GenesisConfig
277//!
278//! The Staking pallet depends on the [`GenesisConfig`]. The `GenesisConfig` is optional and allow
279//! to set some initial stakers.
280//!
281//! ## Related Modules
282//!
283//! - [Balances](../pallet_balances/index.html): Used to manage values at stake.
284//! - [Session](../pallet_session/index.html): Used to manage sessions. Also, a list of new
285//!   validators is stored in the Session pallet's `Validators` at the end of each era.
286
287#![cfg_attr(not(feature = "std"), no_std)]
288#![recursion_limit = "256"]
289
290#[cfg(feature = "runtime-benchmarks")]
291pub mod benchmarking;
292#[cfg(any(feature = "runtime-benchmarks", test))]
293pub mod testing_utils;
294
295#[cfg(test)]
296pub(crate) mod mock;
297#[cfg(test)]
298mod tests;
299
300pub mod asset;
301pub mod election_size_tracker;
302pub mod inflation;
303pub mod ledger;
304pub mod migrations;
305pub mod slashing;
306pub mod weights;
307
308mod pallet;
309
310extern crate alloc;
311
312use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec};
313use codec::{Decode, DecodeWithMemTracking, Encode, HasCompact, MaxEncodedLen};
314use frame_election_provider_support::ElectionProvider;
315use frame_support::{
316	defensive, defensive_assert,
317	traits::{
318		tokens::fungible::{Credit, Debt},
319		ConstU32, Contains, Defensive, DefensiveMax, DefensiveSaturating, Get, LockIdentifier,
320	},
321	weights::Weight,
322	BoundedVec, CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound,
323};
324use scale_info::TypeInfo;
325use sp_runtime::{
326	curve::PiecewiseLinear,
327	traits::{AtLeast32BitUnsigned, Convert, StaticLookup, Zero},
328	Debug, Perbill, Perquintill, Rounding, Saturating,
329};
330use sp_staking::{
331	offence::{Offence, OffenceError, OffenceSeverity, ReportOffence},
332	EraIndex, ExposurePage, OnStakingUpdate, Page, PagedExposureMetadata, SessionIndex,
333};
334pub use sp_staking::{Exposure, IndividualExposure, StakerStatus};
335pub use weights::WeightInfo;
336
337pub use pallet::{pallet::*, UseNominatorsAndValidatorsMap, UseValidatorsMap};
338
339pub(crate) const STAKING_ID: LockIdentifier = *b"staking ";
340pub(crate) const LOG_TARGET: &str = "runtime::staking";
341
342// syntactic sugar for logging.
343#[macro_export]
344macro_rules! log {
345	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
346		log::$level!(
347			target: crate::LOG_TARGET,
348			concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
349		)
350	};
351}
352
353/// Alias for the maximum number of winners (aka. active validators), as defined in by this pallet's
354/// config.
355pub type MaxWinnersOf<T> = <T as Config>::MaxValidatorSet;
356
357/// Alias for the maximum number of winners per page, as expected by the election provider.
358pub type MaxWinnersPerPageOf<P> = <P as ElectionProvider>::MaxWinnersPerPage;
359
360/// Maximum number of nominations per nominator.
361pub type MaxNominationsOf<T> =
362	<<T as Config>::NominationsQuota as NominationsQuota<BalanceOf<T>>>::MaxNominations;
363
364/// Counter for the number of "reward" points earned by a given validator.
365pub type RewardPoint = u32;
366
367/// The balance type of this pallet.
368pub type BalanceOf<T> = <T as Config>::CurrencyBalance;
369
370type PositiveImbalanceOf<T> = Debt<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
371pub type NegativeImbalanceOf<T> =
372	Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
373
374type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
375
376/// Information regarding the active era (era in used in session).
377#[derive(
378	Encode, Decode, DecodeWithMemTracking, Clone, Debug, TypeInfo, MaxEncodedLen, PartialEq, Eq,
379)]
380pub struct ActiveEraInfo {
381	/// Index of era.
382	pub index: EraIndex,
383	/// Moment of start expressed as millisecond from `$UNIX_EPOCH`.
384	///
385	/// Start can be none if start hasn't been set for the era yet,
386	/// Start is set on the first on_finalize of the era to guarantee usage of `Time`.
387	pub start: Option<u64>,
388}
389
390/// Reward points of an era. Used to split era total payout between validators.
391///
392/// This points will be used to reward validators and their respective nominators.
393#[derive(Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo, Clone, PartialEq, Eq)]
394pub struct EraRewardPoints<AccountId: Ord> {
395	/// Total number of points. Equals the sum of reward points for each validator.
396	pub total: RewardPoint,
397	/// The reward points earned by a given validator.
398	pub individual: BTreeMap<AccountId, RewardPoint>,
399}
400
401impl<AccountId: Ord> Default for EraRewardPoints<AccountId> {
402	fn default() -> Self {
403		EraRewardPoints { total: Default::default(), individual: BTreeMap::new() }
404	}
405}
406
407/// A destination account for payment.
408#[derive(
409	PartialEq,
410	Eq,
411	Copy,
412	Clone,
413	Encode,
414	Decode,
415	DecodeWithMemTracking,
416	Debug,
417	TypeInfo,
418	MaxEncodedLen,
419)]
420pub enum RewardDestination<AccountId> {
421	/// Pay into the stash account, increasing the amount at stake accordingly.
422	Staked,
423	/// Pay into the stash account, not increasing the amount at stake.
424	Stash,
425	#[deprecated(
426		note = "`Controller` will be removed after January 2024. Use `Account(controller)` instead."
427	)]
428	Controller,
429	/// Pay into a specified account.
430	Account(AccountId),
431	/// Receive no reward.
432	None,
433}
434
435/// Preference of what happens regarding validation.
436#[derive(
437	PartialEq,
438	Eq,
439	Clone,
440	Encode,
441	Decode,
442	DecodeWithMemTracking,
443	Debug,
444	TypeInfo,
445	Default,
446	MaxEncodedLen,
447)]
448pub struct ValidatorPrefs {
449	/// Reward that validator takes up-front; only the rest is split between themselves and
450	/// nominators.
451	#[codec(compact)]
452	pub commission: Perbill,
453	/// Whether or not this validator is accepting more nominations. If `true`, then no nominator
454	/// who is not already nominating this validator may nominate them. By default, validators
455	/// are accepting nominations.
456	pub blocked: bool,
457}
458
459/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.
460#[derive(
461	PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo, MaxEncodedLen,
462)]
463pub struct UnlockChunk<Balance: HasCompact + MaxEncodedLen> {
464	/// Amount of funds to be unlocked.
465	#[codec(compact)]
466	pub value: Balance,
467	/// Era number at which point it'll be unlocked.
468	#[codec(compact)]
469	pub era: EraIndex,
470}
471
472/// The ledger of a (bonded) stash.
473///
474/// Note: All the reads and mutations to the [`Ledger`], [`Bonded`] and [`Payee`] storage items
475/// *MUST* be performed through the methods exposed by this struct, to ensure the consistency of
476/// ledger's data and corresponding staking lock
477///
478/// TODO: move struct definition and full implementation into `/src/ledger.rs`. Currently
479/// leaving here to enforce a clean PR diff, given how critical this logic is. Tracking issue
480/// <https://github.com/paritytech/substrate/issues/14749>.
481#[derive(
482	PartialEqNoBound,
483	EqNoBound,
484	CloneNoBound,
485	Encode,
486	Decode,
487	DecodeWithMemTracking,
488	DebugNoBound,
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 [`Self::controller()`] function to get the controller associated with the ledger.
523	#[codec(skip)]
524	pub 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,
798	EqNoBound,
799	Clone,
800	Encode,
801	Decode,
802	DecodeWithMemTracking,
803	DebugNoBound,
804	TypeInfo,
805	MaxEncodedLen,
806)]
807#[codec(mel_bound())]
808#[scale_info(skip_type_params(T))]
809pub struct Nominations<T: Config> {
810	/// The targets of nomination.
811	pub targets: BoundedVec<T::AccountId, MaxNominationsOf<T>>,
812	/// The era the nominations were submitted.
813	///
814	/// Except for initial nominations which are considered submitted at era 0.
815	pub submitted_in: EraIndex,
816	/// Whether the nominations have been suppressed. This can happen due to slashing of the
817	/// validators, or other events that might invalidate the nomination.
818	///
819	/// NOTE: this for future proofing and is thus far not used.
820	pub suppressed: bool,
821}
822
823/// Facade struct to encapsulate `PagedExposureMetadata` and a single page of `ExposurePage`.
824///
825/// This is useful where we need to take into account the validator's own stake and total exposure
826/// in consideration, in addition to the individual nominators backing them.
827#[derive(Encode, Decode, Debug, TypeInfo, PartialEq, Eq)]
828pub struct PagedExposure<AccountId, Balance: HasCompact + codec::MaxEncodedLen> {
829	exposure_metadata: PagedExposureMetadata<Balance>,
830	exposure_page: ExposurePage<AccountId, Balance>,
831}
832
833impl<AccountId, Balance: HasCompact + Copy + AtLeast32BitUnsigned + codec::MaxEncodedLen>
834	PagedExposure<AccountId, Balance>
835{
836	/// Create a new instance of `PagedExposure` from legacy clipped exposures.
837	pub fn from_clipped(exposure: Exposure<AccountId, Balance>) -> Self {
838		Self {
839			exposure_metadata: PagedExposureMetadata {
840				total: exposure.total,
841				own: exposure.own,
842				nominator_count: exposure.others.len() as u32,
843				page_count: 1,
844			},
845			exposure_page: ExposurePage { page_total: exposure.total, others: exposure.others },
846		}
847	}
848
849	/// Returns total exposure of this validator across pages
850	pub fn total(&self) -> Balance {
851		self.exposure_metadata.total
852	}
853
854	/// Returns total exposure of this validator for the current page
855	pub fn page_total(&self) -> Balance {
856		self.exposure_page.page_total + self.exposure_metadata.own
857	}
858
859	/// Returns validator's own stake that is exposed
860	pub fn own(&self) -> Balance {
861		self.exposure_metadata.own
862	}
863
864	/// Returns the portions of nominators stashes that are exposed in this page.
865	pub fn others(&self) -> &Vec<IndividualExposure<AccountId, Balance>> {
866		&self.exposure_page.others
867	}
868}
869
870/// A pending slash record. The value of the slash has been computed but not applied yet,
871/// rather deferred for several eras.
872#[derive(Encode, Decode, Debug, TypeInfo, PartialEq, Eq, Clone, DecodeWithMemTracking)]
873pub struct UnappliedSlash<AccountId, Balance: HasCompact> {
874	/// The stash ID of the offending validator.
875	pub validator: AccountId,
876	/// The validator's own slash.
877	pub own: Balance,
878	/// All other slashed stakers and amounts.
879	pub others: Vec<(AccountId, Balance)>,
880	/// Reporters of the offence; bounty payout recipients.
881	pub reporters: Vec<AccountId>,
882	/// The amount of payout.
883	pub payout: Balance,
884}
885
886impl<AccountId, Balance: HasCompact + Zero> UnappliedSlash<AccountId, Balance> {
887	/// Initializes the default object using the given `validator`.
888	pub fn default_from(validator: AccountId) -> Self {
889		Self {
890			validator,
891			own: Zero::zero(),
892			others: vec![],
893			reporters: vec![],
894			payout: Zero::zero(),
895		}
896	}
897}
898
899/// Something that defines the maximum number of nominations per nominator based on a curve.
900///
901/// The method `curve` implements the nomination quota curve and should not be used directly.
902/// However, `get_quota` returns the bounded maximum number of nominations based on `fn curve` and
903/// the nominator's balance.
904pub trait NominationsQuota<Balance> {
905	/// Strict maximum number of nominations that caps the nominations curve. This value can be
906	/// used as the upper bound of the number of votes per nominator.
907	type MaxNominations: Get<u32>;
908
909	/// Returns the voter's nomination quota within reasonable bounds [`min`, `max`], where `min`
910	/// is 1 and `max` is `Self::MaxNominations`.
911	fn get_quota(balance: Balance) -> u32 {
912		Self::curve(balance).clamp(1, Self::MaxNominations::get())
913	}
914
915	/// Returns the voter's nomination quota based on its balance and a curve.
916	fn curve(balance: Balance) -> u32;
917}
918
919/// A nomination quota that allows up to MAX nominations for all validators.
920pub struct FixedNominationsQuota<const MAX: u32>;
921impl<Balance, const MAX: u32> NominationsQuota<Balance> for FixedNominationsQuota<MAX> {
922	type MaxNominations = ConstU32<MAX>;
923
924	fn curve(_: Balance) -> u32 {
925		MAX
926	}
927}
928
929/// Means for interacting with a specialized version of the `session` trait.
930///
931/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Config`
932pub trait SessionInterface<AccountId> {
933	/// Report an offending validator.
934	fn report_offence(validator: AccountId, severity: OffenceSeverity);
935	/// Get the validators from session.
936	fn validators() -> Vec<AccountId>;
937	/// Prune historical session tries up to but not including the given index.
938	fn prune_historical_up_to(up_to: SessionIndex);
939}
940
941impl<T: Config> SessionInterface<<T as frame_system::Config>::AccountId> for T
942where
943	T: pallet_session::Config<ValidatorId = <T as frame_system::Config>::AccountId>,
944	T: pallet_session::historical::Config,
945	T::SessionHandler: pallet_session::SessionHandler<<T as frame_system::Config>::AccountId>,
946	T::SessionManager: pallet_session::SessionManager<<T as frame_system::Config>::AccountId>,
947	T::ValidatorIdOf: Convert<
948		<T as frame_system::Config>::AccountId,
949		Option<<T as frame_system::Config>::AccountId>,
950	>,
951{
952	fn report_offence(
953		validator: <T as frame_system::Config>::AccountId,
954		severity: OffenceSeverity,
955	) {
956		<pallet_session::Pallet<T>>::report_offence(validator, severity)
957	}
958
959	fn validators() -> Vec<<T as frame_system::Config>::AccountId> {
960		<pallet_session::Pallet<T>>::validators()
961	}
962
963	fn prune_historical_up_to(up_to: SessionIndex) {
964		<pallet_session::historical::Pallet<T>>::prune_up_to(up_to);
965	}
966}
967
968impl<AccountId> SessionInterface<AccountId> for () {
969	fn report_offence(_validator: AccountId, _severity: OffenceSeverity) {
970		()
971	}
972	fn validators() -> Vec<AccountId> {
973		Vec::new()
974	}
975	fn prune_historical_up_to(_: SessionIndex) {
976		()
977	}
978}
979
980/// Handler for determining how much of a balance should be paid out on the current era.
981pub trait EraPayout<Balance> {
982	/// Determine the payout for this era.
983	///
984	/// Returns the amount to be paid to stakers in this era, as well as whatever else should be
985	/// paid out ("the rest").
986	fn era_payout(
987		total_staked: Balance,
988		total_issuance: Balance,
989		era_duration_millis: u64,
990	) -> (Balance, Balance);
991}
992
993impl<Balance: Default> EraPayout<Balance> for () {
994	fn era_payout(
995		_total_staked: Balance,
996		_total_issuance: Balance,
997		_era_duration_millis: u64,
998	) -> (Balance, Balance) {
999		(Default::default(), Default::default())
1000	}
1001}
1002
1003/// Adaptor to turn a `PiecewiseLinear` curve definition into an `EraPayout` impl, used for
1004/// backwards compatibility.
1005pub struct ConvertCurve<T>(core::marker::PhantomData<T>);
1006impl<Balance, T> EraPayout<Balance> for ConvertCurve<T>
1007where
1008	Balance: AtLeast32BitUnsigned + Clone + Copy,
1009	T: Get<&'static PiecewiseLinear<'static>>,
1010{
1011	fn era_payout(
1012		total_staked: Balance,
1013		total_issuance: Balance,
1014		era_duration_millis: u64,
1015	) -> (Balance, Balance) {
1016		let (validator_payout, max_payout) = inflation::compute_total_payout(
1017			T::get(),
1018			total_staked,
1019			total_issuance,
1020			// Duration of era; more than u64::MAX is rewarded as u64::MAX.
1021			era_duration_millis,
1022		);
1023		let rest = max_payout.saturating_sub(validator_payout);
1024		(validator_payout, rest)
1025	}
1026}
1027
1028/// Mode of era-forcing.
1029#[derive(
1030	Copy,
1031	Clone,
1032	PartialEq,
1033	Eq,
1034	Encode,
1035	Decode,
1036	DecodeWithMemTracking,
1037	Debug,
1038	TypeInfo,
1039	MaxEncodedLen,
1040	serde::Serialize,
1041	serde::Deserialize,
1042)]
1043pub enum Forcing {
1044	/// Not forcing anything - just let whatever happen.
1045	NotForcing,
1046	/// Force a new era, then reset to `NotForcing` as soon as it is done.
1047	/// Note that this will force to trigger an election until a new era is triggered, if the
1048	/// election failed, the next session end will trigger a new election again, until success.
1049	ForceNew,
1050	/// Avoid a new era indefinitely.
1051	ForceNone,
1052	/// Force a new era at the end of all sessions indefinitely.
1053	ForceAlways,
1054}
1055
1056impl Default for Forcing {
1057	fn default() -> Self {
1058		Forcing::NotForcing
1059	}
1060}
1061
1062/// A typed conversion from stash account ID to the active exposure of nominators
1063/// on that account.
1064///
1065/// Active exposure is the exposure of the validator set currently validating, i.e. in
1066/// `active_era`. It can differ from the latest planned exposure in `current_era`.
1067#[deprecated(note = "Use `DefaultExposureOf` instead")]
1068pub struct ExposureOf<T>(core::marker::PhantomData<T>);
1069
1070#[allow(deprecated)]
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
1080/// Identify a validator with their default exposure.
1081///
1082/// This type should not be used in a fresh runtime, instead use [`UnitIdentificationOf`].
1083///
1084/// In the past, a type called [`ExposureOf`] used to return the full exposure of a validator to
1085/// identify their exposure. This type is kept, marked as deprecated, for backwards compatibility of
1086/// external SDK users, but is no longer used in this repo.
1087///
1088/// In the new model, we don't need to identify a validator with their full exposure anymore, and
1089/// therefore [`UnitIdentificationOf`] is perfectly fine. Yet, for runtimes that used to work with
1090/// [`ExposureOf`], we need to be able to decode old identification data, possibly stored in the
1091/// historical session pallet in older blocks. Therefore, this type is a good compromise, allowing
1092/// old exposure identifications to be decoded, and returning a few zero bytes
1093/// (`Exposure::default`) for any new identification request.
1094///
1095/// A typical usage of this type is:
1096///
1097/// ```ignore
1098/// impl pallet_session::historical::Config for Runtime {
1099///     type FullIdentification = sp_staking::Exposure<AccountId, Balance>;
1100///     type IdentificationOf = pallet_staking::DefaultExposureOf<Self>
1101/// }
1102/// ```
1103pub struct DefaultExposureOf<T>(core::marker::PhantomData<T>);
1104
1105impl<T: Config> Convert<T::AccountId, Option<Exposure<T::AccountId, BalanceOf<T>>>>
1106	for DefaultExposureOf<T>
1107{
1108	fn convert(validator: T::AccountId) -> Option<Exposure<T::AccountId, BalanceOf<T>>> {
1109		T::SessionInterface::validators()
1110			.contains(&validator)
1111			.then_some(Default::default())
1112	}
1113}
1114
1115/// An identification type that signifies the existence of a validator by returning `Some(())`, and
1116/// `None` otherwise. Also see the documentation of [`DefaultExposureOf`] for more info.
1117///
1118/// ```ignore
1119/// impl pallet_session::historical::Config for Runtime {
1120///     type FullIdentification = ();
1121///     type IdentificationOf = pallet_staking::UnitIdentificationOf<Self>
1122/// }
1123/// ```
1124pub struct UnitIdentificationOf<T>(core::marker::PhantomData<T>);
1125impl<T: Config> Convert<T::AccountId, Option<()>> for UnitIdentificationOf<T> {
1126	fn convert(validator: T::AccountId) -> Option<()> {
1127		DefaultExposureOf::<T>::convert(validator).map(|_default_exposure| ())
1128	}
1129}
1130
1131/// Filter historical offences out and only allow those from the bonding period.
1132pub struct FilterHistoricalOffences<T, R> {
1133	_inner: core::marker::PhantomData<(T, R)>,
1134}
1135
1136impl<T, Reporter, Offender, R, O> ReportOffence<Reporter, Offender, O>
1137	for FilterHistoricalOffences<Pallet<T>, R>
1138where
1139	T: Config,
1140	R: ReportOffence<Reporter, Offender, O>,
1141	O: Offence<Offender>,
1142{
1143	fn report_offence(reporters: Vec<Reporter>, offence: O) -> Result<(), OffenceError> {
1144		// Disallow any slashing from before the current bonding period.
1145		let offence_session = offence.session_index();
1146		let bonded_eras = BondedEras::<T>::get();
1147
1148		if bonded_eras.first().filter(|(_, start)| offence_session >= *start).is_some() {
1149			R::report_offence(reporters, offence)
1150		} else {
1151			<Pallet<T>>::deposit_event(Event::<T>::OldSlashingReportDiscarded {
1152				session_index: offence_session,
1153			});
1154			Ok(())
1155		}
1156	}
1157
1158	fn is_known_offence(offenders: &[Offender], time_slot: &O::TimeSlot) -> bool {
1159		R::is_known_offence(offenders, time_slot)
1160	}
1161}
1162
1163/// Wrapper struct for Era-related information. It is not a pure encapsulation as these storage
1164/// items can be accessed directly but nevertheless, its recommended to use `EraInfo` where we
1165/// can and add more functions to it as needed.
1166pub struct EraInfo<T>(core::marker::PhantomData<T>);
1167impl<T: Config> EraInfo<T> {
1168	/// Returns true if validator has one or more page of era rewards not claimed yet.
1169	// Also looks at legacy storage that can be cleaned up after #433.
1170	pub fn pending_rewards(era: EraIndex, validator: &T::AccountId) -> bool {
1171		let page_count = if let Some(overview) = <ErasStakersOverview<T>>::get(&era, validator) {
1172			overview.page_count
1173		} else {
1174			if <ErasStakers<T>>::contains_key(era, validator) {
1175				// this means non paged exposure, and we treat them as single paged.
1176				1
1177			} else {
1178				// if no exposure, then no rewards to claim.
1179				return false
1180			}
1181		};
1182
1183		// check if era is marked claimed in legacy storage.
1184		if <Ledger<T>>::get(validator)
1185			.map(|l| l.legacy_claimed_rewards.contains(&era))
1186			.unwrap_or_default()
1187		{
1188			return false
1189		}
1190
1191		ClaimedRewards::<T>::get(era, validator).len() < page_count as usize
1192	}
1193
1194	/// Temporary function which looks at both (1) passed param `T::StakingLedger` for legacy
1195	/// non-paged rewards, and (2) `T::ClaimedRewards` for paged rewards. This function can be
1196	/// removed once `T::HistoryDepth` eras have passed and none of the older non-paged rewards
1197	/// are relevant/claimable.
1198	// Refer tracker issue for cleanup: https://github.com/paritytech/polkadot-sdk/issues/433
1199	pub(crate) fn is_rewards_claimed_with_legacy_fallback(
1200		era: EraIndex,
1201		ledger: &StakingLedger<T>,
1202		validator: &T::AccountId,
1203		page: Page,
1204	) -> bool {
1205		ledger.legacy_claimed_rewards.binary_search(&era).is_ok() ||
1206			Self::is_rewards_claimed(era, validator, page)
1207	}
1208
1209	/// Check if the rewards for the given era and page index have been claimed.
1210	///
1211	/// This is only used for paged rewards. Once older non-paged rewards are no longer
1212	/// relevant, `is_rewards_claimed_with_legacy_fallback` can be removed and this function can
1213	/// be made public.
1214	fn is_rewards_claimed(era: EraIndex, validator: &T::AccountId, page: Page) -> bool {
1215		ClaimedRewards::<T>::get(era, validator).contains(&page)
1216	}
1217
1218	/// Get exposure for a validator at a given era and page.
1219	///
1220	/// This builds a paged exposure from `PagedExposureMetadata` and `ExposurePage` of the
1221	/// validator. For older non-paged exposure, it returns the clipped exposure directly.
1222	pub fn get_paged_exposure(
1223		era: EraIndex,
1224		validator: &T::AccountId,
1225		page: Page,
1226	) -> Option<PagedExposure<T::AccountId, BalanceOf<T>>> {
1227		let overview = <ErasStakersOverview<T>>::get(&era, validator);
1228
1229		// return clipped exposure if page zero and paged exposure does not exist
1230		// exists for backward compatibility and can be removed as part of #13034
1231		if overview.is_none() && page == 0 {
1232			return Some(PagedExposure::from_clipped(<ErasStakersClipped<T>>::get(era, validator)))
1233		}
1234
1235		// no exposure for this validator
1236		if overview.is_none() {
1237			return None
1238		}
1239
1240		let overview = overview.expect("checked above; qed");
1241
1242		// validator stake is added only in page zero
1243		let validator_stake = if page == 0 { overview.own } else { Zero::zero() };
1244
1245		// since overview is present, paged exposure will always be present except when a
1246		// validator only has its own stake and no nominator stake.
1247		let exposure_page = <ErasStakersPaged<T>>::get((era, validator, page)).unwrap_or_default();
1248
1249		// build the exposure
1250		Some(PagedExposure {
1251			exposure_metadata: PagedExposureMetadata { own: validator_stake, ..overview },
1252			exposure_page,
1253		})
1254	}
1255
1256	/// Get full exposure of the validator at a given era.
1257	pub fn get_full_exposure(
1258		era: EraIndex,
1259		validator: &T::AccountId,
1260	) -> Exposure<T::AccountId, BalanceOf<T>> {
1261		let overview = <ErasStakersOverview<T>>::get(&era, validator);
1262
1263		if overview.is_none() {
1264			return ErasStakers::<T>::get(era, validator)
1265		}
1266
1267		let overview = overview.expect("checked above; qed");
1268
1269		let mut others = Vec::with_capacity(overview.nominator_count as usize);
1270		for page in 0..overview.page_count {
1271			let nominators = <ErasStakersPaged<T>>::get((era, validator, page));
1272			others.append(&mut nominators.map(|n| n.others).defensive_unwrap_or_default());
1273		}
1274
1275		Exposure { total: overview.total, own: overview.own, others }
1276	}
1277
1278	/// Returns the number of pages of exposure a validator has for the given era.
1279	///
1280	/// For eras where paged exposure does not exist, this returns 1 to keep backward compatibility.
1281	pub(crate) fn get_page_count(era: EraIndex, validator: &T::AccountId) -> Page {
1282		<ErasStakersOverview<T>>::get(&era, validator)
1283			.map(|overview| {
1284				if overview.page_count == 0 && overview.own > Zero::zero() {
1285					// Even though there are no nominator pages, there is still validator's own
1286					// stake exposed which needs to be paid out in a page.
1287					1
1288				} else {
1289					overview.page_count
1290				}
1291			})
1292			// Always returns 1 page for older non-paged exposure.
1293			// FIXME: Can be cleaned up with issue #13034.
1294			.unwrap_or(1)
1295	}
1296
1297	/// Returns the next page that can be claimed or `None` if nothing to claim.
1298	pub(crate) fn get_next_claimable_page(
1299		era: EraIndex,
1300		validator: &T::AccountId,
1301		ledger: &StakingLedger<T>,
1302	) -> Option<Page> {
1303		if Self::is_non_paged_exposure(era, validator) {
1304			return match ledger.legacy_claimed_rewards.binary_search(&era) {
1305				// already claimed
1306				Ok(_) => None,
1307				// Non-paged exposure is considered as a single page
1308				Err(_) => Some(0),
1309			}
1310		}
1311
1312		// Find next claimable page of paged exposure.
1313		let page_count = Self::get_page_count(era, validator);
1314		let all_claimable_pages: Vec<Page> = (0..page_count).collect();
1315		let claimed_pages = ClaimedRewards::<T>::get(era, validator);
1316
1317		all_claimable_pages.into_iter().find(|p| !claimed_pages.contains(p))
1318	}
1319
1320	/// Checks if exposure is paged or not.
1321	fn is_non_paged_exposure(era: EraIndex, validator: &T::AccountId) -> bool {
1322		<ErasStakersClipped<T>>::contains_key(&era, validator)
1323	}
1324
1325	/// Returns validator commission for this era and page.
1326	pub(crate) fn get_validator_commission(
1327		era: EraIndex,
1328		validator_stash: &T::AccountId,
1329	) -> Perbill {
1330		<ErasValidatorPrefs<T>>::get(&era, validator_stash).commission
1331	}
1332
1333	/// Creates an entry to track whether validator reward has been claimed for a given era and
1334	/// page. Noop if already claimed.
1335	pub(crate) fn set_rewards_as_claimed(era: EraIndex, validator: &T::AccountId, page: Page) {
1336		let mut claimed_pages = ClaimedRewards::<T>::get(era, validator);
1337
1338		// this should never be called if the reward has already been claimed
1339		if claimed_pages.contains(&page) {
1340			defensive!("Trying to set an already claimed reward");
1341			// nevertheless don't do anything since the page already exists in claimed rewards.
1342			return
1343		}
1344
1345		// add page to claimed entries
1346		claimed_pages.push(page);
1347		ClaimedRewards::<T>::insert(era, validator, claimed_pages);
1348	}
1349
1350	/// Store exposure for elected validators at start of an era.
1351	pub fn set_exposure(
1352		era: EraIndex,
1353		validator: &T::AccountId,
1354		exposure: Exposure<T::AccountId, BalanceOf<T>>,
1355	) {
1356		let page_size = T::MaxExposurePageSize::get().defensive_max(1);
1357
1358		let nominator_count = exposure.others.len();
1359		// expected page count is the number of nominators divided by the page size, rounded up.
1360		let expected_page_count = nominator_count
1361			.defensive_saturating_add((page_size as usize).defensive_saturating_sub(1))
1362			.saturating_div(page_size as usize);
1363
1364		let (exposure_metadata, exposure_pages) = exposure.into_pages(page_size);
1365		defensive_assert!(exposure_pages.len() == expected_page_count, "unexpected page count");
1366
1367		<ErasStakersOverview<T>>::insert(era, &validator, &exposure_metadata);
1368		exposure_pages.iter().enumerate().for_each(|(page, paged_exposure)| {
1369			<ErasStakersPaged<T>>::insert((era, &validator, page as Page), &paged_exposure);
1370		});
1371	}
1372
1373	/// Store total exposure for all the elected validators in the era.
1374	pub(crate) fn set_total_stake(era: EraIndex, total_stake: BalanceOf<T>) {
1375		<ErasTotalStake<T>>::insert(era, total_stake);
1376	}
1377}
1378
1379/// A utility struct that provides a way to check if a given account is a staker.
1380///
1381/// This struct implements the `Contains` trait, allowing it to determine whether
1382/// a particular account is currently staking by checking if the account exists in
1383/// the staking ledger.
1384pub struct AllStakers<T: Config>(core::marker::PhantomData<T>);
1385
1386impl<T: Config> Contains<T::AccountId> for AllStakers<T> {
1387	/// Checks if the given account ID corresponds to a staker.
1388	///
1389	/// # Returns
1390	/// - `true` if the account has an entry in the staking ledger (indicating it is staking).
1391	/// - `false` otherwise.
1392	fn contains(account: &T::AccountId) -> bool {
1393		Ledger::<T>::contains_key(account)
1394	}
1395}
1396
1397/// Configurations of the benchmarking of the pallet.
1398pub trait BenchmarkingConfig {
1399	/// The maximum number of validators to use.
1400	type MaxValidators: Get<u32>;
1401	/// The maximum number of nominators to use.
1402	type MaxNominators: Get<u32>;
1403}
1404
1405/// A mock benchmarking config for pallet-staking.
1406///
1407/// Should only be used for testing.
1408#[cfg(feature = "std")]
1409pub struct TestBenchmarkingConfig;
1410
1411#[cfg(feature = "std")]
1412impl BenchmarkingConfig for TestBenchmarkingConfig {
1413	type MaxValidators = frame_support::traits::ConstU32<100>;
1414	type MaxNominators = frame_support::traits::ConstU32<100>;
1415}