Skip to main content

pallet_staking_async/pallet/
mod.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//! `pallet-staking-async`'s main `pallet` module.
19
20use crate::{
21	asset, session_rotation::EraElectionPlanner, slashing, weights::WeightInfo, AccountIdLookupOf,
22	ActiveEraInfo, BalanceOf, EraPayout, EraRewardPoints, ExposurePage, Forcing,
23	LedgerIntegrityState, MaxNominationsOf, NegativeImbalanceOf, Nominations, NominationsQuota,
24	PositiveImbalanceOf, RewardDestination, StakingLedger, UnappliedSlash, UnlockChunk,
25	ValidatorPrefs,
26};
27use alloc::{format, vec::Vec};
28use codec::Codec;
29use frame_election_provider_support::{ElectionProvider, SortedListProvider, VoteWeight};
30use frame_support::{
31	assert_ok,
32	pallet_prelude::*,
33	traits::{
34		fungible::{
35			hold::{Balanced as FunHoldBalanced, Mutate as FunHoldMutate},
36			Mutate, Mutate as FunMutate,
37		},
38		Contains, Defensive, DefensiveSaturating, EnsureOrigin, Get, InspectLockableCurrency,
39		Nothing, OnUnbalanced,
40	},
41	weights::Weight,
42	BoundedBTreeSet, BoundedVec,
43};
44use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
45pub use impls::*;
46use rand::seq::SliceRandom;
47use rand_chacha::{
48	rand_core::{RngCore, SeedableRng},
49	ChaChaRng,
50};
51use sp_core::{sr25519::Pair as SrPair, Pair};
52use sp_runtime::{
53	traits::{StaticLookup, Zero},
54	ArithmeticError, Perbill, Percent,
55};
56use sp_staking::{
57	EraIndex, Page, SessionIndex,
58	StakingAccount::{self, Controller, Stash},
59	StakingInterface,
60};
61
62mod impls;
63
64#[frame_support::pallet]
65pub mod pallet {
66	use core::ops::Deref;
67
68	use super::*;
69	use crate::{session_rotation, PagedExposureMetadata, SnapshotStatus};
70	use codec::HasCompact;
71	use frame_election_provider_support::{ElectionDataProvider, PageIndex};
72	use frame_support::{traits::ConstBool, weights::WeightMeter, DefaultNoBound};
73
74	/// Dimensionless weight from the validator self-stake incentive curve. Same underlying type as
75	/// `BalanceOf<T>` for arithmetic compatibility, but represents the output of the sqrt weight
76	/// function.
77	type IncentiveWeight<T> = BalanceOf<T>;
78
79	/// Represents the current step in the era pruning process
80	#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen)]
81	pub enum PruningStep {
82		/// Pruning ErasStakersPaged storage
83		ErasStakersPaged,
84		/// Pruning ErasStakersOverview storage
85		ErasStakersOverview,
86		/// Pruning ErasValidatorPrefs storage
87		ErasValidatorPrefs,
88		/// Pruning ClaimedRewards storage
89		ClaimedRewards,
90		/// Pruning ErasValidatorReward storage
91		ErasValidatorReward,
92		/// Pruning ErasRewardPoints storage
93		ErasRewardPoints,
94		/// Pruning single-entry storages
95		SingleEntryCleanups,
96		/// Pruning ValidatorSlashInEra storage
97		ValidatorSlashInEra,
98		/// Pruning ErasValidatorIncentiveWeight storage
99		ErasValidatorIncentiveWeight,
100	}
101
102	/// The in-code storage version.
103	const STORAGE_VERSION: StorageVersion = StorageVersion::new(17);
104
105	#[pallet::pallet]
106	#[pallet::storage_version(STORAGE_VERSION)]
107	pub struct Pallet<T>(_);
108
109	/// Possible operations on the configuration values of this pallet.
110	#[derive(TypeInfo, Debug, Clone, Encode, Decode, DecodeWithMemTracking, PartialEq)]
111	pub enum ConfigOp<T: Default + Codec> {
112		/// Don't change.
113		Noop,
114		/// Set the given value.
115		Set(T),
116		/// Remove from storage.
117		Remove,
118	}
119
120	#[pallet::config(with_default)]
121	pub trait Config: frame_system::Config {
122		/// The old trait for staking balance. Deprecated and only used for migrating old ledgers.
123		#[pallet::no_default]
124		type OldCurrency: InspectLockableCurrency<
125			Self::AccountId,
126			Moment = BlockNumberFor<Self>,
127			Balance = Self::CurrencyBalance,
128		>;
129
130		/// The staking balance.
131		#[pallet::no_default]
132		type Currency: FunHoldMutate<
133				Self::AccountId,
134				Reason = Self::RuntimeHoldReason,
135				Balance = Self::CurrencyBalance,
136			> + FunMutate<Self::AccountId, Balance = Self::CurrencyBalance>
137			+ FunHoldBalanced<Self::AccountId, Balance = Self::CurrencyBalance>;
138
139		/// Overarching hold reason.
140		#[pallet::no_default_bounds]
141		type RuntimeHoldReason: From<HoldReason>;
142
143		/// Just the `Currency::Balance` type; we have this item to allow us to constrain it to
144		/// `From<u64>`.
145		type CurrencyBalance: sp_runtime::traits::AtLeast32BitUnsigned
146			+ codec::FullCodec
147			+ DecodeWithMemTracking
148			+ HasCompact<Type: DecodeWithMemTracking>
149			+ Copy
150			+ MaybeSerializeDeserialize
151			+ core::fmt::Debug
152			+ Default
153			+ From<u64>
154			+ TypeInfo
155			+ Send
156			+ Sync
157			+ MaxEncodedLen;
158
159		/// Convert a balance into a number used for election calculation. This must fit into a
160		/// `u64` but is allowed to be sensibly lossy. The `u64` is used to communicate with the
161		/// [`frame_election_provider_support`] crate which accepts u64 numbers and does operations
162		/// in 128.
163		/// Consequently, the backward convert is used convert the u128s from sp-elections back to a
164		/// [`BalanceOf`].
165		#[pallet::no_default_bounds]
166		type CurrencyToVote: sp_staking::currency_to_vote::CurrencyToVote<BalanceOf<Self>>;
167
168		/// Something that provides the election functionality.
169		#[pallet::no_default]
170		type ElectionProvider: ElectionProvider<
171			AccountId = Self::AccountId,
172			BlockNumber = BlockNumberFor<Self>,
173			// we only accept an election provider that has staking as data provider.
174			DataProvider = Pallet<Self>,
175		>;
176
177		/// Something that defines the maximum number of nominations per nominator.
178		#[pallet::no_default_bounds]
179		type NominationsQuota: NominationsQuota<BalanceOf<Self>>;
180
181		/// Number of eras to keep in history.
182		///
183		/// Following information is kept for eras in `[current_era -
184		/// HistoryDepth, current_era]`: `ErasValidatorPrefs`, `ErasValidatorReward`,
185		/// `ErasRewardPoints`, `ErasTotalStake`, `ClaimedRewards`,
186		/// `ErasStakersPaged`, `ErasStakersOverview`.
187		///
188		/// Must be more than the number of eras delayed by session.
189		/// I.e. active era must always be in history. I.e. `active_era >
190		/// current_era - history_depth` must be guaranteed.
191		///
192		/// If migrating an existing pallet from storage value to config value,
193		/// this should be set to same value or greater as in storage.
194		#[pallet::constant]
195		type HistoryDepth: Get<u32>;
196
197		/// Tokens have been minted and are unused for validator-reward.
198		///
199		/// Only used in legacy minting mode (`DisableMinting = false`).
200		#[pallet::no_default_bounds]
201		type RewardRemainder: OnUnbalanced<NegativeImbalanceOf<Self>>;
202
203		/// Handler for the unbalanced reduction when slashing a staker.
204		#[pallet::no_default_bounds]
205		type Slash: OnUnbalanced<NegativeImbalanceOf<Self>>;
206
207		/// Handler for the unbalanced increment when rewarding a staker.
208		/// NOTE: in most cases, the implementation of `OnUnbalanced` should modify the total
209		/// issuance.
210		///
211		/// Only used in legacy minting mode (`DisableMinting = false`).
212		#[pallet::no_default_bounds]
213		type Reward: OnUnbalanced<PositiveImbalanceOf<Self>>;
214
215		/// Number of sessions per era, as per the preferences of the **relay chain**.
216		#[pallet::constant]
217		type SessionsPerEra: Get<SessionIndex>;
218
219		/// Number of sessions before the end of an era when the election for the next era will
220		/// start.
221		///
222		/// - This determines how many sessions **before** the last session of the era the staking
223		///   election process should begin.
224		/// - The value is bounded between **1** (election starts at the beginning of the last
225		///   session) and `SessionsPerEra` (election starts at the beginning of the first session
226		///   of the era).
227		///
228		/// ### Example:
229		/// - If `SessionsPerEra = 6` and `PlanningEraOffset = 1`, the election starts at the
230		///   beginning of session `6 - 1 = 5`.
231		/// - If `PlanningEraOffset = 6`, the election starts at the beginning of session `6 - 6 =
232		///   0`, meaning it starts at the very beginning of the era.
233		#[pallet::constant]
234		type PlanningEraOffset: Get<SessionIndex>;
235
236		/// Number of eras that staked funds must remain bonded for.
237		///
238		/// This is the bonding duration for validators. Nominators may have a shorter bonding
239		/// duration when [`AreNominatorsSlashable`] is set to `false` (see
240		/// [`StakingInterface::nominator_bonding_duration`]).
241		#[pallet::constant]
242		type BondingDuration: Get<EraIndex>;
243
244		/// Number of eras nominators must wait to unbond when they are not slashable.
245		///
246		/// This duration is used for nominators when [`AreNominatorsSlashable`] is `false`.
247		/// When nominators are slashable, they use the full [`Config::BondingDuration`] to ensure
248		/// slashes can be applied during the unbonding period.
249		///
250		/// Setting this to a lower value (e.g., 1 era) allows for faster withdrawals when
251		/// nominators are not subject to slashing risk.
252		#[pallet::constant]
253		type NominatorFastUnbondDuration: Get<EraIndex>;
254
255		/// Number of eras that slashes are deferred by, after computation.
256		///
257		/// This should be less than the bonding duration. Set to 0 if slashes
258		/// should be applied immediately, without opportunity for intervention.
259		#[pallet::constant]
260		type SlashDeferDuration: Get<EraIndex>;
261
262		/// The origin which can manage less critical staking parameters that does not require root.
263		///
264		/// Supported actions: (1) cancel deferred slash, (2) set minimum commission.
265		#[pallet::no_default]
266		type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
267
268		/// The payout for validators and the system for the current era.
269		/// See [Era payout](./index.html#era-payout).
270		///
271		/// Only used in legacy minting mode (`DisableMinting = false`).
272		/// Should be set to () in non-minting mode.
273		#[pallet::no_default]
274		type EraPayout: EraPayout<BalanceOf<Self>>;
275
276		/// When `true`, staking does not mint. It expects an external source to fund
277		/// the general reward pot. At era boundary, rewards are snapshotted from
278		/// the pot. `EraPayout` is not called.
279		///
280		/// When `false`, staking uses the legacy path: `EraPayout` computes inflation,
281		/// tokens are minted on-the-fly during payout.
282		///
283		/// **Irreversible**: once set to `true`, must never be switched back. Eras
284		/// created in non-minting mode have funded reward pots — switching to legacy
285		/// would orphan those pots and cause double-minting.
286		#[pallet::constant]
287		type DisableMinting: Get<bool>;
288
289		/// Handler for unclaimed era rewards (non-minting mode only).
290		///
291		/// When era pots are cleaned up past `HistoryDepth`, remaining funds are
292		/// withdrawn and passed to this handler.
293		#[pallet::no_default_bounds]
294		type UnclaimedRewardHandler: OnUnbalanced<NegativeImbalanceOf<Self>>;
295
296		/// Provider for generating reward pot account IDs (non-minting mode only).
297		///
298		/// Provides both general pots (funded by an external source like pallet-dap)
299		/// and era-specific pots (snapshotted at era boundaries).
300		#[pallet::no_default]
301		type RewardPots: crate::PotAccountProvider<Self::AccountId>;
302
303		/// Calculator for staker rewards.
304		///
305		/// Determines how staking rewards are distributed between validators and nominators.
306		#[pallet::no_default_bounds]
307		type StakerRewardCalculator: sp_staking::StakerRewardCalculator<BalanceOf<Self>>;
308
309		/// The maximum size of each `T::ExposurePage`.
310		///
311		/// An `ExposurePage` is weakly bounded to a maximum of `MaxExposurePageSize`
312		/// nominators.
313		///
314		/// For older non-paged exposure, a reward payout was restricted to the top
315		/// `MaxExposurePageSize` nominators. This is to limit the i/o cost for the
316		/// nominator payout.
317		///
318		/// Note: `MaxExposurePageSize` is used to bound `ClaimedRewards` and is unsafe to
319		/// reduce without handling it in a migration.
320		#[pallet::constant]
321		type MaxExposurePageSize: Get<u32>;
322
323		/// The absolute maximum of winner validators this pallet should return.
324		///
325		/// As this pallet supports multi-block election, the set of winner validators *per
326		/// election* is bounded by this type.
327		#[pallet::constant]
328		type MaxValidatorSet: Get<u32>;
329
330		/// Something that provides a best-effort sorted list of voters aka electing nominators,
331		/// used for NPoS election.
332		///
333		/// The changes to nominators are reported to this. Moreover, each validator's self-vote is
334		/// also reported as one independent vote.
335		///
336		/// To keep the load off the chain as much as possible, changes made to the staked amount
337		/// via rewards and slashes are not reported and thus need to be manually fixed by the
338		/// staker. In case of `bags-list`, this always means using `rebag` and `putInFrontOf`.
339		///
340		/// Invariant: what comes out of this list will always be a nominator.
341		#[pallet::no_default]
342		type VoterList: SortedListProvider<Self::AccountId, Score = VoteWeight>;
343
344		/// WIP: This is a noop as of now, the actual business logic that's described below is going
345		/// to be introduced in a follow-up PR.
346		///
347		/// Something that provides a best-effort sorted list of targets aka electable validators,
348		/// used for NPoS election.
349		///
350		/// The changes to the approval stake of each validator are reported to this. This means any
351		/// change to:
352		/// 1. The stake of any validator or nominator.
353		/// 2. The targets of any nominator
354		/// 3. The role of any staker (e.g. validator -> chilled, nominator -> validator, etc)
355		///
356		/// Unlike `VoterList`, the values in this list are always kept up to date with reward and
357		/// slash as well, and thus represent the accurate approval stake of all account being
358		/// nominated by nominators.
359		///
360		/// Note that while at the time of nomination, all targets are checked to be real
361		/// validators, they can chill at any point, and their approval stakes will still be
362		/// recorded. This implies that what comes out of iterating this list MIGHT NOT BE AN ACTIVE
363		/// VALIDATOR.
364		#[pallet::no_default]
365		type TargetList: SortedListProvider<Self::AccountId, Score = BalanceOf<Self>>;
366
367		/// The maximum number of `unlocking` chunks a [`StakingLedger`] can
368		/// have. Effectively determines how many unique eras a staker may be
369		/// unbonding in.
370		///
371		/// Note: `MaxUnlockingChunks` is used as the upper bound for the
372		/// `BoundedVec` item `StakingLedger.unlocking`. Setting this value
373		/// lower than the existing value can lead to inconsistencies in the
374		/// `StakingLedger` and will need to be handled properly in a runtime
375		/// migration. The test `reducing_max_unlocking_chunks_abrupt` shows
376		/// this effect.
377		#[pallet::constant]
378		type MaxUnlockingChunks: Get<u32>;
379
380		/// The maximum amount of controller accounts that can be deprecated in one call.
381		type MaxControllersInDeprecationBatch: Get<u32>;
382
383		/// Something that listens to staking updates and performs actions based on the data it
384		/// receives.
385		///
386		/// WARNING: this only reports slashing and withdraw events for the time being.
387		#[pallet::no_default_bounds]
388		type EventListeners: sp_staking::OnStakingUpdate<Self::AccountId, BalanceOf<Self>>;
389
390		/// Maximum allowed era duration in milliseconds.
391		///
392		/// This provides a defensive upper bound to cap the effective era duration, preventing
393		/// excessively long eras from causing runaway inflation (e.g., due to bugs). If the actual
394		/// era duration exceeds this value, it will be clamped to this maximum.
395		///
396		/// Example: For an ideal era duration of 24 hours (86,400,000 ms),
397		/// this can be set to 604,800,000 ms (7 days).
398		///
399		/// Only used in legacy minting mode (`DisableMinting = false`).
400		#[pallet::constant]
401		type MaxEraDuration: Get<u64>;
402
403		/// Maximum number of storage items that can be pruned in a single call.
404		///
405		/// This controls how many storage items can be deleted in each call to `prune_era_step`.
406		/// This should be set to a conservative value (e.g., 100-500 items) to ensure pruning
407		/// doesn't consume too much block space. The actual weight is determined by benchmarks.
408		#[pallet::constant]
409		type MaxPruningItems: Get<u32>;
410
411		/// Interface to talk to the RC-Client pallet, possibly sending election results to the
412		/// relay chain.
413		#[pallet::no_default]
414		type RcClientInterface: pallet_staking_async_rc_client::RcClientInterface<
415			AccountId = Self::AccountId,
416		>;
417
418		#[pallet::no_default_bounds]
419		/// Filter some accounts from participating in staking.
420		///
421		/// This is useful for example to blacklist an account that is participating in staking in
422		/// another way (such as pools).
423		type Filter: Contains<Self::AccountId>;
424
425		/// Weight information for extrinsics in this pallet.
426		type WeightInfo: WeightInfo;
427	}
428
429	/// A reason for placing a hold on funds.
430	#[pallet::composite_enum]
431	pub enum HoldReason {
432		/// Funds on stake by a nominator or a validator.
433		#[codec(index = 0)]
434		Staking,
435	}
436
437	/// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`].
438	pub mod config_preludes {
439		use super::*;
440		use frame_support::{derive_impl, parameter_types, traits::ConstU32};
441		pub struct TestDefaultConfig;
442
443		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
444		impl frame_system::DefaultConfig for TestDefaultConfig {}
445
446		parameter_types! {
447			pub const SessionsPerEra: SessionIndex = 3;
448			pub const BondingDuration: EraIndex = 3;
449			pub const NominatorFastUnbondDuration: EraIndex = 2;
450			pub const MaxPruningItems: u32 = 100;
451		}
452
453		#[frame_support::register_default_impl(TestDefaultConfig)]
454		impl DefaultConfig for TestDefaultConfig {
455			#[inject_runtime_type]
456			type RuntimeHoldReason = ();
457			type CurrencyBalance = u128;
458			type CurrencyToVote = ();
459			type NominationsQuota = crate::FixedNominationsQuota<16>;
460			type HistoryDepth = ConstU32<84>;
461			type RewardRemainder = ();
462			type Slash = ();
463			type Reward = ();
464			type UnclaimedRewardHandler = ();
465			type StakerRewardCalculator = ();
466			type DisableMinting = ConstBool<false>;
467			type SessionsPerEra = SessionsPerEra;
468			type BondingDuration = BondingDuration;
469			type NominatorFastUnbondDuration = NominatorFastUnbondDuration;
470			type PlanningEraOffset = ConstU32<1>;
471			type SlashDeferDuration = ();
472			type MaxExposurePageSize = ConstU32<64>;
473			type MaxUnlockingChunks = ConstU32<32>;
474			type MaxValidatorSet = ConstU32<100>;
475			type MaxControllersInDeprecationBatch = ConstU32<100>;
476			type MaxEraDuration = ();
477			type MaxPruningItems = MaxPruningItems;
478			type EventListeners = ();
479			type Filter = Nothing;
480			type WeightInfo = ();
481		}
482	}
483
484	/// The ideal number of active validators.
485	#[pallet::storage]
486	pub type ValidatorCount<T> = StorageValue<_, u32, ValueQuery>;
487
488	/// Map from all locked "stash" accounts to the controller account.
489	///
490	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
491	#[pallet::storage]
492	pub type Bonded<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, T::AccountId>;
493
494	/// The minimum active bond to become and maintain the role of a nominator.
495	#[pallet::storage]
496	pub type MinNominatorBond<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
497
498	/// The minimum active bond to become and maintain the role of a validator.
499	#[pallet::storage]
500	pub type MinValidatorBond<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
501
502	/// The minimum active nominator stake of the last successful election.
503	#[pallet::storage]
504	pub type MinimumActiveStake<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;
505
506	/// The minimum amount of commission that validators can set.
507	///
508	/// If set to `0`, no limit exists.
509	#[pallet::storage]
510	pub type MinCommission<T: Config> = StorageValue<_, Perbill, ValueQuery>;
511
512	/// The maximum commission that validators can set.
513	///
514	/// If not set, defaults to `Perbill::one()` (100%), i.e. no upper limit.
515	#[pallet::storage]
516	pub type MaxCommission<T: Config> = StorageValue<_, Perbill, ValueQuery, MaxCommissionDefault>;
517
518	/// Default for MaxCommission: 100% (no restriction).
519	pub struct MaxCommissionDefault;
520	impl Get<Perbill> for MaxCommissionDefault {
521		fn get() -> Perbill {
522			Perbill::one()
523		}
524	}
525
526	/// Safety guard: the era from which legacy minting is permanently disabled on the
527	/// payout side. **Irreversible** — once set, should never be cleared.
528	///
529	/// Separate from [`Config::DisableMinting`] which controls the `end_era` path.
530	/// This storage guards against minting during payout for eras that were created
531	/// in DAP mode. Set automatically by `end_era_dap` on first successful pot snapshot.
532	/// In legacy mode (Kusama), this is never set and the guard is inactive.
533	#[pallet::storage]
534	pub type DisableMintingGuard<T: Config> = StorageValue<_, EraIndex>;
535
536	/// Optimum self-stake threshold for validators.
537	///
538	/// Below this threshold, the incentive weight grows as `sqrt(self_stake)`.
539	/// Above it, growth is dampened by [`SelfStakeSlopeFactor`].
540	#[pallet::storage]
541	pub type OptimumSelfStake<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
542
543	/// Hard cap on effective validator self-stake.
544	///
545	/// Self-stake above this value receives no additional reward benefit (plateau).
546	#[pallet::storage]
547	pub type HardCapSelfStake<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
548
549	/// Slope factor controlling the discouragement rate for self-stake between optimum and cap.
550	///
551	/// Value between 0 and 1: k=1 means no discouragement, k=0 means immediate plateau.
552	#[pallet::storage]
553	pub type SelfStakeSlopeFactor<T: Config> = StorageValue<_, Perbill, ValueQuery>;
554
555	/// The total validator incentive budget for the given era, snapshotted at era end.
556	///
557	/// This is the similar to [`ErasValidatorReward`] but for the self-stake incentive pot.
558	#[pallet::storage]
559	pub type ErasValidatorIncentiveBudget<T: Config> =
560		StorageMap<_, Twox64Concat, EraIndex, BalanceOf<T>, ValueQuery>;
561
562	/// Sum of all validators' incentive weights for the era.
563	///
564	/// Directly linked to [`ErasValidatorIncentiveWeight`].
565	#[pallet::storage]
566	pub type ErasSumValidatorIncentiveWeight<T: Config> =
567		StorageMap<_, Twox64Concat, EraIndex, IncentiveWeight<T>, ValueQuery>;
568
569	/// Individual validator incentive weight per era.
570	/// Each validator's share of the incentive pot = `their_weight / sum_weight`.
571	#[pallet::storage]
572	pub type ErasValidatorIncentiveWeight<T: Config> = StorageDoubleMap<
573		_,
574		Twox64Concat,
575		EraIndex,
576		Twox64Concat,
577		T::AccountId,
578		IncentiveWeight<T>,
579		OptionQuery,
580	>;
581
582	/// Whether nominators are slashable or not.
583	///
584	/// - When set to `true` (default), nominators are slashed along with validators and must wait
585	///   the full [`Config::BondingDuration`] before withdrawing unbonded funds.
586	/// - When set to `false`, nominators are not slashed, and can unbond in
587	///   [`Config::NominatorFastUnbondDuration`] eras instead of the full
588	///   [`Config::BondingDuration`] (see [`StakingInterface::nominator_bonding_duration`]).
589	#[pallet::storage]
590	pub type AreNominatorsSlashable<T: Config> = StorageValue<_, bool, ValueQuery, ConstBool<true>>;
591
592	/// Per-era snapshot of whether nominators are slashable.
593	///
594	/// This is copied from [`AreNominatorsSlashable`] at the start of each era. When processing
595	/// offences, we use the value from this storage for the offence era to ensure that the
596	/// slashing rules at the time of the offence are applied, not the current rules.
597	///
598	/// If an entry does not exist for an era, nominators are assumed to be slashable (default).
599	#[pallet::storage]
600	pub type ErasNominatorsSlashable<T: Config> =
601		StorageMap<_, Twox64Concat, EraIndex, bool, OptionQuery>;
602
603	/// Map from all (unlocked) "controller" accounts to the info regarding the staking.
604	///
605	/// Note: All the reads and mutations to this storage *MUST* be done through the methods exposed
606	/// by [`StakingLedger`] to ensure data and lock consistency.
607	#[pallet::storage]
608	pub type Ledger<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, StakingLedger<T>>;
609
610	/// Where the reward payment should be made. Keyed by stash.
611	///
612	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
613	#[pallet::storage]
614	pub type Payee<T: Config> =
615		StorageMap<_, Twox64Concat, T::AccountId, RewardDestination<T::AccountId>, OptionQuery>;
616
617	/// The map from (wannabe) validator stash key to the preferences of that validator.
618	///
619	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
620	#[pallet::storage]
621	pub type Validators<T: Config> =
622		CountedStorageMap<_, Twox64Concat, T::AccountId, ValidatorPrefs, ValueQuery>;
623
624	/// The maximum validator count before we stop allowing new validators to join.
625	///
626	/// When this value is not set, no limits are enforced.
627	#[pallet::storage]
628	pub type MaxValidatorsCount<T> = StorageValue<_, u32, OptionQuery>;
629
630	/// Tracks the last era in which an account was active as a validator (included in the era's
631	/// exposure/snapshot).
632	///
633	/// This is used to enforce that accounts who were recently validators must wait the full
634	/// [`Config::BondingDuration`] before their funds can be withdrawn, even if they switch to
635	/// nominator role. This prevents validators from:
636	/// 1. Committing a slashable offence in era N
637	/// 2. Switching to nominator role
638	/// 3. Using the shorter nominator unbonding duration to withdraw funds before being slashed
639	///
640	/// Updated when era snapshots are created (in `ErasStakersPaged`/`ErasStakersOverview`).
641	/// Cleaned up when the stash is killed (fully withdrawn/reaped).
642	#[pallet::storage]
643	pub type LastValidatorEra<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, EraIndex>;
644
645	/// The map from nominator stash key to their nomination preferences, namely the validators that
646	/// they wish to support.
647	///
648	/// Note that the keys of this storage map might become non-decodable in case the
649	/// account's [`NominationsQuota::MaxNominations`] configuration is decreased.
650	/// In this rare case, these nominators
651	/// are still existent in storage, their key is correct and retrievable (i.e. `contains_key`
652	/// indicates that they exist), but their value cannot be decoded. Therefore, the non-decodable
653	/// nominators will effectively not-exist, until they re-submit their preferences such that it
654	/// is within the bounds of the newly set `Config::MaxNominations`.
655	///
656	/// This implies that `::iter_keys().count()` and `::iter().count()` might return different
657	/// values for this map. Moreover, the main `::count()` is aligned with the former, namely the
658	/// number of keys that exist.
659	///
660	/// Lastly, if any of the nominators become non-decodable, they can be chilled immediately via
661	/// [`Call::chill_other`] dispatchable by anyone.
662	///
663	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
664	#[pallet::storage]
665	pub type Nominators<T: Config> =
666		CountedStorageMap<_, Twox64Concat, T::AccountId, Nominations<T>>;
667
668	/// Stakers whose funds are managed by other pallets.
669	///
670	/// This pallet does not apply any locks on them, therefore they are only virtually bonded. They
671	/// are expected to be keyless accounts and hence should not be allowed to mutate their ledger
672	/// directly via this pallet. Instead, these accounts are managed by other pallets and accessed
673	/// via low level apis. We keep track of them to do minimal integrity checks.
674	#[pallet::storage]
675	pub type VirtualStakers<T: Config> = CountedStorageMap<_, Twox64Concat, T::AccountId, ()>;
676
677	/// The maximum nominator count before we stop allowing new validators to join.
678	///
679	/// When this value is not set, no limits are enforced.
680	#[pallet::storage]
681	pub type MaxNominatorsCount<T> = StorageValue<_, u32, OptionQuery>;
682
683	// --- AUDIT NOTE: the following storage items should only be controlled by `Rotator`
684
685	/// The current planned era index.
686	///
687	/// This is the latest planned era, depending on how the Session pallet queues the validator
688	/// set, it might be active or not.
689	#[pallet::storage]
690	pub type CurrentEra<T> = StorageValue<_, EraIndex>;
691
692	/// The active era information, it holds index and start.
693	///
694	/// The active era is the era being currently rewarded. Validator set of this era must be
695	/// equal to what is RC's session pallet.
696	#[pallet::storage]
697	pub type ActiveEra<T> = StorageValue<_, ActiveEraInfo>;
698
699	/// Custom bound for [`BondedEras`] which is equal to [`Config::BondingDuration`] + 1.
700	pub struct BondedErasBound<T>(core::marker::PhantomData<T>);
701	impl<T: Config> Get<u32> for BondedErasBound<T> {
702		fn get() -> u32 {
703			T::BondingDuration::get().saturating_add(1)
704		}
705	}
706
707	const OFFENCE_QUEUE_ERAS_BOUND: u32 = 10;
708	/// Custom bound for [`OffenceQueueEras`] which is equal to `Config::BondingDuration +
709	/// OFFENCE_QUEUE_ERAS_BOUND`.
710	pub struct OffenceQueueErasBound<T>(core::marker::PhantomData<T>);
711	impl<T: Config> Get<u32> for OffenceQueueErasBound<T> {
712		fn get() -> u32 {
713			let bonding_duration = T::BondingDuration::get();
714			bonding_duration.saturating_add(OFFENCE_QUEUE_ERAS_BOUND) // adding OFFENCE_QUEUE_ERAS_BOUND eras
715			                                                 // to add headroom to
716			                                                 // the bound for runtime upgrades that
717			                                                 // lower BondingDuration so we avoid
718			                                                 // the try_into trap.
719		}
720	}
721
722	/// A mapping from still-bonded eras to the first session index of that era.
723	///
724	/// Must contains information for eras for the range:
725	/// `[active_era - bounding_duration; active_era]`
726	#[pallet::storage]
727	pub type BondedEras<T: Config> =
728		StorageValue<_, BoundedVec<(EraIndex, SessionIndex), BondedErasBound<T>>, ValueQuery>;
729
730	// --- AUDIT Note: end of storage items controlled by `Rotator`.
731
732	/// Summary of validator exposure at a given era.
733	///
734	/// This contains the total stake in support of the validator and their own stake. In addition,
735	/// it can also be used to get the number of nominators backing this validator and the number of
736	/// exposure pages they are divided into. The page count is useful to determine the number of
737	/// pages of rewards that needs to be claimed.
738	///
739	/// This is keyed first by the era index to allow bulk deletion and then the stash account.
740	/// Should only be accessed through `Eras`.
741	///
742	/// Is it removed after [`Config::HistoryDepth`] eras.
743	/// If stakers hasn't been set or has been removed then empty overview is returned.
744	#[pallet::storage]
745	pub type ErasStakersOverview<T: Config> = StorageDoubleMap<
746		_,
747		Twox64Concat,
748		EraIndex,
749		Twox64Concat,
750		T::AccountId,
751		PagedExposureMetadata<BalanceOf<T>>,
752		OptionQuery,
753	>;
754
755	/// A bounded wrapper for [`sp_staking::ExposurePage`].
756	///
757	/// It has `Deref` and `DerefMut` impls that map it back [`sp_staking::ExposurePage`] for all
758	/// purposes. This is done in such a way because we prefer to keep the types in [`sp_staking`]
759	/// pure, and not polluted by pallet-specific bounding logic.
760	///
761	/// It encoded and decodes exactly the same as [`sp_staking::ExposurePage`], and provides a
762	/// manual `MaxEncodedLen` implementation, to be used in benchmarking
763	#[derive(PartialEqNoBound, Encode, Decode, DebugNoBound, TypeInfo, DefaultNoBound)]
764	#[scale_info(skip_type_params(T))]
765	pub struct BoundedExposurePage<T: Config>(pub ExposurePage<T::AccountId, BalanceOf<T>>);
766	impl<T: Config> Deref for BoundedExposurePage<T> {
767		type Target = ExposurePage<T::AccountId, BalanceOf<T>>;
768
769		fn deref(&self) -> &Self::Target {
770			&self.0
771		}
772	}
773
774	impl<T: Config> core::ops::DerefMut for BoundedExposurePage<T> {
775		fn deref_mut(&mut self) -> &mut Self::Target {
776			&mut self.0
777		}
778	}
779
780	impl<T: Config> codec::MaxEncodedLen for BoundedExposurePage<T> {
781		fn max_encoded_len() -> usize {
782			let max_exposure_page_size = T::MaxExposurePageSize::get() as usize;
783			let individual_size =
784				T::AccountId::max_encoded_len() + BalanceOf::<T>::max_encoded_len();
785
786			// 1 balance for `total`
787			BalanceOf::<T>::max_encoded_len() +
788			// individual_size multiplied by page size
789				max_exposure_page_size.saturating_mul(individual_size)
790		}
791	}
792
793	impl<T: Config> From<ExposurePage<T::AccountId, BalanceOf<T>>> for BoundedExposurePage<T> {
794		fn from(value: ExposurePage<T::AccountId, BalanceOf<T>>) -> Self {
795			Self(value)
796		}
797	}
798
799	impl<T: Config> From<BoundedExposurePage<T>> for ExposurePage<T::AccountId, BalanceOf<T>> {
800		fn from(value: BoundedExposurePage<T>) -> Self {
801			value.0
802		}
803	}
804
805	impl<T: Config> codec::EncodeLike<BoundedExposurePage<T>>
806		for ExposurePage<T::AccountId, BalanceOf<T>>
807	{
808	}
809
810	/// Paginated exposure of a validator at given era.
811	///
812	/// This is keyed first by the era index to allow bulk deletion, then stash account and finally
813	/// the page. Should only be accessed through `Eras`.
814	///
815	/// This is cleared after [`Config::HistoryDepth`] eras.
816	#[pallet::storage]
817	pub type ErasStakersPaged<T: Config> = StorageNMap<
818		_,
819		(
820			NMapKey<Twox64Concat, EraIndex>,
821			NMapKey<Twox64Concat, T::AccountId>,
822			NMapKey<Twox64Concat, Page>,
823		),
824		BoundedExposurePage<T>,
825		OptionQuery,
826	>;
827
828	pub struct ClaimedRewardsBound<T>(core::marker::PhantomData<T>);
829	impl<T: Config> Get<u32> for ClaimedRewardsBound<T> {
830		fn get() -> u32 {
831			let max_total_nominators_per_validator =
832				<T::ElectionProvider as ElectionProvider>::MaxBackersPerWinnerFinal::get();
833			let exposure_page_size = T::MaxExposurePageSize::get();
834			max_total_nominators_per_validator
835				.saturating_div(exposure_page_size)
836				.saturating_add(1)
837		}
838	}
839
840	/// History of claimed paged rewards by era and validator.
841	///
842	/// This is keyed by era and validator stash which maps to the set of page indexes which have
843	/// been claimed.
844	///
845	/// It is removed after [`Config::HistoryDepth`] eras.
846	#[pallet::storage]
847	pub type ClaimedRewards<T: Config> = StorageDoubleMap<
848		_,
849		Twox64Concat,
850		EraIndex,
851		Twox64Concat,
852		T::AccountId,
853		WeakBoundedVec<Page, ClaimedRewardsBound<T>>,
854		ValueQuery,
855	>;
856
857	/// Exposure of validator at era with the preferences of validators.
858	///
859	/// This is keyed first by the era index to allow bulk deletion and then the stash account.
860	///
861	/// Is it removed after [`Config::HistoryDepth`] eras.
862	// If prefs hasn't been set or has been removed then 0 commission is returned.
863	#[pallet::storage]
864	pub type ErasValidatorPrefs<T: Config> = StorageDoubleMap<
865		_,
866		Twox64Concat,
867		EraIndex,
868		Twox64Concat,
869		T::AccountId,
870		ValidatorPrefs,
871		ValueQuery,
872	>;
873
874	/// The total staker reward budget for each era within [`Config::HistoryDepth`].
875	///
876	/// Set at era finalization:
877	/// - in non-minting mode this is the snapshot of the era pot balance before any payouts.
878	/// - in legacy mode it comes from `EraPayout`, with rewards minted on the fly.
879	#[pallet::storage]
880	pub type ErasValidatorReward<T: Config> = StorageMap<_, Twox64Concat, EraIndex, BalanceOf<T>>;
881
882	/// Rewards for the last [`Config::HistoryDepth`] eras.
883	/// If reward hasn't been set or has been removed then 0 reward is returned.
884	#[pallet::storage]
885	pub type ErasRewardPoints<T: Config> =
886		StorageMap<_, Twox64Concat, EraIndex, EraRewardPoints<T>, ValueQuery>;
887
888	/// The total amount staked for the last [`Config::HistoryDepth`] eras.
889	/// If total hasn't been set or has been removed then 0 stake is returned.
890	#[pallet::storage]
891	pub type ErasTotalStake<T: Config> =
892		StorageMap<_, Twox64Concat, EraIndex, BalanceOf<T>, ValueQuery>;
893
894	/// Mode of era forcing.
895	#[pallet::storage]
896	pub type ForceEra<T> = StorageValue<_, Forcing, ValueQuery>;
897
898	/// Maximum staked rewards, i.e. the percentage of the era inflation that
899	/// is used for stake rewards.
900	///
901	/// Only used in legacy minting mode (`DisableMinting = false`).
902	#[pallet::storage]
903	pub type MaxStakedRewards<T> = StorageValue<_, Percent, OptionQuery>;
904
905	/// The percentage of the slash that is distributed to reporters.
906	///
907	/// The rest of the slashed value is handled by the `Slash`.
908	#[pallet::storage]
909	pub type SlashRewardFraction<T> = StorageValue<_, Perbill, ValueQuery>;
910
911	/// The amount of currency given to reporters of a slash event which was
912	/// canceled by extraordinary circumstances (e.g. governance).
913	#[pallet::storage]
914	pub type CanceledSlashPayout<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
915
916	/// Stores reported offences in a queue until they are processed in subsequent blocks.
917	///
918	/// Each offence is recorded under the corresponding era index and the offending validator's
919	/// account. If an offence spans multiple pages, only one page is processed at a time. Offences
920	/// are handled sequentially, with their associated slashes computed and stored in
921	/// `UnappliedSlashes`. These slashes are then applied in a future era as determined by
922	/// `SlashDeferDuration`.
923	///
924	/// Any offences tied to an era older than `BondingDuration` are automatically dropped.
925	/// Processing always prioritizes the oldest era first.
926	#[pallet::storage]
927	pub type OffenceQueue<T: Config> = StorageDoubleMap<
928		_,
929		Twox64Concat,
930		EraIndex,
931		Twox64Concat,
932		T::AccountId,
933		slashing::OffenceRecord<T::AccountId>,
934	>;
935
936	/// Tracks the eras that contain offences in `OffenceQueue`, sorted from **earliest to latest**.
937	///
938	/// - This ensures efficient retrieval of the oldest offence without iterating through
939	/// `OffenceQueue`.
940	/// - When a new offence is added to `OffenceQueue`, its era is **inserted in sorted order**
941	/// if not already present.
942	/// - When all offences for an era are processed, it is **removed** from this list.
943	/// - The maximum length of this vector is bounded by `BondingDuration +
944	///   OFFENCE_QUEUE_ERAS_BOUND`.
945	///
946	/// This eliminates the need for expensive iteration and sorting when fetching the next offence
947	/// to process.
948	#[pallet::storage]
949	pub type OffenceQueueEras<T: Config> =
950		StorageValue<_, WeakBoundedVec<u32, OffenceQueueErasBound<T>>>;
951
952	/// Tracks the currently processed offence record from the `OffenceQueue`.
953	///
954	/// - When processing offences, an offence record is **popped** from the oldest era in
955	///   `OffenceQueue` and stored here.
956	/// - The function `process_offence` reads from this storage, processing one page of exposure at
957	///   a time.
958	/// - After processing a page, the `exposure_page` count is **decremented** until it reaches
959	///   zero.
960	/// - Once fully processed, the offence record is removed from this storage.
961	///
962	/// This ensures that offences are processed incrementally, preventing excessive computation
963	/// in a single block while maintaining correct slashing behavior.
964	#[pallet::storage]
965	pub type ProcessingOffence<T: Config> =
966		StorageValue<_, (EraIndex, T::AccountId, slashing::OffenceRecord<T::AccountId>)>;
967
968	/// All unapplied slashes that are queued for later.
969	#[pallet::storage]
970	pub type UnappliedSlashes<T: Config> = StorageDoubleMap<
971		_,
972		Twox64Concat,
973		EraIndex,
974		Twox64Concat,
975		// Unique key for unapplied slashes: (validator, slash fraction, page index).
976		(T::AccountId, Perbill, u32),
977		UnappliedSlash<T>,
978		OptionQuery,
979	>;
980
981	/// Cancelled slashes by era and validator with maximum slash fraction to be cancelled.
982	///
983	/// When slashes are cancelled by governance, this stores the era and the validators
984	/// whose slashes should be cancelled, along with the maximum slash fraction that should
985	/// be cancelled for each validator.
986	#[pallet::storage]
987	pub type CancelledSlashes<T: Config> = StorageMap<
988		_,
989		Twox64Concat,
990		EraIndex,
991		BoundedVec<(T::AccountId, Perbill), T::MaxValidatorSet>,
992		ValueQuery,
993	>;
994
995	/// All slashing events on validators, mapped by era to the highest slash proportion
996	/// and slash value of the era.
997	#[pallet::storage]
998	pub type ValidatorSlashInEra<T: Config> = StorageDoubleMap<
999		_,
1000		Twox64Concat,
1001		EraIndex,
1002		Twox64Concat,
1003		T::AccountId,
1004		(Perbill, BalanceOf<T>),
1005	>;
1006
1007	/// The threshold for when users can start calling `chill_other` for other validators /
1008	/// nominators. The threshold is compared to the actual number of validators / nominators
1009	/// (`CountFor*`) in the system compared to the configured max (`Max*Count`).
1010	#[pallet::storage]
1011	pub type ChillThreshold<T: Config> = StorageValue<_, Percent, OptionQuery>;
1012
1013	/// Voter snapshot progress status.
1014	///
1015	/// If the status is `Ongoing`, it keeps a cursor of the last voter retrieved to proceed when
1016	/// creating the next snapshot page.
1017	#[pallet::storage]
1018	pub type VoterSnapshotStatus<T: Config> =
1019		StorageValue<_, SnapshotStatus<T::AccountId>, ValueQuery>;
1020
1021	/// Keeps track of an ongoing multi-page election solution request.
1022	///
1023	/// If `Some(_)``, it is the next page that we intend to elect. If `None`, we are not in the
1024	/// election process.
1025	///
1026	/// This is only set in multi-block elections. Should always be `None` otherwise.
1027	#[pallet::storage]
1028	pub type NextElectionPage<T: Config> = StorageValue<_, PageIndex, OptionQuery>;
1029
1030	/// A bounded list of the "electable" stashes that resulted from a successful election.
1031	#[pallet::storage]
1032	pub type ElectableStashes<T: Config> =
1033		StorageValue<_, BoundedBTreeSet<T::AccountId, T::MaxValidatorSet>, ValueQuery>;
1034
1035	/// Tracks the current step of era pruning process for each era being lazily pruned.
1036	#[pallet::storage]
1037	pub type EraPruningState<T: Config> = StorageMap<_, Twox64Concat, EraIndex, PruningStep>;
1038
1039	#[pallet::genesis_config]
1040	#[derive(frame_support::DefaultNoBound, frame_support::DebugNoBound)]
1041	pub struct GenesisConfig<T: Config> {
1042		pub validator_count: u32,
1043		pub force_era: Forcing,
1044		pub slash_reward_fraction: Perbill,
1045		pub canceled_payout: BalanceOf<T>,
1046		pub stakers: Vec<(T::AccountId, BalanceOf<T>, crate::StakerStatus<T::AccountId>)>,
1047		pub min_nominator_bond: BalanceOf<T>,
1048		pub min_validator_bond: BalanceOf<T>,
1049		pub max_validator_count: Option<u32>,
1050		pub max_nominator_count: Option<u32>,
1051		/// Create the given number of validators and nominators.
1052		///
1053		/// These account need not be in the endowment list of balances, and are auto-topped up
1054		/// here.
1055		///
1056		/// Useful for testing genesis config.
1057		pub dev_stakers: Option<(u32, u32)>,
1058		/// initial active era, corresponding session index and start timestamp.
1059		pub active_era: (u32, u32, u64),
1060	}
1061
1062	impl<T: Config> GenesisConfig<T> {
1063		fn generate_endowed_bonded_account(derivation: &str, rng: &mut ChaChaRng) -> T::AccountId {
1064			let pair: SrPair = Pair::from_string(&derivation, None)
1065				.expect(&format!("Failed to parse derivation string: {derivation}"));
1066			let who = T::AccountId::decode(&mut &pair.public().encode()[..])
1067				.expect(&format!("Failed to decode public key from pair: {:?}", pair.public()));
1068
1069			let (min, max) = T::VoterList::range();
1070			let stake = BalanceOf::<T>::from(rng.next_u64().min(max).max(min));
1071			let two: BalanceOf<T> = 2u32.into();
1072
1073			assert_ok!(T::Currency::mint_into(&who, stake * two));
1074			assert_ok!(<Pallet<T>>::bond(
1075				T::RuntimeOrigin::from(Some(who.clone()).into()),
1076				stake,
1077				RewardDestination::Staked,
1078			));
1079			who
1080		}
1081	}
1082
1083	#[pallet::genesis_build]
1084	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
1085		fn build(&self) {
1086			crate::log!(trace, "initializing with {:?}", self);
1087			assert!(
1088				self.validator_count <=
1089					<T::ElectionProvider as ElectionProvider>::MaxWinnersPerPage::get() *
1090						<T::ElectionProvider as ElectionProvider>::Pages::get(),
1091				"validator count is too high, `ElectionProvider` can never fulfill this"
1092			);
1093			ValidatorCount::<T>::put(self.validator_count);
1094
1095			ForceEra::<T>::put(self.force_era);
1096			CanceledSlashPayout::<T>::put(self.canceled_payout);
1097			SlashRewardFraction::<T>::put(self.slash_reward_fraction);
1098			MinNominatorBond::<T>::put(self.min_nominator_bond);
1099			MinValidatorBond::<T>::put(self.min_validator_bond);
1100			if let Some(x) = self.max_validator_count {
1101				MaxValidatorsCount::<T>::put(x);
1102			}
1103			if let Some(x) = self.max_nominator_count {
1104				MaxNominatorsCount::<T>::put(x);
1105			}
1106
1107			// First pass: set up all validators and idle stakers
1108			for &(ref stash, balance, ref status) in &self.stakers {
1109				match status {
1110					crate::StakerStatus::Validator => {
1111						crate::log!(
1112							trace,
1113							"inserting genesis validator: {:?} => {:?} => {:?}",
1114							stash,
1115							balance,
1116							status
1117						);
1118						assert!(
1119							asset::free_to_stake::<T>(stash) >= balance,
1120							"Stash does not have enough balance to bond."
1121						);
1122						assert_ok!(<Pallet<T>>::bond(
1123							T::RuntimeOrigin::from(Some(stash.clone()).into()),
1124							balance,
1125							RewardDestination::Staked,
1126						));
1127						assert_ok!(<Pallet<T>>::validate(
1128							T::RuntimeOrigin::from(Some(stash.clone()).into()),
1129							Default::default(),
1130						));
1131					},
1132					crate::StakerStatus::Idle => {
1133						crate::log!(
1134							trace,
1135							"inserting genesis idle staker: {:?} => {:?} => {:?}",
1136							stash,
1137							balance,
1138							status
1139						);
1140						assert!(
1141							asset::free_to_stake::<T>(stash) >= balance,
1142							"Stash does not have enough balance to bond."
1143						);
1144						assert_ok!(<Pallet<T>>::bond(
1145							T::RuntimeOrigin::from(Some(stash.clone()).into()),
1146							balance,
1147							RewardDestination::Staked,
1148						));
1149					},
1150					_ => {},
1151				}
1152			}
1153
1154			// Second pass: set up all nominators (now that validators exist)
1155			for &(ref stash, balance, ref status) in &self.stakers {
1156				match status {
1157					crate::StakerStatus::Nominator(votes) => {
1158						crate::log!(
1159							trace,
1160							"inserting genesis nominator: {:?} => {:?} => {:?}",
1161							stash,
1162							balance,
1163							status
1164						);
1165						assert!(
1166							asset::free_to_stake::<T>(stash) >= balance,
1167							"Stash does not have enough balance to bond."
1168						);
1169						assert_ok!(<Pallet<T>>::bond(
1170							T::RuntimeOrigin::from(Some(stash.clone()).into()),
1171							balance,
1172							RewardDestination::Staked,
1173						));
1174						assert_ok!(<Pallet<T>>::nominate(
1175							T::RuntimeOrigin::from(Some(stash.clone()).into()),
1176							votes.iter().map(|l| T::Lookup::unlookup(l.clone())).collect(),
1177						));
1178					},
1179					_ => {},
1180				}
1181			}
1182
1183			// all voters are reported to the `VoterList`.
1184			assert_eq!(
1185				T::VoterList::count(),
1186				Nominators::<T>::count() + Validators::<T>::count(),
1187				"not all genesis stakers were inserted into sorted list provider, something is wrong."
1188			);
1189
1190			// now generate the dev stakers, after all else is setup
1191			if let Some((validators, nominators)) = self.dev_stakers {
1192				crate::log!(
1193					debug,
1194					"generating dev stakers: validators: {}, nominators: {}",
1195					validators,
1196					nominators
1197				);
1198				let base_derivation = "//staker//{}";
1199
1200				// it is okay for the randomness to be the same on every call. If we want different,
1201				// we can make `base_derivation` configurable.
1202				let mut rng =
1203					ChaChaRng::from_seed(base_derivation.using_encoded(sp_core::blake2_256));
1204
1205				(0..validators).for_each(|index| {
1206					let derivation = base_derivation.replace("{}", &format!("validator{}", index));
1207					let who = Self::generate_endowed_bonded_account(&derivation, &mut rng);
1208					assert_ok!(<Pallet<T>>::validate(
1209						T::RuntimeOrigin::from(Some(who.clone()).into()),
1210						Default::default(),
1211					));
1212				});
1213
1214				// This allows us to work with configs like `dev_stakers: (0, 10)`. Don't create new
1215				// validators, just add a bunch of nominators. Useful for slashing tests.
1216				let all_validators = Validators::<T>::iter_keys().collect::<Vec<_>>();
1217
1218				(0..nominators).for_each(|index| {
1219					let derivation = base_derivation.replace("{}", &format!("nominator{}", index));
1220					let who = Self::generate_endowed_bonded_account(&derivation, &mut rng);
1221
1222					let random_nominations = all_validators
1223						.choose_multiple(&mut rng, MaxNominationsOf::<T>::get() as usize)
1224						.map(|v| v.clone())
1225						.collect::<Vec<_>>();
1226
1227					assert_ok!(<Pallet<T>>::nominate(
1228						T::RuntimeOrigin::from(Some(who.clone()).into()),
1229						random_nominations.iter().map(|l| T::Lookup::unlookup(l.clone())).collect(),
1230					));
1231				})
1232			}
1233
1234			let (active_era, session_index, timestamp) = self.active_era;
1235			ActiveEra::<T>::put(ActiveEraInfo { index: active_era, start: Some(timestamp) });
1236			// at genesis, we do not have any new planned era.
1237			CurrentEra::<T>::put(active_era);
1238			// set the bonded genesis era
1239			BondedEras::<T>::put(
1240				BoundedVec::<_, BondedErasBound<T>>::try_from(
1241					alloc::vec![(active_era, session_index)]
1242				)
1243				.expect("bound for BondedEras is BondingDuration + 1; can contain at least one element; qed")
1244			);
1245		}
1246	}
1247
1248	#[pallet::event]
1249	#[pallet::generate_deposit(pub fn deposit_event)]
1250	pub enum Event<T: Config> {
1251		/// The era payout has been set.
1252		///
1253		/// In non-minting mode, `validator_payout` is the staker reward budget
1254		/// snapshotted from the general pot, and `remainder` is always zero.
1255		/// In legacy minting mode, both fields reflect the `EraPayout` computation.
1256		EraPaid {
1257			era_index: EraIndex,
1258			validator_payout: BalanceOf<T>,
1259			remainder: BalanceOf<T>,
1260		},
1261		/// The nominator has been rewarded by this amount to this destination.
1262		Rewarded {
1263			stash: T::AccountId,
1264			dest: RewardDestination<T::AccountId>,
1265			amount: BalanceOf<T>,
1266		},
1267		/// A staker (validator or nominator) has been slashed by the given amount.
1268		Slashed {
1269			staker: T::AccountId,
1270			amount: BalanceOf<T>,
1271		},
1272		/// An old slashing report from a prior era was discarded because it could
1273		/// not be processed.
1274		OldSlashingReportDiscarded {
1275			session_index: SessionIndex,
1276		},
1277		/// An account has bonded this amount. \[stash, amount\]
1278		///
1279		/// NOTE: This event is only emitted when funds are bonded via a dispatchable. Notably,
1280		/// it will not be emitted for staking rewards when they are added to stake.
1281		Bonded {
1282			stash: T::AccountId,
1283			amount: BalanceOf<T>,
1284		},
1285		/// An account has unbonded this amount.
1286		Unbonded {
1287			stash: T::AccountId,
1288			amount: BalanceOf<T>,
1289		},
1290		/// An account has called `withdraw_unbonded` and removed unbonding chunks worth `Balance`
1291		/// from the unlocking queue.
1292		Withdrawn {
1293			stash: T::AccountId,
1294			amount: BalanceOf<T>,
1295		},
1296		/// A subsequent event of `Withdrawn`, indicating that `stash` was fully removed from the
1297		/// system.
1298		StakerRemoved {
1299			stash: T::AccountId,
1300		},
1301		/// A nominator has been kicked from a validator.
1302		Kicked {
1303			nominator: T::AccountId,
1304			stash: T::AccountId,
1305		},
1306		/// An account has stopped participating as either a validator or nominator.
1307		Chilled {
1308			stash: T::AccountId,
1309		},
1310		/// A Page of stakers rewards are getting paid. `next` is `None` if all pages are claimed.
1311		PayoutStarted {
1312			era_index: EraIndex,
1313			validator_stash: T::AccountId,
1314			page: Page,
1315			next: Option<Page>,
1316		},
1317		/// A validator has set their preferences.
1318		ValidatorPrefsSet {
1319			stash: T::AccountId,
1320			prefs: ValidatorPrefs,
1321		},
1322		/// Voters size limit reached.
1323		SnapshotVotersSizeExceeded {
1324			size: u32,
1325		},
1326		/// Targets size limit reached.
1327		SnapshotTargetsSizeExceeded {
1328			size: u32,
1329		},
1330		ForceEra {
1331			mode: Forcing,
1332		},
1333		/// Report of a controller batch deprecation.
1334		ControllerBatchDeprecated {
1335			failures: u32,
1336		},
1337		/// Staking balance migrated from locks to holds, with any balance that could not be held
1338		/// is force withdrawn.
1339		CurrencyMigrated {
1340			stash: T::AccountId,
1341			force_withdraw: BalanceOf<T>,
1342		},
1343		/// A page from a multi-page election was fetched. A number of these are followed by
1344		/// `StakersElected`.
1345		///
1346		/// `Ok(count)` indicates the give number of stashes were added.
1347		/// `Err(index)` indicates that the stashes after index were dropped.
1348		/// `Err(0)` indicates that an error happened but no stashes were dropped nor added.
1349		///
1350		/// The error indicates that a number of validators were dropped due to excess size, but
1351		/// the overall election will continue.
1352		PagedElectionProceeded {
1353			page: PageIndex,
1354			result: Result<u32, u32>,
1355		},
1356		/// An offence for the given validator, for the given percentage of their stake, at the
1357		/// given era as been reported.
1358		OffenceReported {
1359			offence_era: EraIndex,
1360			validator: T::AccountId,
1361			fraction: Perbill,
1362		},
1363		/// An offence has been processed and the corresponding slash has been computed.
1364		SlashComputed {
1365			offence_era: EraIndex,
1366			slash_era: EraIndex,
1367			offender: T::AccountId,
1368			page: u32,
1369		},
1370		/// An unapplied slash has been cancelled.
1371		SlashCancelled {
1372			slash_era: EraIndex,
1373			validator: T::AccountId,
1374		},
1375		/// Session change has been triggered.
1376		///
1377		/// If planned_era is one era ahead of active_era, it implies new era is being planned and
1378		/// election is ongoing.
1379		SessionRotated {
1380			starting_session: SessionIndex,
1381			active_era: EraIndex,
1382			planned_era: EraIndex,
1383		},
1384		/// Something occurred that should never happen under normal operation.
1385		/// Logged as an event for fail-safe observability.
1386		Unexpected(UnexpectedKind<T>),
1387		/// An offence was reported that was too old to be processed, and thus was dropped.
1388		OffenceTooOld {
1389			offence_era: EraIndex,
1390			validator: T::AccountId,
1391			fraction: Perbill,
1392		},
1393		/// An old era with the given index was pruned.
1394		EraPruned {
1395			index: EraIndex,
1396		},
1397		/// The validator has been paid their self-stake incentive bonus.
1398		ValidatorIncentivePaid {
1399			era: EraIndex,
1400			validator_stash: T::AccountId,
1401			dest: RewardDestination<T::AccountId>,
1402			amount: BalanceOf<T>,
1403		},
1404		/// Validator self-stake incentive configuration has been updated.
1405		ValidatorIncentiveConfigSet {
1406			optimum_self_stake: BalanceOf<T>,
1407			hard_cap_self_stake: BalanceOf<T>,
1408			slope_factor: Perbill,
1409		},
1410	}
1411
1412	/// Represents unexpected or invariant-breaking conditions encountered during execution.
1413	///
1414	/// These variants are emitted as [`Event::Unexpected`] and indicate a defensive check has
1415	/// failed. While these should never occur under normal operation, they are useful for
1416	/// diagnosing issues in production or test environments.
1417	#[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, TypeInfo, DebugNoBound)]
1418	#[codec(mel_bound())]
1419	#[scale_info(skip_type_params(T))]
1420	pub enum UnexpectedKind<T: Config> {
1421		/// Emitted when calculated era duration exceeds the configured maximum.
1422		EraDurationBoundExceeded,
1423		/// Received a validator activation event that is not recognized.
1424		UnknownValidatorActivation,
1425		/// Failed to proceed paged election due to weight limits
1426		PagedElectionOutOfWeight { page: PageIndex, required: Weight, had: Weight },
1427		/// Payee not set for a staker when paying rewards.
1428		MissingPayee { era: EraIndex, stash: T::AccountId },
1429		/// Total validator weight is zero but incentive allocation exists.
1430		ValidatorIncentiveWeightMismatch { era: EraIndex },
1431		/// Validator incentive transfer from era pot failed.
1432		ValidatorIncentiveTransferFailed { era: EraIndex },
1433	}
1434
1435	#[pallet::error]
1436	#[derive(PartialEq)]
1437	pub enum Error<T> {
1438		/// Not a controller account.
1439		NotController,
1440		/// Not a stash account.
1441		NotStash,
1442		/// Stash is already bonded.
1443		AlreadyBonded,
1444		/// Controller is already paired.
1445		AlreadyPaired,
1446		/// Targets cannot be empty.
1447		EmptyTargets,
1448		/// Duplicate index.
1449		DuplicateIndex,
1450		/// Slash record not found.
1451		InvalidSlashRecord,
1452		/// Cannot bond, nominate or validate with value less than the minimum defined by
1453		/// governance (see `MinValidatorBond` and `MinNominatorBond`). If unbonding is the
1454		/// intention, `chill` first to remove one's role as validator/nominator.
1455		InsufficientBond,
1456		/// Can not schedule more unlock chunks.
1457		NoMoreChunks,
1458		/// Can not rebond without unlocking chunks.
1459		NoUnlockChunk,
1460		/// Attempting to target a stash that still has funds.
1461		FundedTarget,
1462		/// Invalid era to reward.
1463		InvalidEraToReward,
1464		/// Invalid number of nominations.
1465		InvalidNumberOfNominations,
1466		/// Rewards for this era have already been claimed for this validator.
1467		AlreadyClaimed,
1468		/// No nominators exist on this page.
1469		InvalidPage,
1470		/// Incorrect previous history depth input provided.
1471		IncorrectHistoryDepth,
1472		/// Internal state has become somehow corrupted and the operation cannot continue.
1473		BadState,
1474		/// Too many nomination targets supplied.
1475		TooManyTargets,
1476		/// A nomination target was supplied that was blocked or otherwise not a validator.
1477		BadTarget,
1478		/// The user has enough bond and thus cannot be chilled forcefully by an external person.
1479		CannotChillOther,
1480		/// There are too many nominators in the system. Governance needs to adjust the staking
1481		/// settings to keep things safe for the runtime.
1482		TooManyNominators,
1483		/// There are too many validator candidates in the system. Governance needs to adjust the
1484		/// staking settings to keep things safe for the runtime.
1485		TooManyValidators,
1486		/// Commission is too low. Must be at least `MinCommission`.
1487		CommissionTooLow,
1488		/// Some bound is not met.
1489		BoundNotMet,
1490		/// Used when attempting to use deprecated controller account logic.
1491		ControllerDeprecated,
1492		/// Cannot reset a ledger.
1493		CannotRestoreLedger,
1494		/// Provided reward destination is not allowed.
1495		RewardDestinationRestricted,
1496		/// Not enough funds available to withdraw.
1497		NotEnoughFunds,
1498		/// Operation not allowed for virtual stakers.
1499		VirtualStakerNotAllowed,
1500		/// Stash could not be reaped as other pallet might depend on it.
1501		CannotReapStash,
1502		/// The stake of this account is already migrated to `Fungible` holds.
1503		AlreadyMigrated,
1504		/// Era not yet started.
1505		EraNotStarted,
1506		/// Account is restricted from participation in staking. This may happen if the account is
1507		/// staking in another way already, such as via pool.
1508		Restricted,
1509		/// Unapplied slashes in the recently concluded era is blocking this operation.
1510		/// See `Call::apply_slash` to apply them.
1511		UnappliedSlashesInPreviousEra,
1512		/// The era is not eligible for pruning.
1513		EraNotPrunable,
1514		/// The slash has been cancelled and cannot be applied.
1515		CancelledSlash,
1516		/// Commission is higher than the allowed maximum `MaxCommission`.
1517		CommissionTooHigh,
1518		/// Optimum self-stake cannot be greater than hard cap.
1519		OptimumGreaterThanCap,
1520	}
1521
1522	impl<T: Config> Pallet<T> {
1523		/// Apply previously-unapplied slashes on the beginning of a new era, after a delay.
1524		pub fn apply_unapplied_slashes(active_era: EraIndex) -> Weight {
1525			let mut slashes = UnappliedSlashes::<T>::iter_prefix(&active_era).take(1);
1526			if let Some((key, slash)) = slashes.next() {
1527				crate::log!(
1528					debug,
1529					"🦹 found slash {:?} scheduled to be executed in era {:?}",
1530					slash,
1531					active_era,
1532				);
1533
1534				let nominators_slashed = slash.others.len() as u32;
1535
1536				// Check if this slash has been cancelled
1537				if Self::check_slash_cancelled(active_era, &key.0, key.1) {
1538					crate::log!(
1539						debug,
1540						"🦹 slash for {:?} in era {:?} was cancelled, skipping",
1541						key.0,
1542						active_era,
1543					);
1544				} else {
1545					slashing::apply_slash::<T>(slash, Self::offence_era_of(active_era));
1546				}
1547
1548				// Always remove the slash from UnappliedSlashes
1549				UnappliedSlashes::<T>::remove(&active_era, &key);
1550
1551				// Check if there are more slashes for this era
1552				if UnappliedSlashes::<T>::iter_prefix(&active_era).next().is_none() {
1553					// No more slashes for this era, clear CancelledSlashes
1554					CancelledSlashes::<T>::remove(&active_era);
1555				}
1556
1557				T::WeightInfo::apply_slash(nominators_slashed)
1558			} else {
1559				// No slashes found for this era
1560				T::DbWeight::get().reads(1)
1561			}
1562		}
1563
1564		/// Execute one step of era pruning and get actual weight used
1565		fn do_prune_era_step(era: EraIndex) -> Result<Weight, DispatchError> {
1566			// Get current pruning state. If EraPruningState doesn't exist, it means:
1567			// - Era was never marked for pruning, OR
1568			// - Era was already fully pruned (pruning state was removed on final step)
1569			// In either case, this is an error - user should not call prune on non-prunable eras
1570			let current_step = EraPruningState::<T>::get(era).ok_or(Error::<T>::EraNotPrunable)?;
1571
1572			// Limit items to prevent deleting more than we can safely account for in weight
1573			// calculations
1574			let items_limit = T::MaxPruningItems::get().min(T::MaxValidatorSet::get());
1575
1576			let actual_weight = match current_step {
1577				PruningStep::ErasStakersPaged => {
1578					let result = ErasStakersPaged::<T>::clear_prefix((era,), items_limit, None);
1579					let items_deleted = result.backend as u32;
1580					result.maybe_cursor.is_none().then(|| {
1581						EraPruningState::<T>::insert(era, PruningStep::ErasStakersOverview)
1582					});
1583					T::WeightInfo::prune_era_stakers_paged(items_deleted)
1584				},
1585				PruningStep::ErasStakersOverview => {
1586					let result = ErasStakersOverview::<T>::clear_prefix(era, items_limit, None);
1587					let items_deleted = result.backend as u32;
1588					result.maybe_cursor.is_none().then(|| {
1589						EraPruningState::<T>::insert(era, PruningStep::ErasValidatorPrefs)
1590					});
1591					T::WeightInfo::prune_era_stakers_overview(items_deleted)
1592				},
1593				PruningStep::ErasValidatorPrefs => {
1594					let result = ErasValidatorPrefs::<T>::clear_prefix(era, items_limit, None);
1595					let items_deleted = result.backend as u32;
1596					result
1597						.maybe_cursor
1598						.is_none()
1599						.then(|| EraPruningState::<T>::insert(era, PruningStep::ClaimedRewards));
1600					T::WeightInfo::prune_era_validator_prefs(items_deleted)
1601				},
1602				PruningStep::ClaimedRewards => {
1603					let result = ClaimedRewards::<T>::clear_prefix(era, items_limit, None);
1604					let items_deleted = result.backend as u32;
1605					result.maybe_cursor.is_none().then(|| {
1606						EraPruningState::<T>::insert(era, PruningStep::ErasValidatorReward)
1607					});
1608					T::WeightInfo::prune_era_claimed_rewards(items_deleted)
1609				},
1610				PruningStep::ErasValidatorReward => {
1611					ErasValidatorReward::<T>::remove(era);
1612					EraPruningState::<T>::insert(era, PruningStep::ErasRewardPoints);
1613					T::WeightInfo::prune_era_validator_reward()
1614				},
1615				PruningStep::ErasRewardPoints => {
1616					ErasRewardPoints::<T>::remove(era);
1617					EraPruningState::<T>::insert(era, PruningStep::SingleEntryCleanups);
1618					T::WeightInfo::prune_era_reward_points()
1619				},
1620				PruningStep::SingleEntryCleanups => {
1621					ErasTotalStake::<T>::remove(era);
1622					ErasNominatorsSlashable::<T>::remove(era);
1623					ErasValidatorIncentiveBudget::<T>::remove(era);
1624					ErasSumValidatorIncentiveWeight::<T>::remove(era);
1625					EraPruningState::<T>::insert(era, PruningStep::ValidatorSlashInEra);
1626					T::WeightInfo::prune_era_single_entry_cleanups()
1627				},
1628				PruningStep::ValidatorSlashInEra => {
1629					let result = ValidatorSlashInEra::<T>::clear_prefix(era, items_limit, None);
1630					let items_deleted = result.backend as u32;
1631
1632					if result.maybe_cursor.is_none() {
1633						EraPruningState::<T>::insert(
1634							era,
1635							PruningStep::ErasValidatorIncentiveWeight,
1636						);
1637					}
1638
1639					T::WeightInfo::prune_era_validator_slash_in_era(items_deleted)
1640				},
1641				PruningStep::ErasValidatorIncentiveWeight => {
1642					let result =
1643						ErasValidatorIncentiveWeight::<T>::clear_prefix(era, items_limit, None);
1644					if result.maybe_cursor.is_none() {
1645						// Final step — remove pruning state.
1646						EraPruningState::<T>::remove(era);
1647					}
1648					T::WeightInfo::prune_era_validator_incentive_weight(result.backend as u32)
1649				},
1650			};
1651
1652			// Check if era is fully pruned (pruning state removed) and emit event
1653			if EraPruningState::<T>::get(era).is_none() {
1654				Self::deposit_event(Event::<T>::EraPruned { index: era });
1655			}
1656
1657			Ok(actual_weight)
1658		}
1659	}
1660
1661	#[pallet::hooks]
1662	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
1663		fn on_poll(_now: BlockNumberFor<T>, weight_meter: &mut WeightMeter) {
1664			let (weight, exec) = EraElectionPlanner::<T>::maybe_fetch_election_results();
1665			crate::log!(
1666				trace,
1667				"weight of fetching next election page is {:?}, have {:?}",
1668				weight,
1669				weight_meter.remaining()
1670			);
1671
1672			if weight_meter.can_consume(weight) {
1673				exec(weight_meter);
1674			} else {
1675				Self::deposit_event(Event::<T>::Unexpected(
1676					UnexpectedKind::PagedElectionOutOfWeight {
1677						page: NextElectionPage::<T>::get().unwrap_or(
1678							EraElectionPlanner::<T>::election_pages().defensive_saturating_sub(1),
1679						),
1680						required: weight,
1681						had: weight_meter.remaining(),
1682					},
1683				));
1684			}
1685		}
1686
1687		fn on_initialize(_now: BlockNumberFor<T>) -> Weight {
1688			// Process our queue, using the era-specific nominators slashable setting.
1689			let mut consumed_weight = slashing::process_offence_for_era::<T>();
1690
1691			// apply any pending slashes after `SlashDeferDuration`.
1692			consumed_weight.saturating_accrue(T::DbWeight::get().reads(1));
1693			if let Some(active_era) = ActiveEra::<T>::get() {
1694				let slash_weight = Self::apply_unapplied_slashes(active_era.index);
1695				consumed_weight.saturating_accrue(slash_weight);
1696			}
1697
1698			consumed_weight
1699		}
1700
1701		fn integrity_test() {
1702			// ensure that we funnel the correct value to the `DataProvider::MaxVotesPerVoter`;
1703			assert_eq!(
1704				MaxNominationsOf::<T>::get(),
1705				<Self as ElectionDataProvider>::MaxVotesPerVoter::get()
1706			);
1707
1708			// and that MaxNominations is always greater than 1, since we count on this.
1709			assert!(!MaxNominationsOf::<T>::get().is_zero());
1710
1711			assert!(
1712				T::SlashDeferDuration::get() < T::BondingDuration::get() || T::BondingDuration::get() == 0,
1713				"As per documentation, slash defer duration ({}) should be less than bonding duration ({}).",
1714				T::SlashDeferDuration::get(),
1715				T::BondingDuration::get(),
1716			);
1717
1718			// Ensure NominatorFastUnbondDuration is not greater than BondingDuration
1719			assert!(
1720				T::NominatorFastUnbondDuration::get() <= T::BondingDuration::get(),
1721				"NominatorFastUnbondDuration ({}) must not exceed BondingDuration ({}).",
1722				T::NominatorFastUnbondDuration::get(),
1723				T::BondingDuration::get(),
1724			);
1725			// Ensure MaxPruningItems is reasonable (minimum 100 for efficiency)
1726			assert!(
1727				T::MaxPruningItems::get() >= 100,
1728				"MaxPruningItems must be at least 100 for efficient pruning, got: {}",
1729				T::MaxPruningItems::get()
1730			);
1731
1732			assert!(
1733				crate::POT_POOL_SIZE > T::HistoryDepth::get(),
1734				"POT_POOL_SIZE ({}) must be strictly greater than HistoryDepth ({}) \
1735				 to avoid reusing a pot slot whose era is still in the active history.",
1736				crate::POT_POOL_SIZE,
1737				T::HistoryDepth::get(),
1738			);
1739
1740			// If minting is disabled, EraPayout must be a noop to prevent double-minting.
1741			if T::DisableMinting::get() {
1742				let (v, r) = T::EraPayout::era_payout(
1743					BalanceOf::<T>::from(1u64),
1744					BalanceOf::<T>::from(1u64),
1745					1000u64,
1746				);
1747				assert!(
1748					v.is_zero() && r.is_zero(),
1749					"DisableMinting is true but EraPayout returns non-zero. \
1750					 Set EraPayout = () when DisableMinting = true."
1751				);
1752			}
1753		}
1754
1755		#[cfg(feature = "try-runtime")]
1756		fn try_state(n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
1757			Self::do_try_state(n)
1758		}
1759	}
1760
1761	#[pallet::call]
1762	impl<T: Config> Pallet<T> {
1763		/// Take the origin account as a stash and lock up `value` of its balance. `controller` will
1764		/// be the account that controls it.
1765		///
1766		/// `value` must be more than the `minimum_balance` specified by `T::Currency`.
1767		///
1768		/// The dispatch origin for this call must be _Signed_ by the stash account.
1769		///
1770		/// Emits `Bonded`.
1771		///
1772		/// NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned
1773		/// unless the `origin` falls below _existential deposit_ (or equal to 0) and gets removed
1774		/// as dust.
1775		#[pallet::call_index(0)]
1776		#[pallet::weight(T::WeightInfo::bond())]
1777		pub fn bond(
1778			origin: OriginFor<T>,
1779			#[pallet::compact] value: BalanceOf<T>,
1780			payee: RewardDestination<T::AccountId>,
1781		) -> DispatchResult {
1782			let stash = ensure_signed(origin)?;
1783
1784			ensure!(!T::Filter::contains(&stash), Error::<T>::Restricted);
1785
1786			if StakingLedger::<T>::is_bonded(StakingAccount::Stash(stash.clone())) {
1787				return Err(Error::<T>::AlreadyBonded.into());
1788			}
1789
1790			// An existing controller cannot become a stash.
1791			if StakingLedger::<T>::is_bonded(StakingAccount::Controller(stash.clone())) {
1792				return Err(Error::<T>::AlreadyPaired.into());
1793			}
1794
1795			// Reject a bond which is lower than the minimum bond.
1796			if value < Self::min_chilled_bond() {
1797				return Err(Error::<T>::InsufficientBond.into());
1798			}
1799
1800			let stash_balance = asset::free_to_stake::<T>(&stash);
1801			let value = value.min(stash_balance);
1802			Self::deposit_event(Event::<T>::Bonded { stash: stash.clone(), amount: value });
1803			let ledger = StakingLedger::<T>::new(stash.clone(), value);
1804
1805			// You're auto-bonded forever, here. We might improve this by only bonding when
1806			// you actually validate/nominate and remove once you unbond __everything__.
1807			ledger.bond(payee)?;
1808
1809			Ok(())
1810		}
1811
1812		/// Add some extra amount that have appeared in the stash `free_balance` into the balance up
1813		/// for staking.
1814		///
1815		/// The dispatch origin for this call must be _Signed_ by the stash, not the controller.
1816		///
1817		/// Use this if there are additional funds in your stash account that you wish to bond.
1818		/// Unlike [`bond`](Self::bond) or [`unbond`](Self::unbond) this function does not impose
1819		/// any limitation on the amount that can be added.
1820		///
1821		/// Emits `Bonded`.
1822		#[pallet::call_index(1)]
1823		#[pallet::weight(T::WeightInfo::bond_extra())]
1824		pub fn bond_extra(
1825			origin: OriginFor<T>,
1826			#[pallet::compact] max_additional: BalanceOf<T>,
1827		) -> DispatchResult {
1828			let stash = ensure_signed(origin)?;
1829			ensure!(!T::Filter::contains(&stash), Error::<T>::Restricted);
1830			Self::do_bond_extra(&stash, max_additional)
1831		}
1832
1833		/// Schedule a portion of the stash to be unlocked ready for transfer out after the bond
1834		/// period ends. If this leaves an amount actively bonded less than
1835		/// [`asset::existential_deposit`], then it is increased to the full amount.
1836		///
1837		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
1838		///
1839		/// Once the unlock period is done, you can call `withdraw_unbonded` to actually move
1840		/// the funds out of management ready for transfer.
1841		///
1842		/// No more than a limited number of unlocking chunks (see `MaxUnlockingChunks`)
1843		/// can co-exists at the same time. If there are no unlocking chunks slots available
1844		/// [`Call::withdraw_unbonded`] is called to remove some of the chunks (if possible).
1845		///
1846		/// If a user encounters the `InsufficientBond` error when calling this extrinsic,
1847		/// they should call `chill` first in order to free up their bonded funds.
1848		///
1849		/// Emits `Unbonded`.
1850		///
1851		/// See also [`Call::withdraw_unbonded`].
1852		#[pallet::call_index(2)]
1853		#[pallet::weight(
1854            T::WeightInfo::withdraw_unbonded_kill().saturating_add(T::WeightInfo::unbond()))
1855        ]
1856		pub fn unbond(
1857			origin: OriginFor<T>,
1858			#[pallet::compact] value: BalanceOf<T>,
1859		) -> DispatchResultWithPostInfo {
1860			let controller = ensure_signed(origin)?;
1861			let unlocking =
1862				Self::ledger(Controller(controller.clone())).map(|l| l.unlocking.len())?;
1863
1864			// if there are no unlocking chunks available, try to remove any chunks by withdrawing
1865			// funds that have fully unbonded.
1866			let maybe_withdraw_weight = {
1867				if unlocking == T::MaxUnlockingChunks::get() as usize {
1868					Some(Self::do_withdraw_unbonded(&controller)?)
1869				} else {
1870					None
1871				}
1872			};
1873
1874			// we need to fetch the ledger again because it may have been mutated in the call
1875			// to `Self::do_withdraw_unbonded` above.
1876			let mut ledger = Self::ledger(Controller(controller))?;
1877			let mut value = value.min(ledger.active);
1878			let stash = ledger.stash.clone();
1879
1880			// If unbonding all active stake, chill the stash first to avoid `InsufficientBond`
1881			// errors. This matches the behavior of pallet-staking.
1882			let chill_weight = if value >= ledger.active {
1883				Self::chill_stash(&stash);
1884				T::WeightInfo::chill()
1885			} else {
1886				Weight::zero()
1887			};
1888
1889			ensure!(
1890				ledger.unlocking.len() < T::MaxUnlockingChunks::get() as usize,
1891				Error::<T>::NoMoreChunks,
1892			);
1893
1894			if !value.is_zero() {
1895				ledger.active -= value;
1896
1897				// Avoid there being a dust balance left in the staking system.
1898				if ledger.active < asset::existential_deposit::<T>() {
1899					value += ledger.active;
1900					ledger.active = Zero::zero();
1901				}
1902
1903				let is_nominator = Nominators::<T>::contains_key(&stash);
1904
1905				let min_active_bond = if is_nominator {
1906					Self::min_nominator_bond()
1907				} else if Validators::<T>::contains_key(&stash) {
1908					Self::min_validator_bond()
1909				} else {
1910					// staker is chilled, no min bond.
1911					Zero::zero()
1912				};
1913
1914				// Make sure that the user maintains enough active bond for their role.
1915				// If a user runs into this error, they should chill first.
1916				ensure!(ledger.active >= min_active_bond, Error::<T>::InsufficientBond);
1917
1918				// Determine unbonding duration based on validator history.
1919				// If the account was a validator in recent eras (within BondingDuration), they must
1920				// wait the full BondingDuration even if they've switched to nominator role.
1921				// This prevents validators from avoiding slashing by switching roles and using the
1922				// shorter nominator unbonding period.
1923				let active_era = session_rotation::Rotator::<T>::active_era();
1924				let was_recent_validator = LastValidatorEra::<T>::get(&stash)
1925					.map(|last_era| active_era.saturating_sub(last_era) < T::BondingDuration::get())
1926					.unwrap_or(false);
1927
1928				let unbond_duration = if was_recent_validator {
1929					// Use full bonding duration for recent validators
1930					T::BondingDuration::get()
1931				} else {
1932					// Use nominator bonding duration for pure nominators
1933					<Self as sp_staking::StakingInterface>::nominator_bonding_duration()
1934				};
1935
1936				let era =
1937					session_rotation::Rotator::<T>::active_era().saturating_add(unbond_duration);
1938				if let Some(chunk) = ledger.unlocking.last_mut().filter(|chunk| chunk.era == era) {
1939					// To keep the chunk count down, we only keep one chunk per era. Since
1940					// `unlocking` is a FiFo queue, if a chunk exists for `era` we know that it will
1941					// be the last one.
1942					chunk.value = chunk.value.defensive_saturating_add(value)
1943				} else {
1944					ledger
1945						.unlocking
1946						.try_push(UnlockChunk { value, era })
1947						.map_err(|_| Error::<T>::NoMoreChunks)?;
1948				};
1949				// NOTE: ledger must be updated prior to calling `Self::weight_of`.
1950				ledger.update()?;
1951
1952				// update this staker in the sorted list, if they exist in it.
1953				if T::VoterList::contains(&stash) {
1954					let _ = T::VoterList::on_update(&stash, Self::weight_of(&stash));
1955				}
1956
1957				Self::deposit_event(Event::<T>::Unbonded { stash, amount: value });
1958			}
1959
1960			let actual_weight = if let Some(withdraw_weight) = maybe_withdraw_weight {
1961				Some(
1962					T::WeightInfo::unbond()
1963						.saturating_add(withdraw_weight)
1964						.saturating_add(chill_weight),
1965				)
1966			} else {
1967				Some(T::WeightInfo::unbond().saturating_add(chill_weight))
1968			};
1969
1970			Ok(actual_weight.into())
1971		}
1972
1973		/// Remove any stake that has been fully unbonded and is ready for withdrawal.
1974		///
1975		/// Stake is considered fully unbonded once [`Config::BondingDuration`] has elapsed since
1976		/// the unbonding was initiated. In rare cases—such as when offences for the unbonded era
1977		/// have been reported but not yet processed—withdrawal is restricted to eras for which
1978		/// all offences have been processed.
1979		///
1980		/// The unlocked stake will be returned as free balance in the stash account.
1981		///
1982		/// The dispatch origin for this call must be _Signed_ by the controller.
1983		///
1984		/// Emits `Withdrawn`.
1985		///
1986		/// See also [`Call::unbond`].
1987		///
1988		/// ## Parameters
1989		///
1990		/// - `num_slashing_spans`: **Deprecated**. Retained only for backward compatibility; this
1991		///   parameter has no effect.
1992		#[pallet::call_index(3)]
1993		#[pallet::weight(T::WeightInfo::withdraw_unbonded_kill())]
1994		pub fn withdraw_unbonded(
1995			origin: OriginFor<T>,
1996			_num_slashing_spans: u32,
1997		) -> DispatchResultWithPostInfo {
1998			let controller = ensure_signed(origin)?;
1999
2000			let actual_weight = Self::do_withdraw_unbonded(&controller)?;
2001			Ok(Some(actual_weight).into())
2002		}
2003
2004		/// Declare the desire to validate for the origin controller.
2005		///
2006		/// Effects will be felt at the beginning of the next era.
2007		///
2008		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
2009		#[pallet::call_index(4)]
2010		#[pallet::weight(T::WeightInfo::validate())]
2011		pub fn validate(origin: OriginFor<T>, prefs: ValidatorPrefs) -> DispatchResult {
2012			let controller = ensure_signed(origin)?;
2013
2014			let ledger = Self::ledger(Controller(controller))?;
2015
2016			ensure!(ledger.active >= Self::min_validator_bond(), Error::<T>::InsufficientBond);
2017			let stash = &ledger.stash;
2018
2019			// ensure their commission is correct.
2020			ensure!(prefs.commission >= MinCommission::<T>::get(), Error::<T>::CommissionTooLow);
2021			ensure!(prefs.commission <= MaxCommission::<T>::get(), Error::<T>::CommissionTooHigh);
2022
2023			// Only check limits if they are not already a validator.
2024			if !Validators::<T>::contains_key(stash) {
2025				// If this error is reached, we need to adjust the `MinValidatorBond` and start
2026				// calling `chill_other`. Until then, we explicitly block new validators to protect
2027				// the runtime.
2028				if let Some(max_validators) = MaxValidatorsCount::<T>::get() {
2029					ensure!(
2030						Validators::<T>::count() < max_validators,
2031						Error::<T>::TooManyValidators
2032					);
2033				}
2034			}
2035
2036			Self::do_remove_nominator(stash);
2037			Self::do_add_validator(stash, prefs.clone());
2038			Self::deposit_event(Event::<T>::ValidatorPrefsSet { stash: ledger.stash, prefs });
2039
2040			Ok(())
2041		}
2042
2043		/// Declare the desire to nominate `targets` for the origin controller.
2044		///
2045		/// Effects will be felt at the beginning of the next era.
2046		///
2047		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
2048		#[pallet::call_index(5)]
2049		#[pallet::weight(T::WeightInfo::nominate(targets.len() as u32))]
2050		pub fn nominate(
2051			origin: OriginFor<T>,
2052			targets: Vec<AccountIdLookupOf<T>>,
2053		) -> DispatchResult {
2054			let controller = ensure_signed(origin)?;
2055
2056			let ledger = Self::ledger(StakingAccount::Controller(controller.clone()))?;
2057
2058			ensure!(ledger.active >= Self::min_nominator_bond(), Error::<T>::InsufficientBond);
2059			let stash = &ledger.stash;
2060
2061			// Only check limits if they are not already a nominator.
2062			if !Nominators::<T>::contains_key(stash) {
2063				// If this error is reached, we need to adjust the `MinNominatorBond` and start
2064				// calling `chill_other`. Until then, we explicitly block new nominators to protect
2065				// the runtime.
2066				if let Some(max_nominators) = MaxNominatorsCount::<T>::get() {
2067					ensure!(
2068						Nominators::<T>::count() < max_nominators,
2069						Error::<T>::TooManyNominators
2070					);
2071				}
2072			}
2073
2074			// dedup targets
2075			let mut targets = targets
2076				.into_iter()
2077				.map(|t| T::Lookup::lookup(t).map_err(DispatchError::from))
2078				.collect::<Result<Vec<_>, _>>()?;
2079			targets.sort();
2080			targets.dedup();
2081
2082			ensure!(!targets.is_empty(), Error::<T>::EmptyTargets);
2083			ensure!(
2084				targets.len() <= T::NominationsQuota::get_quota(ledger.active) as usize,
2085				Error::<T>::TooManyTargets
2086			);
2087
2088			let old = Nominators::<T>::get(stash).map_or_else(Vec::new, |x| x.targets.into_inner());
2089
2090			let targets: BoundedVec<_, _> = targets
2091				.into_iter()
2092				.map(|n| {
2093					if old.contains(&n) ||
2094						(Validators::<T>::contains_key(&n) && !Validators::<T>::get(&n).blocked)
2095					{
2096						Ok(n)
2097					} else {
2098						Err(Error::<T>::BadTarget.into())
2099					}
2100				})
2101				.collect::<Result<Vec<_>, DispatchError>>()?
2102				.try_into()
2103				.map_err(|_| Error::<T>::TooManyNominators)?;
2104
2105			let nominations = Nominations {
2106				targets,
2107				// Initial nominations are considered submitted at era 0. See `Nominations` doc.
2108				submitted_in: CurrentEra::<T>::get().unwrap_or(0),
2109				suppressed: false,
2110			};
2111
2112			Self::do_remove_validator(stash);
2113			Self::do_add_nominator(stash, nominations);
2114			Ok(())
2115		}
2116
2117		/// Declare no desire to either validate or nominate.
2118		///
2119		/// Effects will be felt at the beginning of the next era.
2120		///
2121		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
2122		///
2123		/// ## Complexity
2124		/// - Independent of the arguments. Insignificant complexity.
2125		/// - Contains one read.
2126		/// - Writes are limited to the `origin` account key.
2127		#[pallet::call_index(6)]
2128		#[pallet::weight(T::WeightInfo::chill())]
2129		pub fn chill(origin: OriginFor<T>) -> DispatchResult {
2130			let controller = ensure_signed(origin)?;
2131
2132			let ledger = Self::ledger(StakingAccount::Controller(controller))?;
2133
2134			Self::chill_stash(&ledger.stash);
2135			Ok(())
2136		}
2137
2138		/// (Re-)set the payment target for a controller.
2139		///
2140		/// Effects will be felt instantly (as soon as this function is completed successfully).
2141		///
2142		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
2143		#[pallet::call_index(7)]
2144		#[pallet::weight(T::WeightInfo::set_payee())]
2145		pub fn set_payee(
2146			origin: OriginFor<T>,
2147			payee: RewardDestination<T::AccountId>,
2148		) -> DispatchResult {
2149			let controller = ensure_signed(origin)?;
2150			let ledger = Self::ledger(Controller(controller.clone()))?;
2151
2152			ensure!(
2153				(payee != {
2154					#[allow(deprecated)]
2155					RewardDestination::Controller
2156				}),
2157				Error::<T>::ControllerDeprecated
2158			);
2159
2160			let _ = ledger
2161				.set_payee(payee)
2162				.defensive_proof("ledger was retrieved from storage, thus it's bonded; qed.")?;
2163
2164			Ok(())
2165		}
2166
2167		/// (Re-)sets the controller of a stash to the stash itself. This function previously
2168		/// accepted a `controller` argument to set the controller to an account other than the
2169		/// stash itself. This functionality has now been removed, now only setting the controller
2170		/// to the stash, if it is not already.
2171		///
2172		/// Effects will be felt instantly (as soon as this function is completed successfully).
2173		///
2174		/// The dispatch origin for this call must be _Signed_ by the stash, not the controller.
2175		#[pallet::call_index(8)]
2176		#[pallet::weight(T::WeightInfo::set_controller())]
2177		pub fn set_controller(origin: OriginFor<T>) -> DispatchResult {
2178			let stash = ensure_signed(origin)?;
2179
2180			Self::ledger(StakingAccount::Stash(stash.clone())).map(|ledger| {
2181				let controller = ledger.controller()
2182                    .defensive_proof("Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.")
2183                    .ok_or(Error::<T>::NotController)?;
2184
2185				if controller == stash {
2186					// Stash is already its own controller.
2187					return Err(Error::<T>::AlreadyPaired.into())
2188				}
2189
2190				let _ = ledger.set_controller_to_stash()?;
2191				Ok(())
2192			})?
2193		}
2194
2195		/// Sets the ideal number of validators.
2196		///
2197		/// The dispatch origin must be Root.
2198		#[pallet::call_index(9)]
2199		#[pallet::weight(T::WeightInfo::set_validator_count())]
2200		pub fn set_validator_count(
2201			origin: OriginFor<T>,
2202			#[pallet::compact] new: u32,
2203		) -> DispatchResult {
2204			ensure_root(origin)?;
2205
2206			ensure!(new <= T::MaxValidatorSet::get(), Error::<T>::TooManyValidators);
2207
2208			ValidatorCount::<T>::put(new);
2209			Ok(())
2210		}
2211
2212		/// Increments the ideal number of validators up to maximum of
2213		/// `T::MaxValidatorSet`.
2214		///
2215		/// The dispatch origin must be Root.
2216		#[pallet::call_index(10)]
2217		#[pallet::weight(T::WeightInfo::set_validator_count())]
2218		pub fn increase_validator_count(
2219			origin: OriginFor<T>,
2220			#[pallet::compact] additional: u32,
2221		) -> DispatchResult {
2222			ensure_root(origin)?;
2223			let old = ValidatorCount::<T>::get();
2224			let new = old.checked_add(additional).ok_or(ArithmeticError::Overflow)?;
2225
2226			ensure!(new <= T::MaxValidatorSet::get(), Error::<T>::TooManyValidators);
2227
2228			ValidatorCount::<T>::put(new);
2229			Ok(())
2230		}
2231
2232		/// Scale up the ideal number of validators by a factor up to maximum of
2233		/// `T::MaxValidatorSet`.
2234		///
2235		/// The dispatch origin must be Root.
2236		#[pallet::call_index(11)]
2237		#[pallet::weight(T::WeightInfo::set_validator_count())]
2238		pub fn scale_validator_count(origin: OriginFor<T>, factor: Percent) -> DispatchResult {
2239			ensure_root(origin)?;
2240			let old = ValidatorCount::<T>::get();
2241			let new = old.checked_add(factor.mul_floor(old)).ok_or(ArithmeticError::Overflow)?;
2242
2243			ensure!(new <= T::MaxValidatorSet::get(), Error::<T>::TooManyValidators);
2244
2245			ValidatorCount::<T>::put(new);
2246			Ok(())
2247		}
2248
2249		/// Force there to be no new eras indefinitely.
2250		///
2251		/// The dispatch origin must be Root.
2252		///
2253		/// # Warning
2254		///
2255		/// The election process starts multiple blocks before the end of the era.
2256		/// Thus the election process may be ongoing when this is called. In this case the
2257		/// election will continue until the next era is triggered.
2258		#[pallet::call_index(12)]
2259		#[pallet::weight(T::WeightInfo::force_no_eras())]
2260		pub fn force_no_eras(origin: OriginFor<T>) -> DispatchResult {
2261			ensure_root(origin)?;
2262			Self::set_force_era(Forcing::ForceNone);
2263			Ok(())
2264		}
2265
2266		/// Force there to be a new era at the end of the next session. After this, it will be
2267		/// reset to normal (non-forced) behaviour.
2268		///
2269		/// The dispatch origin must be Root.
2270		///
2271		/// # Warning
2272		///
2273		/// The election process starts multiple blocks before the end of the era.
2274		/// If this is called just before a new era is triggered, the election process may not
2275		/// have enough blocks to get a result.
2276		#[pallet::call_index(13)]
2277		#[pallet::weight(T::WeightInfo::force_new_era())]
2278		pub fn force_new_era(origin: OriginFor<T>) -> DispatchResult {
2279			ensure_root(origin)?;
2280			Self::set_force_era(Forcing::ForceNew);
2281			Ok(())
2282		}
2283
2284		/// Force a current staker to become completely unstaked, immediately.
2285		///
2286		/// The dispatch origin must be Root.
2287		/// ## Parameters
2288		///
2289		/// - `stash`: The stash account to be unstaked.
2290		/// - `num_slashing_spans`: **Deprecated**. This parameter is retained for backward
2291		/// compatibility. It no longer has any effect.
2292		#[pallet::call_index(15)]
2293		#[pallet::weight(T::WeightInfo::force_unstake())]
2294		pub fn force_unstake(
2295			origin: OriginFor<T>,
2296			stash: T::AccountId,
2297			_num_slashing_spans: u32,
2298		) -> DispatchResult {
2299			ensure_root(origin)?;
2300
2301			// Remove all staking-related information and lock.
2302			Self::kill_stash(&stash)?;
2303
2304			Ok(())
2305		}
2306
2307		/// Force there to be a new era at the end of sessions indefinitely.
2308		///
2309		/// The dispatch origin must be Root.
2310		///
2311		/// # Warning
2312		///
2313		/// The election process starts multiple blocks before the end of the era.
2314		/// If this is called just before a new era is triggered, the election process may not
2315		/// have enough blocks to get a result.
2316		#[pallet::call_index(16)]
2317		#[pallet::weight(T::WeightInfo::force_new_era_always())]
2318		pub fn force_new_era_always(origin: OriginFor<T>) -> DispatchResult {
2319			ensure_root(origin)?;
2320			Self::set_force_era(Forcing::ForceAlways);
2321			Ok(())
2322		}
2323
2324		/// Cancels scheduled slashes for a given era before they are applied.
2325		///
2326		/// This function allows `T::AdminOrigin` to cancel pending slashes for specified validators
2327		/// in a given era. The cancelled slashes are stored and will be checked when applying
2328		/// slashes.
2329		///
2330		/// ## Parameters
2331		/// - `era`: The staking era for which slashes should be cancelled. This is the era where
2332		///   the slash would be applied, not the era in which the offence was committed.
2333		/// - `validator_slashes`: A list of validator stash accounts and their slash fractions to
2334		///   be cancelled.
2335		#[pallet::call_index(17)]
2336		#[pallet::weight(T::WeightInfo::cancel_deferred_slash(validator_slashes.len() as u32))]
2337		pub fn cancel_deferred_slash(
2338			origin: OriginFor<T>,
2339			era: EraIndex,
2340			validator_slashes: Vec<(T::AccountId, Perbill)>,
2341		) -> DispatchResult {
2342			T::AdminOrigin::ensure_origin(origin)?;
2343			ensure!(!validator_slashes.is_empty(), Error::<T>::EmptyTargets);
2344
2345			// Get current cancelled slashes for this era
2346			let mut cancelled_slashes = CancelledSlashes::<T>::get(&era);
2347
2348			// Process each validator slash
2349			for (validator, slash_fraction) in validator_slashes {
2350				// Since this is gated by admin origin, we don't need to check if they are really
2351				// validators and trust governance to correctly set the parameters.
2352
2353				// Remove any existing entry for this validator
2354				cancelled_slashes.retain(|(v, _)| v != &validator);
2355
2356				// Add the validator with the specified slash fraction
2357				cancelled_slashes
2358					.try_push((validator.clone(), slash_fraction))
2359					.map_err(|_| Error::<T>::BoundNotMet)
2360					.defensive_proof("cancelled_slashes should have capacity for all validators")?;
2361
2362				Self::deposit_event(Event::<T>::SlashCancelled { slash_era: era, validator });
2363			}
2364
2365			// Update storage
2366			CancelledSlashes::<T>::insert(&era, cancelled_slashes);
2367
2368			Ok(())
2369		}
2370
2371		/// Pay out next page of the stakers behind a validator for the given era.
2372		///
2373		/// - `validator_stash` is the stash account of the validator.
2374		/// - `era` may be any era between `[current_era - history_depth; current_era]`.
2375		///
2376		/// The origin of this call must be _Signed_. Any account can call this function, even if
2377		/// it is not one of the stakers.
2378		///
2379		/// The reward payout could be paged in case there are too many nominators backing the
2380		/// `validator_stash`. This call will payout unpaid pages in an ascending order. To claim a
2381		/// specific page, use `payout_stakers_by_page`.`
2382		///
2383		/// If all pages are claimed, it returns an error `InvalidPage`.
2384		#[pallet::call_index(18)]
2385		#[pallet::weight(T::WeightInfo::payout_stakers_alive_staked(T::MaxExposurePageSize::get()))]
2386		pub fn payout_stakers(
2387			origin: OriginFor<T>,
2388			validator_stash: T::AccountId,
2389			era: EraIndex,
2390		) -> DispatchResultWithPostInfo {
2391			ensure_signed(origin)?;
2392
2393			Self::do_payout_stakers(validator_stash, era)
2394		}
2395
2396		/// Rebond a portion of the stash scheduled to be unlocked.
2397		///
2398		/// The dispatch origin must be signed by the controller.
2399		#[pallet::call_index(19)]
2400		#[pallet::weight(T::WeightInfo::rebond(T::MaxUnlockingChunks::get() as u32))]
2401		pub fn rebond(
2402			origin: OriginFor<T>,
2403			#[pallet::compact] value: BalanceOf<T>,
2404		) -> DispatchResultWithPostInfo {
2405			let controller = ensure_signed(origin)?;
2406			let ledger = Self::ledger(Controller(controller))?;
2407
2408			ensure!(!T::Filter::contains(&ledger.stash), Error::<T>::Restricted);
2409			ensure!(!ledger.unlocking.is_empty(), Error::<T>::NoUnlockChunk);
2410
2411			let initial_unlocking = ledger.unlocking.len() as u32;
2412			let (ledger, rebonded_value) = ledger.rebond(value);
2413			// Last check: the new active amount of ledger must be more than min bond.
2414			ensure!(ledger.active >= Self::min_chilled_bond(), Error::<T>::InsufficientBond);
2415
2416			Self::deposit_event(Event::<T>::Bonded {
2417				stash: ledger.stash.clone(),
2418				amount: rebonded_value,
2419			});
2420
2421			let stash = ledger.stash.clone();
2422			let final_unlocking = ledger.unlocking.len();
2423
2424			// NOTE: ledger must be updated prior to calling `Self::weight_of`.
2425			ledger.update()?;
2426			if T::VoterList::contains(&stash) {
2427				let _ = T::VoterList::on_update(&stash, Self::weight_of(&stash));
2428			}
2429
2430			let removed_chunks = 1u32 // for the case where the last iterated chunk is not removed
2431				.saturating_add(initial_unlocking)
2432				.saturating_sub(final_unlocking as u32);
2433			Ok(Some(T::WeightInfo::rebond(removed_chunks)).into())
2434		}
2435
2436		/// Remove all data structures concerning a staker/stash once it is at a state where it can
2437		/// be considered `dust` in the staking system. The requirements are:
2438		///
2439		/// 1. the `total_balance` of the stash is below `min_chilled_bond` or is zero.
2440		/// 2. or, the `ledger.total` of the stash is below `min_chilled_bond` or is zero.
2441		///
2442		/// The former can happen in cases like a slash; the latter when a fully unbonded account
2443		/// is still receiving staking rewards in `RewardDestination::Staked`.
2444		///
2445		/// It can be called by anyone, as long as `stash` meets the above requirements.
2446		///
2447		/// Refunds the transaction fees upon successful execution.
2448		///
2449		/// ## Parameters
2450		///
2451		/// - `stash`: The stash account to be reaped.
2452		/// - `num_slashing_spans`: **Deprecated**. This parameter is retained for backward
2453		/// compatibility. It no longer has any effect.
2454		#[pallet::call_index(20)]
2455		#[pallet::weight(T::WeightInfo::reap_stash())]
2456		pub fn reap_stash(
2457			origin: OriginFor<T>,
2458			stash: T::AccountId,
2459			_num_slashing_spans: u32,
2460		) -> DispatchResultWithPostInfo {
2461			let _ = ensure_signed(origin)?;
2462
2463			// virtual stakers should not be allowed to be reaped.
2464			ensure!(!Self::is_virtual_staker(&stash), Error::<T>::VirtualStakerNotAllowed);
2465
2466			let min_chilled_bond = Self::min_chilled_bond();
2467			let origin_balance = asset::total_balance::<T>(&stash);
2468			let ledger_total =
2469				Self::ledger(Stash(stash.clone())).map(|l| l.total).unwrap_or_default();
2470			let reapable = origin_balance < min_chilled_bond ||
2471				origin_balance.is_zero() ||
2472				ledger_total < min_chilled_bond ||
2473				ledger_total.is_zero();
2474			ensure!(reapable, Error::<T>::FundedTarget);
2475
2476			// Remove all staking-related information and lock.
2477			Self::kill_stash(&stash)?;
2478
2479			Ok(Pays::No.into())
2480		}
2481
2482		/// Remove the given nominations from the calling validator.
2483		///
2484		/// Effects will be felt at the beginning of the next era.
2485		///
2486		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
2487		///
2488		/// - `who`: A list of nominator stash accounts who are nominating this validator which
2489		///   should no longer be nominating this validator.
2490		///
2491		/// Note: Making this call only makes sense if you first set the validator preferences to
2492		/// block any further nominations.
2493		#[pallet::call_index(21)]
2494		#[pallet::weight(T::WeightInfo::kick(who.len() as u32))]
2495		pub fn kick(origin: OriginFor<T>, who: Vec<AccountIdLookupOf<T>>) -> DispatchResult {
2496			let controller = ensure_signed(origin)?;
2497			let ledger = Self::ledger(Controller(controller))?;
2498			let stash = &ledger.stash;
2499
2500			for nom_stash in who
2501				.into_iter()
2502				.map(T::Lookup::lookup)
2503				.collect::<Result<Vec<T::AccountId>, _>>()?
2504				.into_iter()
2505			{
2506				Nominators::<T>::mutate(&nom_stash, |maybe_nom| {
2507					if let Some(ref mut nom) = maybe_nom {
2508						if let Some(pos) = nom.targets.iter().position(|v| v == stash) {
2509							nom.targets.swap_remove(pos);
2510							Self::deposit_event(Event::<T>::Kicked {
2511								nominator: nom_stash.clone(),
2512								stash: stash.clone(),
2513							});
2514						}
2515					}
2516				});
2517			}
2518
2519			Ok(())
2520		}
2521
2522		/// Update the various staking configurations .
2523		///
2524		/// * `min_nominator_bond`: The minimum active bond needed to be a nominator.
2525		/// * `min_validator_bond`: The minimum active bond needed to be a validator.
2526		/// * `max_nominator_count`: The max number of users who can be a nominator at once. When
2527		///   set to `None`, no limit is enforced.
2528		/// * `max_validator_count`: The max number of users who can be a validator at once. When
2529		///   set to `None`, no limit is enforced.
2530		/// * `chill_threshold`: The ratio of `max_nominator_count` or `max_validator_count` which
2531		///   should be filled in order for the `chill_other` transaction to work.
2532		/// * `min_commission`: The minimum amount of commission that each validators must maintain.
2533		///   This is checked only upon calling `validate`. Existing validators are not affected.
2534		///
2535		/// RuntimeOrigin must be Root to call this function.
2536		///
2537		/// NOTE: Existing nominators and validators will not be affected by this update.
2538		/// to kick people under the new limits, `chill_other` should be called.
2539		// We assume the worst case for this call is either: all items are set or all items are
2540		// removed.
2541		#[pallet::call_index(22)]
2542		#[pallet::weight(
2543			T::WeightInfo::set_staking_configs_all_set()
2544				.max(T::WeightInfo::set_staking_configs_all_remove())
2545		)]
2546		pub fn set_staking_configs(
2547			origin: OriginFor<T>,
2548			min_nominator_bond: ConfigOp<BalanceOf<T>>,
2549			min_validator_bond: ConfigOp<BalanceOf<T>>,
2550			max_nominator_count: ConfigOp<u32>,
2551			max_validator_count: ConfigOp<u32>,
2552			chill_threshold: ConfigOp<Percent>,
2553			min_commission: ConfigOp<Perbill>,
2554			max_staked_rewards: ConfigOp<Percent>,
2555			are_nominators_slashable: ConfigOp<bool>,
2556		) -> DispatchResult {
2557			ensure_root(origin)?;
2558
2559			macro_rules! config_op_exp {
2560				($storage:ty, $op:ident) => {
2561					match $op {
2562						ConfigOp::Noop => (),
2563						ConfigOp::Set(v) => <$storage>::put(v),
2564						ConfigOp::Remove => <$storage>::kill(),
2565					}
2566				};
2567			}
2568
2569			config_op_exp!(MinNominatorBond<T>, min_nominator_bond);
2570			config_op_exp!(MinValidatorBond<T>, min_validator_bond);
2571			config_op_exp!(MaxNominatorsCount<T>, max_nominator_count);
2572			config_op_exp!(MaxValidatorsCount<T>, max_validator_count);
2573			config_op_exp!(ChillThreshold<T>, chill_threshold);
2574			config_op_exp!(MinCommission<T>, min_commission);
2575			config_op_exp!(MaxStakedRewards<T>, max_staked_rewards);
2576			config_op_exp!(AreNominatorsSlashable<T>, are_nominators_slashable);
2577			Ok(())
2578		}
2579		/// Declare a `controller` to stop participating as either a validator or nominator.
2580		///
2581		/// Effects will be felt at the beginning of the next era.
2582		///
2583		/// The dispatch origin for this call must be _Signed_, but can be called by anyone.
2584		///
2585		/// If the caller is the same as the controller being targeted, then no further checks are
2586		/// enforced, and this function behaves just like `chill`.
2587		///
2588		/// If the caller is different than the controller being targeted, the following conditions
2589		/// must be met:
2590		///
2591		/// * `controller` must belong to a nominator who has become non-decodable,
2592		///
2593		/// Or:
2594		///
2595		/// * A `ChillThreshold` must be set and checked which defines how close to the max
2596		///   nominators or validators we must reach before users can start chilling one-another.
2597		/// * A `MaxNominatorCount` and `MaxValidatorCount` must be set which is used to determine
2598		///   how close we are to the threshold.
2599		/// * A `MinNominatorBond` and `MinValidatorBond` must be set and checked, which determines
2600		///   if this is a person that should be chilled because they have not met the threshold
2601		///   bond required.
2602		///
2603		/// This can be helpful if bond requirements are updated, and we need to remove old users
2604		/// who do not satisfy these requirements.
2605		#[pallet::call_index(23)]
2606		#[pallet::weight(T::WeightInfo::chill_other())]
2607		pub fn chill_other(origin: OriginFor<T>, stash: T::AccountId) -> DispatchResult {
2608			// Anyone can call this function.
2609			let caller = ensure_signed(origin)?;
2610			let ledger = Self::ledger(Stash(stash.clone()))?;
2611			let controller = ledger
2612				.controller()
2613				.defensive_proof(
2614					"Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.",
2615				)
2616				.ok_or(Error::<T>::NotController)?;
2617
2618			// In order for one user to chill another user, the following conditions must be met:
2619			//
2620			// * `controller` belongs to a nominator who has become non-decodable,
2621			//
2622			// Or
2623			//
2624			// * A `ChillThreshold` is set which defines how close to the max nominators or
2625			//   validators we must reach before users can start chilling one-another.
2626			// * A `MaxNominatorCount` and `MaxValidatorCount` which is used to determine how close
2627			//   we are to the threshold.
2628			// * A `MinNominatorBond` and `MinValidatorBond` which is the final condition checked to
2629			//   determine this is a person that should be chilled because they have not met the
2630			//   threshold bond required.
2631			//
2632			// Otherwise, if caller is the same as the controller, this is just like `chill`.
2633
2634			if Nominators::<T>::contains_key(&stash) && Nominators::<T>::get(&stash).is_none() {
2635				Self::chill_stash(&stash);
2636				return Ok(());
2637			}
2638
2639			if caller != controller {
2640				let threshold = ChillThreshold::<T>::get().ok_or(Error::<T>::CannotChillOther)?;
2641				let min_active_bond = if Nominators::<T>::contains_key(&stash) {
2642					let max_nominator_count =
2643						MaxNominatorsCount::<T>::get().ok_or(Error::<T>::CannotChillOther)?;
2644					let current_nominator_count = Nominators::<T>::count();
2645					ensure!(
2646						threshold * max_nominator_count < current_nominator_count,
2647						Error::<T>::CannotChillOther
2648					);
2649					Self::min_nominator_bond()
2650				} else if Validators::<T>::contains_key(&stash) {
2651					let max_validator_count =
2652						MaxValidatorsCount::<T>::get().ok_or(Error::<T>::CannotChillOther)?;
2653					let current_validator_count = Validators::<T>::count();
2654					ensure!(
2655						threshold * max_validator_count < current_validator_count,
2656						Error::<T>::CannotChillOther
2657					);
2658					Self::min_validator_bond()
2659				} else {
2660					Zero::zero()
2661				};
2662
2663				ensure!(ledger.active < min_active_bond, Error::<T>::CannotChillOther);
2664			}
2665
2666			Self::chill_stash(&stash);
2667			Ok(())
2668		}
2669
2670		/// Clamps a validator's commission to the `[MinCommission, MaxCommission]` range.
2671		///
2672		/// Named `force_apply_min_commission` for legacy reasons — it also enforces the
2673		/// maximum. Any account can call this.
2674		#[pallet::call_index(24)]
2675		#[pallet::weight(T::WeightInfo::force_apply_min_commission())]
2676		pub fn force_apply_min_commission(
2677			origin: OriginFor<T>,
2678			validator_stash: T::AccountId,
2679		) -> DispatchResult {
2680			ensure_signed(origin)?;
2681			let min_commission = MinCommission::<T>::get();
2682			let max_commission = MaxCommission::<T>::get();
2683			Validators::<T>::try_mutate_exists(validator_stash, |maybe_prefs| {
2684				maybe_prefs
2685					.as_mut()
2686					.map(|prefs| {
2687						if prefs.commission < min_commission {
2688							prefs.commission = min_commission;
2689						}
2690						if prefs.commission > max_commission {
2691							prefs.commission = max_commission;
2692						}
2693					})
2694					.ok_or(Error::<T>::NotStash)
2695			})?;
2696			Ok(())
2697		}
2698
2699		/// Sets the minimum amount of commission that each validators must maintain.
2700		///
2701		/// This call has lower privilege requirements than `set_staking_config` and can be called
2702		/// by the `T::AdminOrigin`. Root can always call this.
2703		#[pallet::call_index(25)]
2704		#[pallet::weight(T::WeightInfo::set_min_commission())]
2705		pub fn set_min_commission(origin: OriginFor<T>, new: Perbill) -> DispatchResult {
2706			T::AdminOrigin::ensure_origin(origin)?;
2707			ensure!(new <= MaxCommission::<T>::get(), Error::<T>::CommissionTooHigh);
2708			MinCommission::<T>::put(new);
2709			Ok(())
2710		}
2711
2712		/// Pay out a page of the stakers behind a validator for the given era and page.
2713		///
2714		/// - `validator_stash` is the stash account of the validator.
2715		/// - `era` may be any era between `[current_era - history_depth; current_era]`.
2716		/// - `page` is the page index of nominators to pay out with value between 0 and
2717		///   `num_nominators / T::MaxExposurePageSize`.
2718		///
2719		/// The origin of this call must be _Signed_. Any account can call this function, even if
2720		/// it is not one of the stakers.
2721		///
2722		/// If a validator has more than [`Config::MaxExposurePageSize`] nominators backing
2723		/// them, then the list of nominators is paged, with each page being capped at
2724		/// [`Config::MaxExposurePageSize`]. If a validator has more than one page of nominators,
2725		/// the call needs to be made for each page separately in order for all the nominators
2726		/// backing a validator to receive the reward. The nominators are not sorted across pages
2727		/// and so it should not be assumed the highest staker would be on the topmost page and vice
2728		/// versa. If rewards are not claimed in [`Config::HistoryDepth`] eras, they are lost.
2729		///
2730		/// The validator's own reward (commission + own-stake share) is prorated across pages
2731		/// proportional to each page's stake. The full validator reward is the sum across all
2732		/// pages.
2733		#[pallet::call_index(26)]
2734		#[pallet::weight(T::WeightInfo::payout_stakers_alive_staked(T::MaxExposurePageSize::get()))]
2735		pub fn payout_stakers_by_page(
2736			origin: OriginFor<T>,
2737			validator_stash: T::AccountId,
2738			era: EraIndex,
2739			page: Page,
2740		) -> DispatchResultWithPostInfo {
2741			ensure_signed(origin)?;
2742			Self::do_payout_stakers_by_page(validator_stash, era, page)
2743		}
2744
2745		/// Migrates an account's `RewardDestination::Controller` to
2746		/// `RewardDestination::Account(controller)`.
2747		///
2748		/// Effects will be felt instantly (as soon as this function is completed successfully).
2749		///
2750		/// This will waive the transaction fee if the `payee` is successfully migrated.
2751		#[pallet::call_index(27)]
2752		#[pallet::weight(T::WeightInfo::update_payee())]
2753		pub fn update_payee(
2754			origin: OriginFor<T>,
2755			controller: T::AccountId,
2756		) -> DispatchResultWithPostInfo {
2757			let _ = ensure_signed(origin)?;
2758			let ledger = Self::ledger(StakingAccount::Controller(controller.clone()))?;
2759
2760			ensure!(
2761				(Payee::<T>::get(&ledger.stash) == {
2762					#[allow(deprecated)]
2763					Some(RewardDestination::Controller)
2764				}),
2765				Error::<T>::NotController
2766			);
2767
2768			let _ = ledger
2769				.set_payee(RewardDestination::Account(controller))
2770				.defensive_proof("ledger should have been previously retrieved from storage.")?;
2771
2772			Ok(Pays::No.into())
2773		}
2774
2775		/// Updates a batch of controller accounts to their corresponding stash account if they are
2776		/// not the same. Ignores any controller accounts that do not exist, and does not operate if
2777		/// the stash and controller are already the same.
2778		///
2779		/// Effects will be felt instantly (as soon as this function is completed successfully).
2780		///
2781		/// The dispatch origin must be `T::AdminOrigin`.
2782		#[pallet::call_index(28)]
2783		#[pallet::weight(T::WeightInfo::deprecate_controller_batch(controllers.len() as u32))]
2784		pub fn deprecate_controller_batch(
2785			origin: OriginFor<T>,
2786			controllers: BoundedVec<T::AccountId, T::MaxControllersInDeprecationBatch>,
2787		) -> DispatchResultWithPostInfo {
2788			T::AdminOrigin::ensure_origin(origin)?;
2789
2790			// Ignore controllers that do not exist or are already the same as stash.
2791			let filtered_batch_with_ledger: Vec<_> = controllers
2792				.iter()
2793				.filter_map(|controller| {
2794					let ledger = Self::ledger(StakingAccount::Controller(controller.clone()));
2795					ledger.ok().map_or(None, |ledger| {
2796						// If the controller `RewardDestination` is still the deprecated
2797						// `Controller` variant, skip deprecating this account.
2798						let payee_deprecated = Payee::<T>::get(&ledger.stash) == {
2799							#[allow(deprecated)]
2800							Some(RewardDestination::Controller)
2801						};
2802
2803						if ledger.stash != *controller && !payee_deprecated {
2804							Some(ledger)
2805						} else {
2806							None
2807						}
2808					})
2809				})
2810				.collect();
2811
2812			// Update unique pairs.
2813			let mut failures = 0;
2814			for ledger in filtered_batch_with_ledger {
2815				let _ = ledger.clone().set_controller_to_stash().map_err(|_| failures += 1);
2816			}
2817			Self::deposit_event(Event::<T>::ControllerBatchDeprecated { failures });
2818
2819			Ok(Some(T::WeightInfo::deprecate_controller_batch(controllers.len() as u32)).into())
2820		}
2821
2822		/// Restores the state of a ledger which is in an inconsistent state.
2823		///
2824		/// The requirements to restore a ledger are the following:
2825		/// * The stash is bonded; or
2826		/// * The stash is not bonded but it has a staking lock left behind; or
2827		/// * If the stash has an associated ledger and its state is inconsistent; or
2828		/// * If the ledger is not corrupted *but* its staking lock is out of sync.
2829		///
2830		/// The `maybe_*` input parameters will overwrite the corresponding data and metadata of the
2831		/// ledger associated with the stash. If the input parameters are not set, the ledger will
2832		/// be reset values from on-chain state.
2833		#[pallet::call_index(29)]
2834		#[pallet::weight(T::WeightInfo::restore_ledger())]
2835		pub fn restore_ledger(
2836			origin: OriginFor<T>,
2837			stash: T::AccountId,
2838			maybe_controller: Option<T::AccountId>,
2839			maybe_total: Option<BalanceOf<T>>,
2840			maybe_unlocking: Option<BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>>,
2841		) -> DispatchResult {
2842			T::AdminOrigin::ensure_origin(origin)?;
2843
2844			// cannot restore ledger for virtual stakers.
2845			ensure!(!Self::is_virtual_staker(&stash), Error::<T>::VirtualStakerNotAllowed);
2846
2847			let current_lock = asset::staked::<T>(&stash);
2848			let stash_balance = asset::stakeable_balance::<T>(&stash);
2849
2850			let (new_controller, new_total) = match Self::inspect_bond_state(&stash) {
2851				Ok(LedgerIntegrityState::Corrupted) => {
2852					let new_controller = maybe_controller.unwrap_or(stash.clone());
2853
2854					let new_total = if let Some(total) = maybe_total {
2855						let new_total = total.min(stash_balance);
2856						// enforce hold == ledger.amount.
2857						asset::update_stake::<T>(&stash, new_total)?;
2858						new_total
2859					} else {
2860						current_lock
2861					};
2862
2863					Ok((new_controller, new_total))
2864				},
2865				Ok(LedgerIntegrityState::CorruptedKilled) => {
2866					if current_lock == Zero::zero() {
2867						// this case needs to restore both lock and ledger, so the new total needs
2868						// to be given by the called since there's no way to restore the total
2869						// on-chain.
2870						ensure!(maybe_total.is_some(), Error::<T>::CannotRestoreLedger);
2871						Ok((
2872							stash.clone(),
2873							maybe_total.expect("total exists as per the check above; qed."),
2874						))
2875					} else {
2876						Ok((stash.clone(), current_lock))
2877					}
2878				},
2879				Ok(LedgerIntegrityState::LockCorrupted) => {
2880					// ledger is not corrupted but its locks are out of sync. In this case, we need
2881					// to enforce a new ledger.total and staking lock for this stash.
2882					let new_total =
2883						maybe_total.ok_or(Error::<T>::CannotRestoreLedger)?.min(stash_balance);
2884					asset::update_stake::<T>(&stash, new_total)?;
2885
2886					Ok((stash.clone(), new_total))
2887				},
2888				Err(Error::<T>::BadState) => {
2889					// the stash and ledger do not exist but lock is lingering.
2890					asset::kill_stake::<T>(&stash)?;
2891					ensure!(
2892						Self::inspect_bond_state(&stash) == Err(Error::<T>::NotStash),
2893						Error::<T>::BadState
2894					);
2895
2896					return Ok(());
2897				},
2898				Ok(LedgerIntegrityState::Ok) | Err(_) => Err(Error::<T>::CannotRestoreLedger),
2899			}?;
2900
2901			// re-bond stash and controller tuple.
2902			Bonded::<T>::insert(&stash, &new_controller);
2903
2904			// resoter ledger state.
2905			let mut ledger = StakingLedger::<T>::new(stash.clone(), new_total);
2906			ledger.controller = Some(new_controller);
2907			ledger.unlocking = maybe_unlocking.unwrap_or_default();
2908			ledger.update()?;
2909
2910			ensure!(
2911				Self::inspect_bond_state(&stash) == Ok(LedgerIntegrityState::Ok),
2912				Error::<T>::BadState
2913			);
2914			Ok(())
2915		}
2916
2917		/// Migrates permissionlessly a stash from locks to holds.
2918		///
2919		/// This removes the old lock on the stake and creates a hold on it atomically. If all
2920		/// stake cannot be held, the best effort is made to hold as much as possible. The remaining
2921		/// stake is removed from the ledger.
2922		///
2923		/// The fee is waived if the migration is successful.
2924		#[pallet::call_index(30)]
2925		#[pallet::weight(T::WeightInfo::migrate_currency())]
2926		pub fn migrate_currency(
2927			origin: OriginFor<T>,
2928			stash: T::AccountId,
2929		) -> DispatchResultWithPostInfo {
2930			let _ = ensure_signed(origin)?;
2931			Self::do_migrate_currency(&stash)?;
2932
2933			// Refund the transaction fee if successful.
2934			Ok(Pays::No.into())
2935		}
2936
2937		/// Manually and permissionlessly applies a deferred slash for a given era.
2938		///
2939		/// Normally, slashes are automatically applied shortly after the start of the `slash_era`.
2940		/// The automatic application of slashes is handled by the pallet's internal logic, and it
2941		/// tries to apply one slash page per block of the era.
2942		/// If for some reason, one era is not enough for applying all slash pages, the remaining
2943		/// slashes need to be manually (permissionlessly) applied.
2944		///
2945		/// For a given era x, if at era x+1, slashes are still unapplied, all withdrawals get
2946		/// blocked, and these need to be manually applied by calling this function.
2947		/// This function exists as a **fallback mechanism** for this extreme situation, but we
2948		/// never expect to encounter this in normal scenarios.
2949		///
2950		/// The parameters for this call can be queried by looking at the `UnappliedSlashes` storage
2951		/// for eras older than the active era.
2952		///
2953		/// ## Parameters
2954		/// - `slash_era`: The application era (`offence_era + SlashDeferDuration`), i.e. the key
2955		///   into [`UnappliedSlashes`].
2956		/// - `slash_key`: A unique identifier for the slash, represented as a tuple:
2957		///   - `stash`: The stash account of the validator being slashed.
2958		///   - `slash_fraction`: The fraction of the stake that was slashed.
2959		///   - `page_index`: The index of the exposure page being processed.
2960		///
2961		/// ## Behavior
2962		/// - The function is **permissionless**—anyone can call it.
2963		/// - The `slash_era` **must be the current era or a past era**.
2964		/// If it is in the future, the
2965		///   call fails with `EraNotStarted`.
2966		/// - The fee is waived if the slash is successfully applied.
2967		///
2968		/// ## Future Improvement
2969		/// - Implement an **off-chain worker (OCW) task** to automatically apply slashes when there
2970		///   is unused block space, improving efficiency.
2971		#[pallet::call_index(31)]
2972		#[pallet::weight(T::WeightInfo::apply_slash(T::MaxExposurePageSize::get()))]
2973		pub fn apply_slash(
2974			origin: OriginFor<T>,
2975			slash_era: EraIndex,
2976			slash_key: (T::AccountId, Perbill, u32),
2977		) -> DispatchResultWithPostInfo {
2978			let _ = ensure_signed(origin)?;
2979			let active_era = ActiveEra::<T>::get().map(|a| a.index).unwrap_or_default();
2980			ensure!(slash_era <= active_era, Error::<T>::EraNotStarted);
2981
2982			// Check if this slash has been cancelled
2983			ensure!(
2984				!Self::check_slash_cancelled(slash_era, &slash_key.0, slash_key.1),
2985				Error::<T>::CancelledSlash
2986			);
2987
2988			let unapplied_slash = UnappliedSlashes::<T>::take(&slash_era, &slash_key)
2989				.ok_or(Error::<T>::InvalidSlashRecord)?;
2990			slashing::apply_slash::<T>(unapplied_slash, Self::offence_era_of(slash_era));
2991
2992			Ok(Pays::No.into())
2993		}
2994
2995		/// Perform one step of era pruning to prevent PoV size exhaustion from unbounded deletions.
2996		///
2997		/// This extrinsic enables permissionless lazy pruning of era data by performing
2998		/// incremental deletion of storage items. Each call processes a limited number
2999		/// of items based on available block weight to avoid exceeding block limits.
3000		///
3001		/// Returns `Pays::No` when work is performed to incentivize regular maintenance.
3002		/// Anyone can call this to help maintain the chain's storage health.
3003		///
3004		/// The era must be eligible for pruning (older than HistoryDepth + 1).
3005		/// Check `EraPruningState` storage to see if an era needs pruning before calling.
3006		#[pallet::call_index(32)]
3007		// NOTE: as pre-dispatch weight, use the maximum of all possible pruning step weights
3008		#[pallet::weight({
3009			let v = T::MaxValidatorSet::get();
3010			T::WeightInfo::prune_era_stakers_paged(v)
3011				.max(T::WeightInfo::prune_era_stakers_overview(v))
3012				.max(T::WeightInfo::prune_era_validator_prefs(v))
3013				.max(T::WeightInfo::prune_era_claimed_rewards(v))
3014				.max(T::WeightInfo::prune_era_validator_reward())
3015				.max(T::WeightInfo::prune_era_reward_points())
3016				.max(T::WeightInfo::prune_era_single_entry_cleanups())
3017				.max(T::WeightInfo::prune_era_validator_slash_in_era(v))
3018				.max(T::WeightInfo::prune_era_validator_incentive_weight(v))
3019		})]
3020		pub fn prune_era_step(origin: OriginFor<T>, era: EraIndex) -> DispatchResultWithPostInfo {
3021			let _ = ensure_signed(origin)?;
3022
3023			// Verify era is eligible for pruning: era <= active_era - history_depth - 1
3024			let active_era = crate::session_rotation::Rotator::<T>::active_era();
3025			let history_depth = T::HistoryDepth::get();
3026			let earliest_prunable_era = active_era.saturating_sub(history_depth).saturating_sub(1);
3027			ensure!(era <= earliest_prunable_era, Error::<T>::EraNotPrunable);
3028
3029			let actual_weight = Self::do_prune_era_step(era)?;
3030
3031			Ok(frame_support::dispatch::PostDispatchInfo {
3032				actual_weight: Some(actual_weight),
3033				pays_fee: frame_support::dispatch::Pays::No,
3034			})
3035		}
3036
3037		/// Sets the maximum commission that validators can set.
3038		///
3039		/// The dispatch origin must be `T::AdminOrigin`.
3040		#[pallet::call_index(33)]
3041		#[pallet::weight(T::WeightInfo::set_max_commission())]
3042		pub fn set_max_commission(origin: OriginFor<T>, new: Perbill) -> DispatchResult {
3043			T::AdminOrigin::ensure_origin(origin)?;
3044			ensure!(new >= MinCommission::<T>::get(), Error::<T>::CommissionTooLow);
3045			MaxCommission::<T>::put(new);
3046			Ok(())
3047		}
3048
3049		/// Configure the validator self-stake incentive parameters.
3050		///
3051		/// The dispatch origin must be `T::AdminOrigin`.
3052		///
3053		/// Changes take effect in the next era when rewards are calculated.
3054		#[pallet::call_index(34)]
3055		#[pallet::weight(T::WeightInfo::set_validator_self_stake_incentive_config())]
3056		pub fn set_validator_self_stake_incentive_config(
3057			origin: OriginFor<T>,
3058			optimum_self_stake: ConfigOp<BalanceOf<T>>,
3059			hard_cap_self_stake: ConfigOp<BalanceOf<T>>,
3060			self_stake_slope_factor: ConfigOp<Perbill>,
3061		) -> DispatchResult {
3062			T::AdminOrigin::ensure_origin(origin)?;
3063
3064			let new_optimum = match optimum_self_stake {
3065				ConfigOp::Noop => OptimumSelfStake::<T>::get(),
3066				ConfigOp::Set(v) => v,
3067				ConfigOp::Remove => BalanceOf::<T>::zero(),
3068			};
3069
3070			let new_cap = match hard_cap_self_stake {
3071				ConfigOp::Noop => HardCapSelfStake::<T>::get(),
3072				ConfigOp::Set(v) => v,
3073				ConfigOp::Remove => BalanceOf::<T>::zero(),
3074			};
3075
3076			ensure!(new_optimum <= new_cap, Error::<T>::OptimumGreaterThanCap);
3077
3078			let has_changes = !matches!(
3079				(&optimum_self_stake, &hard_cap_self_stake, &self_stake_slope_factor),
3080				(ConfigOp::Noop, ConfigOp::Noop, ConfigOp::Noop)
3081			);
3082
3083			macro_rules! config_op_exp {
3084				($storage:ty, $op:ident) => {
3085					match $op {
3086						ConfigOp::Noop => (),
3087						ConfigOp::Set(v) => <$storage>::put(v),
3088						ConfigOp::Remove => <$storage>::kill(),
3089					}
3090				};
3091			}
3092
3093			config_op_exp!(OptimumSelfStake<T>, optimum_self_stake);
3094			config_op_exp!(HardCapSelfStake<T>, hard_cap_self_stake);
3095			config_op_exp!(SelfStakeSlopeFactor<T>, self_stake_slope_factor);
3096
3097			if has_changes {
3098				Self::deposit_event(Event::<T>::ValidatorIncentiveConfigSet {
3099					optimum_self_stake: OptimumSelfStake::<T>::get(),
3100					hard_cap_self_stake: HardCapSelfStake::<T>::get(),
3101					slope_factor: SelfStakeSlopeFactor::<T>::get(),
3102				});
3103			}
3104
3105			Ok(())
3106		}
3107	}
3108
3109	#[pallet::view_functions]
3110	impl<T: Config> Pallet<T> {
3111		/// Resolve the account ID for a given reward pot.
3112		pub fn pot_account(pot: crate::RewardPot) -> T::AccountId {
3113			<T::RewardPots as crate::PotAccountProvider<T::AccountId>>::pot_account(pot)
3114		}
3115
3116		/// Current balance held in a given reward pot.
3117		pub fn pot_balance(pot: crate::RewardPot) -> BalanceOf<T> {
3118			let account =
3119				<T::RewardPots as crate::PotAccountProvider<T::AccountId>>::pot_account(pot);
3120			<T::Currency as frame_support::traits::fungible::Inspect<T::AccountId>>::balance(
3121				&account,
3122			)
3123		}
3124
3125		/// Per-era reward allocation (staker rewards + validator incentive budget).
3126		///
3127		/// Both fields are zero for eras created in legacy minting mode.
3128		pub fn era_reward_allocation(
3129			era: EraIndex,
3130		) -> crate::reward::EraRewardAllocation<BalanceOf<T>> {
3131			crate::reward::EraRewardAllocation {
3132				staker_rewards: ErasValidatorReward::<T>::get(era).unwrap_or_else(Zero::zero),
3133				validator_incentive: ErasValidatorIncentiveBudget::<T>::get(era),
3134			}
3135		}
3136	}
3137}