pallet_staking/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//! Staking FRAME Pallet.
19
20use alloc::vec::Vec;
21use codec::Codec;
22use frame_election_provider_support::{
23	ElectionProvider, ElectionProviderBase, SortedListProvider, VoteWeight,
24};
25use frame_support::{
26	pallet_prelude::*,
27	traits::{
28		Currency, Defensive, DefensiveSaturating, EnsureOrigin, EstimateNextNewSession, Get,
29		InspectLockableCurrency, LockableCurrency, OnUnbalanced, UnixTime,
30	},
31	weights::Weight,
32	BoundedVec,
33};
34use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
35use sp_runtime::{
36	traits::{SaturatedConversion, StaticLookup, Zero},
37	ArithmeticError, Perbill, Percent,
38};
39
40use sp_staking::{
41	EraIndex, Page, SessionIndex,
42	StakingAccount::{self, Controller, Stash},
43	StakingInterface,
44};
45
46mod impls;
47
48pub use impls::*;
49
50use crate::{
51	asset, slashing, weights::WeightInfo, AccountIdLookupOf, ActiveEraInfo, BalanceOf,
52	DisablingStrategy, EraPayout, EraRewardPoints, Exposure, ExposurePage, Forcing,
53	LedgerIntegrityState, MaxNominationsOf, NegativeImbalanceOf, Nominations, NominationsQuota,
54	PositiveImbalanceOf, RewardDestination, SessionInterface, StakingLedger, UnappliedSlash,
55	UnlockChunk, ValidatorPrefs,
56};
57
58// The speculative number of spans are used as an input of the weight annotation of
59// [`Call::unbond`], as the post dispatch weight may depend on the number of slashing span on the
60// account which is not provided as an input. The value set should be conservative but sensible.
61pub(crate) const SPECULATIVE_NUM_SPANS: u32 = 32;
62
63#[frame_support::pallet]
64pub mod pallet {
65	use frame_election_provider_support::ElectionDataProvider;
66
67	use crate::{BenchmarkingConfig, PagedExposureMetadata};
68
69	use super::*;
70
71	/// The in-code storage version.
72	const STORAGE_VERSION: StorageVersion = StorageVersion::new(15);
73
74	#[pallet::pallet]
75	#[pallet::storage_version(STORAGE_VERSION)]
76	pub struct Pallet<T>(_);
77
78	/// Possible operations on the configuration values of this pallet.
79	#[derive(TypeInfo, Debug, Clone, Encode, Decode, PartialEq)]
80	pub enum ConfigOp<T: Default + Codec> {
81		/// Don't change.
82		Noop,
83		/// Set the given value.
84		Set(T),
85		/// Remove from storage.
86		Remove,
87	}
88
89	#[pallet::config(with_default)]
90	pub trait Config: frame_system::Config {
91		/// The staking balance.
92		#[pallet::no_default]
93		type Currency: LockableCurrency<
94				Self::AccountId,
95				Moment = BlockNumberFor<Self>,
96				Balance = Self::CurrencyBalance,
97			> + InspectLockableCurrency<Self::AccountId>;
98		/// Just the `Currency::Balance` type; we have this item to allow us to constrain it to
99		/// `From<u64>`.
100		type CurrencyBalance: sp_runtime::traits::AtLeast32BitUnsigned
101			+ codec::FullCodec
102			+ Copy
103			+ MaybeSerializeDeserialize
104			+ core::fmt::Debug
105			+ Default
106			+ From<u64>
107			+ TypeInfo
108			+ MaxEncodedLen;
109		/// Time used for computing era duration.
110		///
111		/// It is guaranteed to start being called from the first `on_finalize`. Thus value at
112		/// genesis is not used.
113		#[pallet::no_default]
114		type UnixTime: UnixTime;
115
116		/// Convert a balance into a number used for election calculation. This must fit into a
117		/// `u64` but is allowed to be sensibly lossy. The `u64` is used to communicate with the
118		/// [`frame_election_provider_support`] crate which accepts u64 numbers and does operations
119		/// in 128.
120		/// Consequently, the backward convert is used convert the u128s from sp-elections back to a
121		/// [`BalanceOf`].
122		#[pallet::no_default_bounds]
123		type CurrencyToVote: sp_staking::currency_to_vote::CurrencyToVote<BalanceOf<Self>>;
124
125		/// Something that provides the election functionality.
126		#[pallet::no_default]
127		type ElectionProvider: ElectionProvider<
128			AccountId = Self::AccountId,
129			BlockNumber = BlockNumberFor<Self>,
130			// we only accept an election provider that has staking as data provider.
131			DataProvider = Pallet<Self>,
132		>;
133		/// Something that provides the election functionality at genesis.
134		#[pallet::no_default]
135		type GenesisElectionProvider: ElectionProvider<
136			AccountId = Self::AccountId,
137			BlockNumber = BlockNumberFor<Self>,
138			DataProvider = Pallet<Self>,
139		>;
140
141		/// Something that defines the maximum number of nominations per nominator.
142		#[pallet::no_default_bounds]
143		type NominationsQuota: NominationsQuota<BalanceOf<Self>>;
144
145		/// Number of eras to keep in history.
146		///
147		/// Following information is kept for eras in `[current_era -
148		/// HistoryDepth, current_era]`: `ErasStakers`, `ErasStakersClipped`,
149		/// `ErasValidatorPrefs`, `ErasValidatorReward`, `ErasRewardPoints`,
150		/// `ErasTotalStake`, `ErasStartSessionIndex`, `ClaimedRewards`, `ErasStakersPaged`,
151		/// `ErasStakersOverview`.
152		///
153		/// Must be more than the number of eras delayed by session.
154		/// I.e. active era must always be in history. I.e. `active_era >
155		/// current_era - history_depth` must be guaranteed.
156		///
157		/// If migrating an existing pallet from storage value to config value,
158		/// this should be set to same value or greater as in storage.
159		///
160		/// Note: `HistoryDepth` is used as the upper bound for the `BoundedVec`
161		/// item `StakingLedger.legacy_claimed_rewards`. Setting this value lower than
162		/// the existing value can lead to inconsistencies in the
163		/// `StakingLedger` and will need to be handled properly in a migration.
164		/// The test `reducing_history_depth_abrupt` shows this effect.
165		#[pallet::constant]
166		type HistoryDepth: Get<u32>;
167
168		/// Tokens have been minted and are unused for validator-reward.
169		/// See [Era payout](./index.html#era-payout).
170		#[pallet::no_default_bounds]
171		type RewardRemainder: OnUnbalanced<NegativeImbalanceOf<Self>>;
172
173		/// The overarching event type.
174		#[pallet::no_default_bounds]
175		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
176
177		/// Handler for the unbalanced reduction when slashing a staker.
178		#[pallet::no_default_bounds]
179		type Slash: OnUnbalanced<NegativeImbalanceOf<Self>>;
180
181		/// Handler for the unbalanced increment when rewarding a staker.
182		/// NOTE: in most cases, the implementation of `OnUnbalanced` should modify the total
183		/// issuance.
184		#[pallet::no_default_bounds]
185		type Reward: OnUnbalanced<PositiveImbalanceOf<Self>>;
186
187		/// Number of sessions per era.
188		#[pallet::constant]
189		type SessionsPerEra: Get<SessionIndex>;
190
191		/// Number of eras that staked funds must remain bonded for.
192		#[pallet::constant]
193		type BondingDuration: Get<EraIndex>;
194
195		/// Number of eras that slashes are deferred by, after computation.
196		///
197		/// This should be less than the bonding duration. Set to 0 if slashes
198		/// should be applied immediately, without opportunity for intervention.
199		#[pallet::constant]
200		type SlashDeferDuration: Get<EraIndex>;
201
202		/// The origin which can manage less critical staking parameters that does not require root.
203		///
204		/// Supported actions: (1) cancel deferred slash, (2) set minimum commission.
205		#[pallet::no_default]
206		type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
207
208		/// Interface for interacting with a session pallet.
209		type SessionInterface: SessionInterface<Self::AccountId>;
210
211		/// The payout for validators and the system for the current era.
212		/// See [Era payout](./index.html#era-payout).
213		#[pallet::no_default]
214		type EraPayout: EraPayout<BalanceOf<Self>>;
215
216		/// Something that can estimate the next session change, accurately or as a best effort
217		/// guess.
218		#[pallet::no_default_bounds]
219		type NextNewSession: EstimateNextNewSession<BlockNumberFor<Self>>;
220
221		/// The maximum size of each `T::ExposurePage`.
222		///
223		/// An `ExposurePage` is weakly bounded to a maximum of `MaxExposurePageSize`
224		/// nominators.
225		///
226		/// For older non-paged exposure, a reward payout was restricted to the top
227		/// `MaxExposurePageSize` nominators. This is to limit the i/o cost for the
228		/// nominator payout.
229		///
230		/// Note: `MaxExposurePageSize` is used to bound `ClaimedRewards` and is unsafe to reduce
231		/// without handling it in a migration.
232		#[pallet::constant]
233		type MaxExposurePageSize: Get<u32>;
234
235		/// Something that provides a best-effort sorted list of voters aka electing nominators,
236		/// used for NPoS election.
237		///
238		/// The changes to nominators are reported to this. Moreover, each validator's self-vote is
239		/// also reported as one independent vote.
240		///
241		/// To keep the load off the chain as much as possible, changes made to the staked amount
242		/// via rewards and slashes are not reported and thus need to be manually fixed by the
243		/// staker. In case of `bags-list`, this always means using `rebag` and `putInFrontOf`.
244		///
245		/// Invariant: what comes out of this list will always be a nominator.
246		#[pallet::no_default]
247		type VoterList: SortedListProvider<Self::AccountId, Score = VoteWeight>;
248
249		/// WIP: This is a noop as of now, the actual business logic that's described below is going
250		/// to be introduced in a follow-up PR.
251		///
252		/// Something that provides a best-effort sorted list of targets aka electable validators,
253		/// used for NPoS election.
254		///
255		/// The changes to the approval stake of each validator are reported to this. This means any
256		/// change to:
257		/// 1. The stake of any validator or nominator.
258		/// 2. The targets of any nominator
259		/// 3. The role of any staker (e.g. validator -> chilled, nominator -> validator, etc)
260		///
261		/// Unlike `VoterList`, the values in this list are always kept up to date with reward and
262		/// slash as well, and thus represent the accurate approval stake of all account being
263		/// nominated by nominators.
264		///
265		/// Note that while at the time of nomination, all targets are checked to be real
266		/// validators, they can chill at any point, and their approval stakes will still be
267		/// recorded. This implies that what comes out of iterating this list MIGHT NOT BE AN ACTIVE
268		/// VALIDATOR.
269		#[pallet::no_default]
270		type TargetList: SortedListProvider<Self::AccountId, Score = BalanceOf<Self>>;
271
272		/// The maximum number of `unlocking` chunks a [`StakingLedger`] can
273		/// have. Effectively determines how many unique eras a staker may be
274		/// unbonding in.
275		///
276		/// Note: `MaxUnlockingChunks` is used as the upper bound for the
277		/// `BoundedVec` item `StakingLedger.unlocking`. Setting this value
278		/// lower than the existing value can lead to inconsistencies in the
279		/// `StakingLedger` and will need to be handled properly in a runtime
280		/// migration. The test `reducing_max_unlocking_chunks_abrupt` shows
281		/// this effect.
282		#[pallet::constant]
283		type MaxUnlockingChunks: Get<u32>;
284
285		/// The maximum amount of controller accounts that can be deprecated in one call.
286		type MaxControllersInDeprecationBatch: Get<u32>;
287
288		/// Something that listens to staking updates and performs actions based on the data it
289		/// receives.
290		///
291		/// WARNING: this only reports slashing and withdraw events for the time being.
292		#[pallet::no_default_bounds]
293		type EventListeners: sp_staking::OnStakingUpdate<Self::AccountId, BalanceOf<Self>>;
294
295		/// `DisablingStragegy` controls how validators are disabled
296		#[pallet::no_default_bounds]
297		type DisablingStrategy: DisablingStrategy<Self>;
298
299		/// Some parameters of the benchmarking.
300		#[cfg(feature = "std")]
301		type BenchmarkingConfig: BenchmarkingConfig;
302
303		#[cfg(not(feature = "std"))]
304		#[pallet::no_default]
305		type BenchmarkingConfig: BenchmarkingConfig;
306
307		/// Weight information for extrinsics in this pallet.
308		type WeightInfo: WeightInfo;
309
310		/// Determines whether a given account should be filtered out from staking operations.
311		///
312		/// This function provides a way to exclude certain accounts from bonding to staking. An
313		/// already bonded account is allowed to withdraw.
314		///
315		/// The default implementation does not filter out any accounts.
316		fn filter(_who: &Self::AccountId) -> bool {
317			false
318		}
319	}
320
321	/// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`].
322	pub mod config_preludes {
323		use super::*;
324		use frame_support::{derive_impl, parameter_types, traits::ConstU32};
325		pub struct TestDefaultConfig;
326
327		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
328		impl frame_system::DefaultConfig for TestDefaultConfig {}
329
330		parameter_types! {
331			pub const SessionsPerEra: SessionIndex = 3;
332			pub const BondingDuration: EraIndex = 3;
333		}
334
335		#[frame_support::register_default_impl(TestDefaultConfig)]
336		impl DefaultConfig for TestDefaultConfig {
337			#[inject_runtime_type]
338			type RuntimeEvent = ();
339			type CurrencyBalance = u128;
340			type CurrencyToVote = ();
341			type NominationsQuota = crate::FixedNominationsQuota<16>;
342			type HistoryDepth = ConstU32<84>;
343			type RewardRemainder = ();
344			type Slash = ();
345			type Reward = ();
346			type SessionsPerEra = SessionsPerEra;
347			type BondingDuration = BondingDuration;
348			type SlashDeferDuration = ();
349			type SessionInterface = ();
350			type NextNewSession = ();
351			type MaxExposurePageSize = ConstU32<64>;
352			type MaxUnlockingChunks = ConstU32<32>;
353			type MaxControllersInDeprecationBatch = ConstU32<100>;
354			type EventListeners = ();
355			type DisablingStrategy = crate::UpToLimitDisablingStrategy;
356			#[cfg(feature = "std")]
357			type BenchmarkingConfig = crate::TestBenchmarkingConfig;
358			type WeightInfo = ();
359		}
360	}
361
362	/// The ideal number of active validators.
363	#[pallet::storage]
364	#[pallet::getter(fn validator_count)]
365	pub type ValidatorCount<T> = StorageValue<_, u32, ValueQuery>;
366
367	/// Minimum number of staking participants before emergency conditions are imposed.
368	#[pallet::storage]
369	#[pallet::getter(fn minimum_validator_count)]
370	pub type MinimumValidatorCount<T> = StorageValue<_, u32, ValueQuery>;
371
372	/// Any validators that may never be slashed or forcibly kicked. It's a Vec since they're
373	/// easy to initialize and the performance hit is minimal (we expect no more than four
374	/// invulnerables) and restricted to testnets.
375	#[pallet::storage]
376	#[pallet::getter(fn invulnerables)]
377	#[pallet::unbounded]
378	pub type Invulnerables<T: Config> = StorageValue<_, Vec<T::AccountId>, ValueQuery>;
379
380	/// Map from all locked "stash" accounts to the controller account.
381	///
382	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
383	#[pallet::storage]
384	pub type Bonded<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, T::AccountId>;
385
386	/// The minimum active bond to become and maintain the role of a nominator.
387	#[pallet::storage]
388	pub type MinNominatorBond<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
389
390	/// The minimum active bond to become and maintain the role of a validator.
391	#[pallet::storage]
392	pub type MinValidatorBond<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
393
394	/// The minimum active nominator stake of the last successful election.
395	#[pallet::storage]
396	pub type MinimumActiveStake<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;
397
398	/// The minimum amount of commission that validators can set.
399	///
400	/// If set to `0`, no limit exists.
401	#[pallet::storage]
402	pub type MinCommission<T: Config> = StorageValue<_, Perbill, ValueQuery>;
403
404	/// Map from all (unlocked) "controller" accounts to the info regarding the staking.
405	///
406	/// Note: All the reads and mutations to this storage *MUST* be done through the methods exposed
407	/// by [`StakingLedger`] to ensure data and lock consistency.
408	#[pallet::storage]
409	pub type Ledger<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, StakingLedger<T>>;
410
411	/// Where the reward payment should be made. Keyed by stash.
412	///
413	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
414	#[pallet::storage]
415	pub type Payee<T: Config> =
416		StorageMap<_, Twox64Concat, T::AccountId, RewardDestination<T::AccountId>, OptionQuery>;
417
418	/// The map from (wannabe) validator stash key to the preferences of that validator.
419	///
420	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
421	#[pallet::storage]
422	#[pallet::getter(fn validators)]
423	pub type Validators<T: Config> =
424		CountedStorageMap<_, Twox64Concat, T::AccountId, ValidatorPrefs, ValueQuery>;
425
426	/// The maximum validator count before we stop allowing new validators to join.
427	///
428	/// When this value is not set, no limits are enforced.
429	#[pallet::storage]
430	pub type MaxValidatorsCount<T> = StorageValue<_, u32, OptionQuery>;
431
432	/// The map from nominator stash key to their nomination preferences, namely the validators that
433	/// they wish to support.
434	///
435	/// Note that the keys of this storage map might become non-decodable in case the
436	/// account's [`NominationsQuota::MaxNominations`] configuration is decreased.
437	/// In this rare case, these nominators
438	/// are still existent in storage, their key is correct and retrievable (i.e. `contains_key`
439	/// indicates that they exist), but their value cannot be decoded. Therefore, the non-decodable
440	/// nominators will effectively not-exist, until they re-submit their preferences such that it
441	/// is within the bounds of the newly set `Config::MaxNominations`.
442	///
443	/// This implies that `::iter_keys().count()` and `::iter().count()` might return different
444	/// values for this map. Moreover, the main `::count()` is aligned with the former, namely the
445	/// number of keys that exist.
446	///
447	/// Lastly, if any of the nominators become non-decodable, they can be chilled immediately via
448	/// [`Call::chill_other`] dispatchable by anyone.
449	///
450	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
451	#[pallet::storage]
452	#[pallet::getter(fn nominators)]
453	pub type Nominators<T: Config> =
454		CountedStorageMap<_, Twox64Concat, T::AccountId, Nominations<T>>;
455
456	/// Stakers whose funds are managed by other pallets.
457	///
458	/// This pallet does not apply any locks on them, therefore they are only virtually bonded. They
459	/// are expected to be keyless accounts and hence should not be allowed to mutate their ledger
460	/// directly via this pallet. Instead, these accounts are managed by other pallets and accessed
461	/// via low level apis. We keep track of them to do minimal integrity checks.
462	#[pallet::storage]
463	pub type VirtualStakers<T: Config> = CountedStorageMap<_, Twox64Concat, T::AccountId, ()>;
464
465	/// The maximum nominator count before we stop allowing new validators to join.
466	///
467	/// When this value is not set, no limits are enforced.
468	#[pallet::storage]
469	pub type MaxNominatorsCount<T> = StorageValue<_, u32, OptionQuery>;
470
471	/// The current era index.
472	///
473	/// This is the latest planned era, depending on how the Session pallet queues the validator
474	/// set, it might be active or not.
475	#[pallet::storage]
476	#[pallet::getter(fn current_era)]
477	pub type CurrentEra<T> = StorageValue<_, EraIndex>;
478
479	/// The active era information, it holds index and start.
480	///
481	/// The active era is the era being currently rewarded. Validator set of this era must be
482	/// equal to [`SessionInterface::validators`].
483	#[pallet::storage]
484	#[pallet::getter(fn active_era)]
485	pub type ActiveEra<T> = StorageValue<_, ActiveEraInfo>;
486
487	/// The session index at which the era start for the last [`Config::HistoryDepth`] eras.
488	///
489	/// Note: This tracks the starting session (i.e. session index when era start being active)
490	/// for the eras in `[CurrentEra - HISTORY_DEPTH, CurrentEra]`.
491	#[pallet::storage]
492	#[pallet::getter(fn eras_start_session_index)]
493	pub type ErasStartSessionIndex<T> = StorageMap<_, Twox64Concat, EraIndex, SessionIndex>;
494
495	/// Exposure of validator at era.
496	///
497	/// This is keyed first by the era index to allow bulk deletion and then the stash account.
498	///
499	/// Is it removed after [`Config::HistoryDepth`] eras.
500	/// If stakers hasn't been set or has been removed then empty exposure is returned.
501	///
502	/// Note: Deprecated since v14. Use `EraInfo` instead to work with exposures.
503	#[pallet::storage]
504	#[pallet::unbounded]
505	pub type ErasStakers<T: Config> = StorageDoubleMap<
506		_,
507		Twox64Concat,
508		EraIndex,
509		Twox64Concat,
510		T::AccountId,
511		Exposure<T::AccountId, BalanceOf<T>>,
512		ValueQuery,
513	>;
514
515	/// Summary of validator exposure at a given era.
516	///
517	/// This contains the total stake in support of the validator and their own stake. In addition,
518	/// it can also be used to get the number of nominators backing this validator and the number of
519	/// exposure pages they are divided into. The page count is useful to determine the number of
520	/// pages of rewards that needs to be claimed.
521	///
522	/// This is keyed first by the era index to allow bulk deletion and then the stash account.
523	/// Should only be accessed through `EraInfo`.
524	///
525	/// Is it removed after [`Config::HistoryDepth`] eras.
526	/// If stakers hasn't been set or has been removed then empty overview is returned.
527	#[pallet::storage]
528	pub type ErasStakersOverview<T: Config> = StorageDoubleMap<
529		_,
530		Twox64Concat,
531		EraIndex,
532		Twox64Concat,
533		T::AccountId,
534		PagedExposureMetadata<BalanceOf<T>>,
535		OptionQuery,
536	>;
537
538	/// Clipped Exposure of validator at era.
539	///
540	/// Note: This is deprecated, should be used as read-only and will be removed in the future.
541	/// New `Exposure`s are stored in a paged manner in `ErasStakersPaged` instead.
542	///
543	/// This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the
544	/// `T::MaxExposurePageSize` biggest stakers.
545	/// (Note: the field `total` and `own` of the exposure remains unchanged).
546	/// This is used to limit the i/o cost for the nominator payout.
547	///
548	/// This is keyed fist by the era index to allow bulk deletion and then the stash account.
549	///
550	/// It is removed after [`Config::HistoryDepth`] eras.
551	/// If stakers hasn't been set or has been removed then empty exposure is returned.
552	///
553	/// Note: Deprecated since v14. Use `EraInfo` instead to work with exposures.
554	#[pallet::storage]
555	#[pallet::unbounded]
556	#[pallet::getter(fn eras_stakers_clipped)]
557	pub type ErasStakersClipped<T: Config> = StorageDoubleMap<
558		_,
559		Twox64Concat,
560		EraIndex,
561		Twox64Concat,
562		T::AccountId,
563		Exposure<T::AccountId, BalanceOf<T>>,
564		ValueQuery,
565	>;
566
567	/// Paginated exposure of a validator at given era.
568	///
569	/// This is keyed first by the era index to allow bulk deletion, then stash account and finally
570	/// the page. Should only be accessed through `EraInfo`.
571	///
572	/// This is cleared after [`Config::HistoryDepth`] eras.
573	#[pallet::storage]
574	#[pallet::unbounded]
575	pub type ErasStakersPaged<T: Config> = StorageNMap<
576		_,
577		(
578			NMapKey<Twox64Concat, EraIndex>,
579			NMapKey<Twox64Concat, T::AccountId>,
580			NMapKey<Twox64Concat, Page>,
581		),
582		ExposurePage<T::AccountId, BalanceOf<T>>,
583		OptionQuery,
584	>;
585
586	/// History of claimed paged rewards by era and validator.
587	///
588	/// This is keyed by era and validator stash which maps to the set of page indexes which have
589	/// been claimed.
590	///
591	/// It is removed after [`Config::HistoryDepth`] eras.
592	#[pallet::storage]
593	#[pallet::getter(fn claimed_rewards)]
594	#[pallet::unbounded]
595	pub type ClaimedRewards<T: Config> = StorageDoubleMap<
596		_,
597		Twox64Concat,
598		EraIndex,
599		Twox64Concat,
600		T::AccountId,
601		Vec<Page>,
602		ValueQuery,
603	>;
604
605	/// Similar to `ErasStakers`, this holds the preferences of validators.
606	///
607	/// This is keyed first by the era index to allow bulk deletion and then the stash account.
608	///
609	/// Is it removed after [`Config::HistoryDepth`] eras.
610	// If prefs hasn't been set or has been removed then 0 commission is returned.
611	#[pallet::storage]
612	#[pallet::getter(fn eras_validator_prefs)]
613	pub type ErasValidatorPrefs<T: Config> = StorageDoubleMap<
614		_,
615		Twox64Concat,
616		EraIndex,
617		Twox64Concat,
618		T::AccountId,
619		ValidatorPrefs,
620		ValueQuery,
621	>;
622
623	/// The total validator era payout for the last [`Config::HistoryDepth`] eras.
624	///
625	/// Eras that haven't finished yet or has been removed doesn't have reward.
626	#[pallet::storage]
627	#[pallet::getter(fn eras_validator_reward)]
628	pub type ErasValidatorReward<T: Config> = StorageMap<_, Twox64Concat, EraIndex, BalanceOf<T>>;
629
630	/// Rewards for the last [`Config::HistoryDepth`] eras.
631	/// If reward hasn't been set or has been removed then 0 reward is returned.
632	#[pallet::storage]
633	#[pallet::unbounded]
634	#[pallet::getter(fn eras_reward_points)]
635	pub type ErasRewardPoints<T: Config> =
636		StorageMap<_, Twox64Concat, EraIndex, EraRewardPoints<T::AccountId>, ValueQuery>;
637
638	/// The total amount staked for the last [`Config::HistoryDepth`] eras.
639	/// If total hasn't been set or has been removed then 0 stake is returned.
640	#[pallet::storage]
641	#[pallet::getter(fn eras_total_stake)]
642	pub type ErasTotalStake<T: Config> =
643		StorageMap<_, Twox64Concat, EraIndex, BalanceOf<T>, ValueQuery>;
644
645	/// Mode of era forcing.
646	#[pallet::storage]
647	#[pallet::getter(fn force_era)]
648	pub type ForceEra<T> = StorageValue<_, Forcing, ValueQuery>;
649
650	/// Maximum staked rewards, i.e. the percentage of the era inflation that
651	/// is used for stake rewards.
652	/// See [Era payout](./index.html#era-payout).
653	#[pallet::storage]
654	pub type MaxStakedRewards<T> = StorageValue<_, Percent, OptionQuery>;
655
656	/// The percentage of the slash that is distributed to reporters.
657	///
658	/// The rest of the slashed value is handled by the `Slash`.
659	#[pallet::storage]
660	#[pallet::getter(fn slash_reward_fraction)]
661	pub type SlashRewardFraction<T> = StorageValue<_, Perbill, ValueQuery>;
662
663	/// The amount of currency given to reporters of a slash event which was
664	/// canceled by extraordinary circumstances (e.g. governance).
665	#[pallet::storage]
666	#[pallet::getter(fn canceled_payout)]
667	pub type CanceledSlashPayout<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
668
669	/// All unapplied slashes that are queued for later.
670	#[pallet::storage]
671	#[pallet::unbounded]
672	pub type UnappliedSlashes<T: Config> = StorageMap<
673		_,
674		Twox64Concat,
675		EraIndex,
676		Vec<UnappliedSlash<T::AccountId, BalanceOf<T>>>,
677		ValueQuery,
678	>;
679
680	/// A mapping from still-bonded eras to the first session index of that era.
681	///
682	/// Must contains information for eras for the range:
683	/// `[active_era - bounding_duration; active_era]`
684	#[pallet::storage]
685	#[pallet::unbounded]
686	pub(crate) type BondedEras<T: Config> =
687		StorageValue<_, Vec<(EraIndex, SessionIndex)>, ValueQuery>;
688
689	/// All slashing events on validators, mapped by era to the highest slash proportion
690	/// and slash value of the era.
691	#[pallet::storage]
692	pub(crate) type ValidatorSlashInEra<T: Config> = StorageDoubleMap<
693		_,
694		Twox64Concat,
695		EraIndex,
696		Twox64Concat,
697		T::AccountId,
698		(Perbill, BalanceOf<T>),
699	>;
700
701	/// All slashing events on nominators, mapped by era to the highest slash value of the era.
702	#[pallet::storage]
703	pub(crate) type NominatorSlashInEra<T: Config> =
704		StorageDoubleMap<_, Twox64Concat, EraIndex, Twox64Concat, T::AccountId, BalanceOf<T>>;
705
706	/// Slashing spans for stash accounts.
707	#[pallet::storage]
708	#[pallet::getter(fn slashing_spans)]
709	#[pallet::unbounded]
710	pub type SlashingSpans<T: Config> =
711		StorageMap<_, Twox64Concat, T::AccountId, slashing::SlashingSpans>;
712
713	/// Records information about the maximum slash of a stash within a slashing span,
714	/// as well as how much reward has been paid out.
715	#[pallet::storage]
716	pub(crate) type SpanSlash<T: Config> = StorageMap<
717		_,
718		Twox64Concat,
719		(T::AccountId, slashing::SpanIndex),
720		slashing::SpanRecord<BalanceOf<T>>,
721		ValueQuery,
722	>;
723
724	/// The last planned session scheduled by the session pallet.
725	///
726	/// This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
727	#[pallet::storage]
728	#[pallet::getter(fn current_planned_session)]
729	pub type CurrentPlannedSession<T> = StorageValue<_, SessionIndex, ValueQuery>;
730
731	/// Indices of validators that have offended in the active era. The offenders are disabled for a
732	/// whole era. For this reason they are kept here - only staking pallet knows about eras. The
733	/// implementor of [`DisablingStrategy`] defines if a validator should be disabled which
734	/// implicitly means that the implementor also controls the max number of disabled validators.
735	///
736	/// The vec is always kept sorted so that we can find whether a given validator has previously
737	/// offended using binary search.
738	#[pallet::storage]
739	#[pallet::unbounded]
740	pub type DisabledValidators<T: Config> = StorageValue<_, Vec<u32>, ValueQuery>;
741
742	/// The threshold for when users can start calling `chill_other` for other validators /
743	/// nominators. The threshold is compared to the actual number of validators / nominators
744	/// (`CountFor*`) in the system compared to the configured max (`Max*Count`).
745	#[pallet::storage]
746	pub(crate) type ChillThreshold<T: Config> = StorageValue<_, Percent, OptionQuery>;
747
748	#[pallet::genesis_config]
749	#[derive(frame_support::DefaultNoBound)]
750	pub struct GenesisConfig<T: Config> {
751		pub validator_count: u32,
752		pub minimum_validator_count: u32,
753		pub invulnerables: Vec<T::AccountId>,
754		pub force_era: Forcing,
755		pub slash_reward_fraction: Perbill,
756		pub canceled_payout: BalanceOf<T>,
757		pub stakers:
758			Vec<(T::AccountId, T::AccountId, BalanceOf<T>, crate::StakerStatus<T::AccountId>)>,
759		pub min_nominator_bond: BalanceOf<T>,
760		pub min_validator_bond: BalanceOf<T>,
761		pub max_validator_count: Option<u32>,
762		pub max_nominator_count: Option<u32>,
763	}
764
765	#[pallet::genesis_build]
766	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
767		fn build(&self) {
768			ValidatorCount::<T>::put(self.validator_count);
769			MinimumValidatorCount::<T>::put(self.minimum_validator_count);
770			Invulnerables::<T>::put(&self.invulnerables);
771			ForceEra::<T>::put(self.force_era);
772			CanceledSlashPayout::<T>::put(self.canceled_payout);
773			SlashRewardFraction::<T>::put(self.slash_reward_fraction);
774			MinNominatorBond::<T>::put(self.min_nominator_bond);
775			MinValidatorBond::<T>::put(self.min_validator_bond);
776			if let Some(x) = self.max_validator_count {
777				MaxValidatorsCount::<T>::put(x);
778			}
779			if let Some(x) = self.max_nominator_count {
780				MaxNominatorsCount::<T>::put(x);
781			}
782
783			for &(ref stash, _, balance, ref status) in &self.stakers {
784				crate::log!(
785					trace,
786					"inserting genesis staker: {:?} => {:?} => {:?}",
787					stash,
788					balance,
789					status
790				);
791				assert!(
792					asset::stakeable_balance::<T>(stash) >= balance,
793					"Stash does not have enough balance to bond."
794				);
795				frame_support::assert_ok!(<Pallet<T>>::bond(
796					T::RuntimeOrigin::from(Some(stash.clone()).into()),
797					balance,
798					RewardDestination::Staked,
799				));
800				frame_support::assert_ok!(match status {
801					crate::StakerStatus::Validator => <Pallet<T>>::validate(
802						T::RuntimeOrigin::from(Some(stash.clone()).into()),
803						Default::default(),
804					),
805					crate::StakerStatus::Nominator(votes) => <Pallet<T>>::nominate(
806						T::RuntimeOrigin::from(Some(stash.clone()).into()),
807						votes.iter().map(|l| T::Lookup::unlookup(l.clone())).collect(),
808					),
809					_ => Ok(()),
810				});
811				assert!(
812					ValidatorCount::<T>::get() <=
813						<T::ElectionProvider as ElectionProviderBase>::MaxWinners::get()
814				);
815			}
816
817			// all voters are reported to the `VoterList`.
818			assert_eq!(
819				T::VoterList::count(),
820				Nominators::<T>::count() + Validators::<T>::count(),
821				"not all genesis stakers were inserted into sorted list provider, something is wrong."
822			);
823		}
824	}
825
826	#[pallet::event]
827	#[pallet::generate_deposit(pub(crate) fn deposit_event)]
828	pub enum Event<T: Config> {
829		/// The era payout has been set; the first balance is the validator-payout; the second is
830		/// the remainder from the maximum amount of reward.
831		EraPaid { era_index: EraIndex, validator_payout: BalanceOf<T>, remainder: BalanceOf<T> },
832		/// The nominator has been rewarded by this amount to this destination.
833		Rewarded {
834			stash: T::AccountId,
835			dest: RewardDestination<T::AccountId>,
836			amount: BalanceOf<T>,
837		},
838		/// A staker (validator or nominator) has been slashed by the given amount.
839		Slashed { staker: T::AccountId, amount: BalanceOf<T> },
840		/// A slash for the given validator, for the given percentage of their stake, at the given
841		/// era as been reported.
842		SlashReported { validator: T::AccountId, fraction: Perbill, slash_era: EraIndex },
843		/// An old slashing report from a prior era was discarded because it could
844		/// not be processed.
845		OldSlashingReportDiscarded { session_index: SessionIndex },
846		/// A new set of stakers was elected.
847		StakersElected,
848		/// An account has bonded this amount. \[stash, amount\]
849		///
850		/// NOTE: This event is only emitted when funds are bonded via a dispatchable. Notably,
851		/// it will not be emitted for staking rewards when they are added to stake.
852		Bonded { stash: T::AccountId, amount: BalanceOf<T> },
853		/// An account has unbonded this amount.
854		Unbonded { stash: T::AccountId, amount: BalanceOf<T> },
855		/// An account has called `withdraw_unbonded` and removed unbonding chunks worth `Balance`
856		/// from the unlocking queue.
857		Withdrawn { stash: T::AccountId, amount: BalanceOf<T> },
858		/// A nominator has been kicked from a validator.
859		Kicked { nominator: T::AccountId, stash: T::AccountId },
860		/// The election failed. No new era is planned.
861		StakingElectionFailed,
862		/// An account has stopped participating as either a validator or nominator.
863		Chilled { stash: T::AccountId },
864		/// A Page of stakers rewards are getting paid. `next` is `None` if all pages are claimed.
865		PayoutStarted {
866			era_index: EraIndex,
867			validator_stash: T::AccountId,
868			page: Page,
869			next: Option<Page>,
870		},
871		/// A validator has set their preferences.
872		ValidatorPrefsSet { stash: T::AccountId, prefs: ValidatorPrefs },
873		/// Voters size limit reached.
874		SnapshotVotersSizeExceeded { size: u32 },
875		/// Targets size limit reached.
876		SnapshotTargetsSizeExceeded { size: u32 },
877		/// A new force era mode was set.
878		ForceEra { mode: Forcing },
879		/// Report of a controller batch deprecation.
880		ControllerBatchDeprecated { failures: u32 },
881	}
882
883	#[pallet::error]
884	#[derive(PartialEq)]
885	pub enum Error<T> {
886		/// Not a controller account.
887		NotController,
888		/// Not a stash account.
889		NotStash,
890		/// Stash is already bonded.
891		AlreadyBonded,
892		/// Controller is already paired.
893		AlreadyPaired,
894		/// Targets cannot be empty.
895		EmptyTargets,
896		/// Duplicate index.
897		DuplicateIndex,
898		/// Slash record index out of bounds.
899		InvalidSlashIndex,
900		/// Cannot have a validator or nominator role, with value less than the minimum defined by
901		/// governance (see `MinValidatorBond` and `MinNominatorBond`). If unbonding is the
902		/// intention, `chill` first to remove one's role as validator/nominator.
903		InsufficientBond,
904		/// Can not schedule more unlock chunks.
905		NoMoreChunks,
906		/// Can not rebond without unlocking chunks.
907		NoUnlockChunk,
908		/// Attempting to target a stash that still has funds.
909		FundedTarget,
910		/// Invalid era to reward.
911		InvalidEraToReward,
912		/// Invalid number of nominations.
913		InvalidNumberOfNominations,
914		/// Items are not sorted and unique.
915		NotSortedAndUnique,
916		/// Rewards for this era have already been claimed for this validator.
917		AlreadyClaimed,
918		/// No nominators exist on this page.
919		InvalidPage,
920		/// Incorrect previous history depth input provided.
921		IncorrectHistoryDepth,
922		/// Incorrect number of slashing spans provided.
923		IncorrectSlashingSpans,
924		/// Internal state has become somehow corrupted and the operation cannot continue.
925		BadState,
926		/// Too many nomination targets supplied.
927		TooManyTargets,
928		/// A nomination target was supplied that was blocked or otherwise not a validator.
929		BadTarget,
930		/// The user has enough bond and thus cannot be chilled forcefully by an external person.
931		CannotChillOther,
932		/// There are too many nominators in the system. Governance needs to adjust the staking
933		/// settings to keep things safe for the runtime.
934		TooManyNominators,
935		/// There are too many validator candidates in the system. Governance needs to adjust the
936		/// staking settings to keep things safe for the runtime.
937		TooManyValidators,
938		/// Commission is too low. Must be at least `MinCommission`.
939		CommissionTooLow,
940		/// Some bound is not met.
941		BoundNotMet,
942		/// Used when attempting to use deprecated controller account logic.
943		ControllerDeprecated,
944		/// Cannot reset a ledger.
945		CannotRestoreLedger,
946		/// Provided reward destination is not allowed.
947		RewardDestinationRestricted,
948		/// Not enough funds available to withdraw.
949		NotEnoughFunds,
950		/// Operation not allowed for virtual stakers.
951		VirtualStakerNotAllowed,
952	}
953
954	#[pallet::hooks]
955	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
956		fn on_initialize(_now: BlockNumberFor<T>) -> Weight {
957			// just return the weight of the on_finalize.
958			T::DbWeight::get().reads(1)
959		}
960
961		fn on_finalize(_n: BlockNumberFor<T>) {
962			// Set the start of the first era.
963			if let Some(mut active_era) = Self::active_era() {
964				if active_era.start.is_none() {
965					let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::<u64>();
966					active_era.start = Some(now_as_millis_u64);
967					// This write only ever happens once, we don't include it in the weight in
968					// general
969					ActiveEra::<T>::put(active_era);
970				}
971			}
972			// `on_finalize` weight is tracked in `on_initialize`
973		}
974
975		fn integrity_test() {
976			// ensure that we funnel the correct value to the `DataProvider::MaxVotesPerVoter`;
977			assert_eq!(
978				MaxNominationsOf::<T>::get(),
979				<Self as ElectionDataProvider>::MaxVotesPerVoter::get()
980			);
981			// and that MaxNominations is always greater than 1, since we count on this.
982			assert!(!MaxNominationsOf::<T>::get().is_zero());
983
984			// ensure election results are always bounded with the same value
985			assert!(
986				<T::ElectionProvider as ElectionProviderBase>::MaxWinners::get() ==
987					<T::GenesisElectionProvider as ElectionProviderBase>::MaxWinners::get()
988			);
989
990			assert!(
991				T::SlashDeferDuration::get() < T::BondingDuration::get() || T::BondingDuration::get() == 0,
992				"As per documentation, slash defer duration ({}) should be less than bonding duration ({}).",
993				T::SlashDeferDuration::get(),
994				T::BondingDuration::get(),
995			)
996		}
997
998		#[cfg(feature = "try-runtime")]
999		fn try_state(n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
1000			Self::do_try_state(n)
1001		}
1002	}
1003
1004	#[pallet::call]
1005	impl<T: Config> Pallet<T> {
1006		/// Take the origin account as a stash and lock up `value` of its balance. `controller` will
1007		/// be the account that controls it.
1008		///
1009		/// `value` must be more than the `minimum_balance` specified by `T::Currency`.
1010		///
1011		/// The dispatch origin for this call must be _Signed_ by the stash account.
1012		///
1013		/// Emits `Bonded`.
1014		/// ## Complexity
1015		/// - Independent of the arguments. Moderate complexity.
1016		/// - O(1).
1017		/// - Three extra DB entries.
1018		///
1019		/// NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned
1020		/// unless the `origin` falls below _existential deposit_ (or equal to 0) and gets removed
1021		/// as dust.
1022		#[pallet::call_index(0)]
1023		#[pallet::weight(T::WeightInfo::bond())]
1024		pub fn bond(
1025			origin: OriginFor<T>,
1026			#[pallet::compact] value: BalanceOf<T>,
1027			payee: RewardDestination<T::AccountId>,
1028		) -> DispatchResult {
1029			let stash = ensure_signed(origin)?;
1030
1031			ensure!(!T::filter(&stash), Error::<T>::BoundNotMet);
1032
1033			if StakingLedger::<T>::is_bonded(StakingAccount::Stash(stash.clone())) {
1034				return Err(Error::<T>::AlreadyBonded.into())
1035			}
1036
1037			// An existing controller cannot become a stash.
1038			if StakingLedger::<T>::is_bonded(StakingAccount::Controller(stash.clone())) {
1039				return Err(Error::<T>::AlreadyPaired.into())
1040			}
1041
1042			// Reject a bond which is considered to be _dust_.
1043			if value < asset::existential_deposit::<T>() {
1044				return Err(Error::<T>::InsufficientBond.into())
1045			}
1046
1047			// Would fail if account has no provider.
1048			frame_system::Pallet::<T>::inc_consumers(&stash)?;
1049
1050			let stash_balance = asset::stakeable_balance::<T>(&stash);
1051			let value = value.min(stash_balance);
1052			Self::deposit_event(Event::<T>::Bonded { stash: stash.clone(), amount: value });
1053			let ledger = StakingLedger::<T>::new(stash.clone(), value);
1054
1055			// You're auto-bonded forever, here. We might improve this by only bonding when
1056			// you actually validate/nominate and remove once you unbond __everything__.
1057			ledger.bond(payee)?;
1058
1059			Ok(())
1060		}
1061
1062		/// Add some extra amount that have appeared in the stash `free_balance` into the balance up
1063		/// for staking.
1064		///
1065		/// The dispatch origin for this call must be _Signed_ by the stash, not the controller.
1066		///
1067		/// Use this if there are additional funds in your stash account that you wish to bond.
1068		/// Unlike [`bond`](Self::bond) or [`unbond`](Self::unbond) this function does not impose
1069		/// any limitation on the amount that can be added.
1070		///
1071		/// Emits `Bonded`.
1072		///
1073		/// ## Complexity
1074		/// - Independent of the arguments. Insignificant complexity.
1075		/// - O(1).
1076		#[pallet::call_index(1)]
1077		#[pallet::weight(T::WeightInfo::bond_extra())]
1078		pub fn bond_extra(
1079			origin: OriginFor<T>,
1080			#[pallet::compact] max_additional: BalanceOf<T>,
1081		) -> DispatchResult {
1082			let stash = ensure_signed(origin)?;
1083			ensure!(!T::filter(&stash), Error::<T>::BoundNotMet);
1084			Self::do_bond_extra(&stash, max_additional)
1085		}
1086
1087		/// Schedule a portion of the stash to be unlocked ready for transfer out after the bond
1088		/// period ends. If this leaves an amount actively bonded less than
1089		/// [`asset::existential_deposit`], then it is increased to the full amount.
1090		///
1091		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
1092		///
1093		/// Once the unlock period is done, you can call `withdraw_unbonded` to actually move
1094		/// the funds out of management ready for transfer.
1095		///
1096		/// No more than a limited number of unlocking chunks (see `MaxUnlockingChunks`)
1097		/// can co-exists at the same time. If there are no unlocking chunks slots available
1098		/// [`Call::withdraw_unbonded`] is called to remove some of the chunks (if possible).
1099		///
1100		/// If a user encounters the `InsufficientBond` error when calling this extrinsic,
1101		/// they should call `chill` first in order to free up their bonded funds.
1102		///
1103		/// Emits `Unbonded`.
1104		///
1105		/// See also [`Call::withdraw_unbonded`].
1106		#[pallet::call_index(2)]
1107		#[pallet::weight(
1108            T::WeightInfo::withdraw_unbonded_kill(SPECULATIVE_NUM_SPANS).saturating_add(T::WeightInfo::unbond()))
1109        ]
1110		pub fn unbond(
1111			origin: OriginFor<T>,
1112			#[pallet::compact] value: BalanceOf<T>,
1113		) -> DispatchResultWithPostInfo {
1114			let controller = ensure_signed(origin)?;
1115			let unlocking =
1116				Self::ledger(Controller(controller.clone())).map(|l| l.unlocking.len())?;
1117
1118			// if there are no unlocking chunks available, try to withdraw chunks older than
1119			// `BondingDuration` to proceed with the unbonding.
1120			let maybe_withdraw_weight = {
1121				if unlocking == T::MaxUnlockingChunks::get() as usize {
1122					let real_num_slashing_spans =
1123						Self::slashing_spans(&controller).map_or(0, |s| s.iter().count());
1124					Some(Self::do_withdraw_unbonded(&controller, real_num_slashing_spans as u32)?)
1125				} else {
1126					None
1127				}
1128			};
1129
1130			// we need to fetch the ledger again because it may have been mutated in the call
1131			// to `Self::do_withdraw_unbonded` above.
1132			let mut ledger = Self::ledger(Controller(controller))?;
1133			let mut value = value.min(ledger.active);
1134			let stash = ledger.stash.clone();
1135
1136			ensure!(
1137				ledger.unlocking.len() < T::MaxUnlockingChunks::get() as usize,
1138				Error::<T>::NoMoreChunks,
1139			);
1140
1141			if !value.is_zero() {
1142				ledger.active -= value;
1143
1144				// Avoid there being a dust balance left in the staking system.
1145				if ledger.active < asset::existential_deposit::<T>() {
1146					value += ledger.active;
1147					ledger.active = Zero::zero();
1148				}
1149
1150				let min_active_bond = if Nominators::<T>::contains_key(&stash) {
1151					MinNominatorBond::<T>::get()
1152				} else if Validators::<T>::contains_key(&stash) {
1153					MinValidatorBond::<T>::get()
1154				} else {
1155					Zero::zero()
1156				};
1157
1158				// Make sure that the user maintains enough active bond for their role.
1159				// If a user runs into this error, they should chill first.
1160				ensure!(ledger.active >= min_active_bond, Error::<T>::InsufficientBond);
1161
1162				// Note: in case there is no current era it is fine to bond one era more.
1163				let era = Self::current_era()
1164					.unwrap_or(0)
1165					.defensive_saturating_add(T::BondingDuration::get());
1166				if let Some(chunk) = ledger.unlocking.last_mut().filter(|chunk| chunk.era == era) {
1167					// To keep the chunk count down, we only keep one chunk per era. Since
1168					// `unlocking` is a FiFo queue, if a chunk exists for `era` we know that it will
1169					// be the last one.
1170					chunk.value = chunk.value.defensive_saturating_add(value)
1171				} else {
1172					ledger
1173						.unlocking
1174						.try_push(UnlockChunk { value, era })
1175						.map_err(|_| Error::<T>::NoMoreChunks)?;
1176				};
1177				// NOTE: ledger must be updated prior to calling `Self::weight_of`.
1178				ledger.update()?;
1179
1180				// update this staker in the sorted list, if they exist in it.
1181				if T::VoterList::contains(&stash) {
1182					let _ = T::VoterList::on_update(&stash, Self::weight_of(&stash)).defensive();
1183				}
1184
1185				Self::deposit_event(Event::<T>::Unbonded { stash, amount: value });
1186			}
1187
1188			let actual_weight = if let Some(withdraw_weight) = maybe_withdraw_weight {
1189				Some(T::WeightInfo::unbond().saturating_add(withdraw_weight))
1190			} else {
1191				Some(T::WeightInfo::unbond())
1192			};
1193
1194			Ok(actual_weight.into())
1195		}
1196
1197		/// Remove any unlocked chunks from the `unlocking` queue from our management.
1198		///
1199		/// This essentially frees up that balance to be used by the stash account to do whatever
1200		/// it wants.
1201		///
1202		/// The dispatch origin for this call must be _Signed_ by the controller.
1203		///
1204		/// Emits `Withdrawn`.
1205		///
1206		/// See also [`Call::unbond`].
1207		///
1208		/// ## Parameters
1209		///
1210		/// - `num_slashing_spans` indicates the number of metadata slashing spans to clear when
1211		/// this call results in a complete removal of all the data related to the stash account.
1212		/// In this case, the `num_slashing_spans` must be larger or equal to the number of
1213		/// slashing spans associated with the stash account in the [`SlashingSpans`] storage type,
1214		/// otherwise the call will fail. The call weight is directly proportional to
1215		/// `num_slashing_spans`.
1216		///
1217		/// ## Complexity
1218		/// O(S) where S is the number of slashing spans to remove
1219		/// NOTE: Weight annotation is the kill scenario, we refund otherwise.
1220		#[pallet::call_index(3)]
1221		#[pallet::weight(T::WeightInfo::withdraw_unbonded_kill(*num_slashing_spans))]
1222		pub fn withdraw_unbonded(
1223			origin: OriginFor<T>,
1224			num_slashing_spans: u32,
1225		) -> DispatchResultWithPostInfo {
1226			let controller = ensure_signed(origin)?;
1227
1228			let actual_weight = Self::do_withdraw_unbonded(&controller, num_slashing_spans)?;
1229			Ok(Some(actual_weight).into())
1230		}
1231
1232		/// Declare the desire to validate for the origin controller.
1233		///
1234		/// Effects will be felt at the beginning of the next era.
1235		///
1236		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
1237		#[pallet::call_index(4)]
1238		#[pallet::weight(T::WeightInfo::validate())]
1239		pub fn validate(origin: OriginFor<T>, prefs: ValidatorPrefs) -> DispatchResult {
1240			let controller = ensure_signed(origin)?;
1241
1242			let ledger = Self::ledger(Controller(controller))?;
1243
1244			ensure!(ledger.active >= MinValidatorBond::<T>::get(), Error::<T>::InsufficientBond);
1245			let stash = &ledger.stash;
1246
1247			// ensure their commission is correct.
1248			ensure!(prefs.commission >= MinCommission::<T>::get(), Error::<T>::CommissionTooLow);
1249
1250			// Only check limits if they are not already a validator.
1251			if !Validators::<T>::contains_key(stash) {
1252				// If this error is reached, we need to adjust the `MinValidatorBond` and start
1253				// calling `chill_other`. Until then, we explicitly block new validators to protect
1254				// the runtime.
1255				if let Some(max_validators) = MaxValidatorsCount::<T>::get() {
1256					ensure!(
1257						Validators::<T>::count() < max_validators,
1258						Error::<T>::TooManyValidators
1259					);
1260				}
1261			}
1262
1263			Self::do_remove_nominator(stash);
1264			Self::do_add_validator(stash, prefs.clone());
1265			Self::deposit_event(Event::<T>::ValidatorPrefsSet { stash: ledger.stash, prefs });
1266
1267			Ok(())
1268		}
1269
1270		/// Declare the desire to nominate `targets` for the origin controller.
1271		///
1272		/// Effects will be felt at the beginning of the next era.
1273		///
1274		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
1275		///
1276		/// ## Complexity
1277		/// - The transaction's complexity is proportional to the size of `targets` (N)
1278		/// which is capped at CompactAssignments::LIMIT (T::MaxNominations).
1279		/// - Both the reads and writes follow a similar pattern.
1280		#[pallet::call_index(5)]
1281		#[pallet::weight(T::WeightInfo::nominate(targets.len() as u32))]
1282		pub fn nominate(
1283			origin: OriginFor<T>,
1284			targets: Vec<AccountIdLookupOf<T>>,
1285		) -> DispatchResult {
1286			let controller = ensure_signed(origin)?;
1287
1288			let ledger = Self::ledger(StakingAccount::Controller(controller.clone()))?;
1289
1290			ensure!(ledger.active >= MinNominatorBond::<T>::get(), Error::<T>::InsufficientBond);
1291			let stash = &ledger.stash;
1292
1293			// Only check limits if they are not already a nominator.
1294			if !Nominators::<T>::contains_key(stash) {
1295				// If this error is reached, we need to adjust the `MinNominatorBond` and start
1296				// calling `chill_other`. Until then, we explicitly block new nominators to protect
1297				// the runtime.
1298				if let Some(max_nominators) = MaxNominatorsCount::<T>::get() {
1299					ensure!(
1300						Nominators::<T>::count() < max_nominators,
1301						Error::<T>::TooManyNominators
1302					);
1303				}
1304			}
1305
1306			ensure!(!targets.is_empty(), Error::<T>::EmptyTargets);
1307			ensure!(
1308				targets.len() <= T::NominationsQuota::get_quota(ledger.active) as usize,
1309				Error::<T>::TooManyTargets
1310			);
1311
1312			let old = Nominators::<T>::get(stash).map_or_else(Vec::new, |x| x.targets.into_inner());
1313
1314			let targets: BoundedVec<_, _> = targets
1315				.into_iter()
1316				.map(|t| T::Lookup::lookup(t).map_err(DispatchError::from))
1317				.map(|n| {
1318					n.and_then(|n| {
1319						if old.contains(&n) || !Validators::<T>::get(&n).blocked {
1320							Ok(n)
1321						} else {
1322							Err(Error::<T>::BadTarget.into())
1323						}
1324					})
1325				})
1326				.collect::<Result<Vec<_>, _>>()?
1327				.try_into()
1328				.map_err(|_| Error::<T>::TooManyNominators)?;
1329
1330			let nominations = Nominations {
1331				targets,
1332				// Initial nominations are considered submitted at era 0. See `Nominations` doc.
1333				submitted_in: Self::current_era().unwrap_or(0),
1334				suppressed: false,
1335			};
1336
1337			Self::do_remove_validator(stash);
1338			Self::do_add_nominator(stash, nominations);
1339			Ok(())
1340		}
1341
1342		/// Declare no desire to either validate or nominate.
1343		///
1344		/// Effects will be felt at the beginning of the next era.
1345		///
1346		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
1347		///
1348		/// ## Complexity
1349		/// - Independent of the arguments. Insignificant complexity.
1350		/// - Contains one read.
1351		/// - Writes are limited to the `origin` account key.
1352		#[pallet::call_index(6)]
1353		#[pallet::weight(T::WeightInfo::chill())]
1354		pub fn chill(origin: OriginFor<T>) -> DispatchResult {
1355			let controller = ensure_signed(origin)?;
1356
1357			let ledger = Self::ledger(StakingAccount::Controller(controller))?;
1358
1359			Self::chill_stash(&ledger.stash);
1360			Ok(())
1361		}
1362
1363		/// (Re-)set the payment target for a controller.
1364		///
1365		/// Effects will be felt instantly (as soon as this function is completed successfully).
1366		///
1367		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
1368		///
1369		/// ## Complexity
1370		/// - O(1)
1371		/// - Independent of the arguments. Insignificant complexity.
1372		/// - Contains a limited number of reads.
1373		/// - Writes are limited to the `origin` account key.
1374		/// ---------
1375		#[pallet::call_index(7)]
1376		#[pallet::weight(T::WeightInfo::set_payee())]
1377		pub fn set_payee(
1378			origin: OriginFor<T>,
1379			payee: RewardDestination<T::AccountId>,
1380		) -> DispatchResult {
1381			let controller = ensure_signed(origin)?;
1382			let ledger = Self::ledger(Controller(controller.clone()))?;
1383
1384			ensure!(
1385				(payee != {
1386					#[allow(deprecated)]
1387					RewardDestination::Controller
1388				}),
1389				Error::<T>::ControllerDeprecated
1390			);
1391
1392			let _ = ledger
1393				.set_payee(payee)
1394				.defensive_proof("ledger was retrieved from storage, thus its bonded; qed.")?;
1395
1396			Ok(())
1397		}
1398
1399		/// (Re-)sets the controller of a stash to the stash itself. This function previously
1400		/// accepted a `controller` argument to set the controller to an account other than the
1401		/// stash itself. This functionality has now been removed, now only setting the controller
1402		/// to the stash, if it is not already.
1403		///
1404		/// Effects will be felt instantly (as soon as this function is completed successfully).
1405		///
1406		/// The dispatch origin for this call must be _Signed_ by the stash, not the controller.
1407		///
1408		/// ## Complexity
1409		/// O(1)
1410		/// - Independent of the arguments. Insignificant complexity.
1411		/// - Contains a limited number of reads.
1412		/// - Writes are limited to the `origin` account key.
1413		#[pallet::call_index(8)]
1414		#[pallet::weight(T::WeightInfo::set_controller())]
1415		pub fn set_controller(origin: OriginFor<T>) -> DispatchResult {
1416			let stash = ensure_signed(origin)?;
1417
1418			Self::ledger(StakingAccount::Stash(stash.clone())).map(|ledger| {
1419				let controller = ledger.controller()
1420                    .defensive_proof("Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.")
1421                    .ok_or(Error::<T>::NotController)?;
1422
1423				if controller == stash {
1424					// Stash is already its own controller.
1425					return Err(Error::<T>::AlreadyPaired.into())
1426				}
1427
1428				let _ = ledger.set_controller_to_stash()?;
1429				Ok(())
1430			})?
1431		}
1432
1433		/// Sets the ideal number of validators.
1434		///
1435		/// The dispatch origin must be Root.
1436		///
1437		/// ## Complexity
1438		/// O(1)
1439		#[pallet::call_index(9)]
1440		#[pallet::weight(T::WeightInfo::set_validator_count())]
1441		pub fn set_validator_count(
1442			origin: OriginFor<T>,
1443			#[pallet::compact] new: u32,
1444		) -> DispatchResult {
1445			ensure_root(origin)?;
1446			// ensure new validator count does not exceed maximum winners
1447			// support by election provider.
1448			ensure!(
1449				new <= <T::ElectionProvider as ElectionProviderBase>::MaxWinners::get(),
1450				Error::<T>::TooManyValidators
1451			);
1452			ValidatorCount::<T>::put(new);
1453			Ok(())
1454		}
1455
1456		/// Increments the ideal number of validators up to maximum of
1457		/// `ElectionProviderBase::MaxWinners`.
1458		///
1459		/// The dispatch origin must be Root.
1460		///
1461		/// ## Complexity
1462		/// Same as [`Self::set_validator_count`].
1463		#[pallet::call_index(10)]
1464		#[pallet::weight(T::WeightInfo::set_validator_count())]
1465		pub fn increase_validator_count(
1466			origin: OriginFor<T>,
1467			#[pallet::compact] additional: u32,
1468		) -> DispatchResult {
1469			ensure_root(origin)?;
1470			let old = ValidatorCount::<T>::get();
1471			let new = old.checked_add(additional).ok_or(ArithmeticError::Overflow)?;
1472			ensure!(
1473				new <= <T::ElectionProvider as ElectionProviderBase>::MaxWinners::get(),
1474				Error::<T>::TooManyValidators
1475			);
1476
1477			ValidatorCount::<T>::put(new);
1478			Ok(())
1479		}
1480
1481		/// Scale up the ideal number of validators by a factor up to maximum of
1482		/// `ElectionProviderBase::MaxWinners`.
1483		///
1484		/// The dispatch origin must be Root.
1485		///
1486		/// ## Complexity
1487		/// Same as [`Self::set_validator_count`].
1488		#[pallet::call_index(11)]
1489		#[pallet::weight(T::WeightInfo::set_validator_count())]
1490		pub fn scale_validator_count(origin: OriginFor<T>, factor: Percent) -> DispatchResult {
1491			ensure_root(origin)?;
1492			let old = ValidatorCount::<T>::get();
1493			let new = old.checked_add(factor.mul_floor(old)).ok_or(ArithmeticError::Overflow)?;
1494
1495			ensure!(
1496				new <= <T::ElectionProvider as ElectionProviderBase>::MaxWinners::get(),
1497				Error::<T>::TooManyValidators
1498			);
1499
1500			ValidatorCount::<T>::put(new);
1501			Ok(())
1502		}
1503
1504		/// Force there to be no new eras indefinitely.
1505		///
1506		/// The dispatch origin must be Root.
1507		///
1508		/// # Warning
1509		///
1510		/// The election process starts multiple blocks before the end of the era.
1511		/// Thus the election process may be ongoing when this is called. In this case the
1512		/// election will continue until the next era is triggered.
1513		///
1514		/// ## Complexity
1515		/// - No arguments.
1516		/// - Weight: O(1)
1517		#[pallet::call_index(12)]
1518		#[pallet::weight(T::WeightInfo::force_no_eras())]
1519		pub fn force_no_eras(origin: OriginFor<T>) -> DispatchResult {
1520			ensure_root(origin)?;
1521			Self::set_force_era(Forcing::ForceNone);
1522			Ok(())
1523		}
1524
1525		/// Force there to be a new era at the end of the next session. After this, it will be
1526		/// reset to normal (non-forced) behaviour.
1527		///
1528		/// The dispatch origin must be Root.
1529		///
1530		/// # Warning
1531		///
1532		/// The election process starts multiple blocks before the end of the era.
1533		/// If this is called just before a new era is triggered, the election process may not
1534		/// have enough blocks to get a result.
1535		///
1536		/// ## Complexity
1537		/// - No arguments.
1538		/// - Weight: O(1)
1539		#[pallet::call_index(13)]
1540		#[pallet::weight(T::WeightInfo::force_new_era())]
1541		pub fn force_new_era(origin: OriginFor<T>) -> DispatchResult {
1542			ensure_root(origin)?;
1543			Self::set_force_era(Forcing::ForceNew);
1544			Ok(())
1545		}
1546
1547		/// Set the validators who cannot be slashed (if any).
1548		///
1549		/// The dispatch origin must be Root.
1550		#[pallet::call_index(14)]
1551		#[pallet::weight(T::WeightInfo::set_invulnerables(invulnerables.len() as u32))]
1552		pub fn set_invulnerables(
1553			origin: OriginFor<T>,
1554			invulnerables: Vec<T::AccountId>,
1555		) -> DispatchResult {
1556			ensure_root(origin)?;
1557			<Invulnerables<T>>::put(invulnerables);
1558			Ok(())
1559		}
1560
1561		/// Force a current staker to become completely unstaked, immediately.
1562		///
1563		/// The dispatch origin must be Root.
1564		///
1565		/// ## Parameters
1566		///
1567		/// - `num_slashing_spans`: Refer to comments on [`Call::withdraw_unbonded`] for more
1568		/// details.
1569		#[pallet::call_index(15)]
1570		#[pallet::weight(T::WeightInfo::force_unstake(*num_slashing_spans))]
1571		pub fn force_unstake(
1572			origin: OriginFor<T>,
1573			stash: T::AccountId,
1574			num_slashing_spans: u32,
1575		) -> DispatchResult {
1576			ensure_root(origin)?;
1577
1578			// Remove all staking-related information and lock.
1579			Self::kill_stash(&stash, num_slashing_spans)?;
1580
1581			Ok(())
1582		}
1583
1584		/// Force there to be a new era at the end of sessions indefinitely.
1585		///
1586		/// The dispatch origin must be Root.
1587		///
1588		/// # Warning
1589		///
1590		/// The election process starts multiple blocks before the end of the era.
1591		/// If this is called just before a new era is triggered, the election process may not
1592		/// have enough blocks to get a result.
1593		#[pallet::call_index(16)]
1594		#[pallet::weight(T::WeightInfo::force_new_era_always())]
1595		pub fn force_new_era_always(origin: OriginFor<T>) -> DispatchResult {
1596			ensure_root(origin)?;
1597			Self::set_force_era(Forcing::ForceAlways);
1598			Ok(())
1599		}
1600
1601		/// Cancel enactment of a deferred slash.
1602		///
1603		/// Can be called by the `T::AdminOrigin`.
1604		///
1605		/// Parameters: era and indices of the slashes for that era to kill.
1606		#[pallet::call_index(17)]
1607		#[pallet::weight(T::WeightInfo::cancel_deferred_slash(slash_indices.len() as u32))]
1608		pub fn cancel_deferred_slash(
1609			origin: OriginFor<T>,
1610			era: EraIndex,
1611			slash_indices: Vec<u32>,
1612		) -> DispatchResult {
1613			T::AdminOrigin::ensure_origin(origin)?;
1614
1615			ensure!(!slash_indices.is_empty(), Error::<T>::EmptyTargets);
1616			ensure!(is_sorted_and_unique(&slash_indices), Error::<T>::NotSortedAndUnique);
1617
1618			let mut unapplied = UnappliedSlashes::<T>::get(&era);
1619			let last_item = slash_indices[slash_indices.len() - 1];
1620			ensure!((last_item as usize) < unapplied.len(), Error::<T>::InvalidSlashIndex);
1621
1622			for (removed, index) in slash_indices.into_iter().enumerate() {
1623				let index = (index as usize) - removed;
1624				unapplied.remove(index);
1625			}
1626
1627			UnappliedSlashes::<T>::insert(&era, &unapplied);
1628			Ok(())
1629		}
1630
1631		/// Pay out next page of the stakers behind a validator for the given era.
1632		///
1633		/// - `validator_stash` is the stash account of the validator.
1634		/// - `era` may be any era between `[current_era - history_depth; current_era]`.
1635		///
1636		/// The origin of this call must be _Signed_. Any account can call this function, even if
1637		/// it is not one of the stakers.
1638		///
1639		/// The reward payout could be paged in case there are too many nominators backing the
1640		/// `validator_stash`. This call will payout unpaid pages in an ascending order. To claim a
1641		/// specific page, use `payout_stakers_by_page`.`
1642		///
1643		/// If all pages are claimed, it returns an error `InvalidPage`.
1644		#[pallet::call_index(18)]
1645		#[pallet::weight(T::WeightInfo::payout_stakers_alive_staked(T::MaxExposurePageSize::get()))]
1646		pub fn payout_stakers(
1647			origin: OriginFor<T>,
1648			validator_stash: T::AccountId,
1649			era: EraIndex,
1650		) -> DispatchResultWithPostInfo {
1651			ensure_signed(origin)?;
1652			Self::do_payout_stakers(validator_stash, era)
1653		}
1654
1655		/// Rebond a portion of the stash scheduled to be unlocked.
1656		///
1657		/// The dispatch origin must be signed by the controller.
1658		///
1659		/// ## Complexity
1660		/// - Time complexity: O(L), where L is unlocking chunks
1661		/// - Bounded by `MaxUnlockingChunks`.
1662		#[pallet::call_index(19)]
1663		#[pallet::weight(T::WeightInfo::rebond(T::MaxUnlockingChunks::get() as u32))]
1664		pub fn rebond(
1665			origin: OriginFor<T>,
1666			#[pallet::compact] value: BalanceOf<T>,
1667		) -> DispatchResultWithPostInfo {
1668			let controller = ensure_signed(origin)?;
1669			let ledger = Self::ledger(Controller(controller))?;
1670
1671			ensure!(!T::filter(&ledger.stash), Error::<T>::BoundNotMet);
1672			ensure!(!ledger.unlocking.is_empty(), Error::<T>::NoUnlockChunk);
1673
1674			let initial_unlocking = ledger.unlocking.len() as u32;
1675			let (ledger, rebonded_value) = ledger.rebond(value);
1676			// Last check: the new active amount of ledger must be more than ED.
1677			ensure!(
1678				ledger.active >= asset::existential_deposit::<T>(),
1679				Error::<T>::InsufficientBond
1680			);
1681
1682			Self::deposit_event(Event::<T>::Bonded {
1683				stash: ledger.stash.clone(),
1684				amount: rebonded_value,
1685			});
1686
1687			let stash = ledger.stash.clone();
1688			let final_unlocking = ledger.unlocking.len();
1689
1690			// NOTE: ledger must be updated prior to calling `Self::weight_of`.
1691			ledger.update()?;
1692			if T::VoterList::contains(&stash) {
1693				let _ = T::VoterList::on_update(&stash, Self::weight_of(&stash)).defensive();
1694			}
1695
1696			let removed_chunks = 1u32 // for the case where the last iterated chunk is not removed
1697				.saturating_add(initial_unlocking)
1698				.saturating_sub(final_unlocking as u32);
1699			Ok(Some(T::WeightInfo::rebond(removed_chunks)).into())
1700		}
1701
1702		/// Remove all data structures concerning a staker/stash once it is at a state where it can
1703		/// be considered `dust` in the staking system. The requirements are:
1704		///
1705		/// 1. the `total_balance` of the stash is below existential deposit.
1706		/// 2. or, the `ledger.total` of the stash is below existential deposit.
1707		/// 3. or, existential deposit is zero and either `total_balance` or `ledger.total` is zero.
1708		///
1709		/// The former can happen in cases like a slash; the latter when a fully unbonded account
1710		/// is still receiving staking rewards in `RewardDestination::Staked`.
1711		///
1712		/// It can be called by anyone, as long as `stash` meets the above requirements.
1713		///
1714		/// Refunds the transaction fees upon successful execution.
1715		///
1716		/// ## Parameters
1717		///
1718		/// - `num_slashing_spans`: Refer to comments on [`Call::withdraw_unbonded`] for more
1719		/// details.
1720		#[pallet::call_index(20)]
1721		#[pallet::weight(T::WeightInfo::reap_stash(*num_slashing_spans))]
1722		pub fn reap_stash(
1723			origin: OriginFor<T>,
1724			stash: T::AccountId,
1725			num_slashing_spans: u32,
1726		) -> DispatchResultWithPostInfo {
1727			let _ = ensure_signed(origin)?;
1728
1729			// virtual stakers should not be allowed to be reaped.
1730			ensure!(!Self::is_virtual_staker(&stash), Error::<T>::VirtualStakerNotAllowed);
1731
1732			let ed = asset::existential_deposit::<T>();
1733			let origin_balance = asset::total_balance::<T>(&stash);
1734			let ledger_total =
1735				Self::ledger(Stash(stash.clone())).map(|l| l.total).unwrap_or_default();
1736			let reapable = origin_balance < ed ||
1737				origin_balance.is_zero() ||
1738				ledger_total < ed ||
1739				ledger_total.is_zero();
1740			ensure!(reapable, Error::<T>::FundedTarget);
1741
1742			// Remove all staking-related information and lock.
1743			Self::kill_stash(&stash, num_slashing_spans)?;
1744
1745			Ok(Pays::No.into())
1746		}
1747
1748		/// Remove the given nominations from the calling validator.
1749		///
1750		/// Effects will be felt at the beginning of the next era.
1751		///
1752		/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
1753		///
1754		/// - `who`: A list of nominator stash accounts who are nominating this validator which
1755		///   should no longer be nominating this validator.
1756		///
1757		/// Note: Making this call only makes sense if you first set the validator preferences to
1758		/// block any further nominations.
1759		#[pallet::call_index(21)]
1760		#[pallet::weight(T::WeightInfo::kick(who.len() as u32))]
1761		pub fn kick(origin: OriginFor<T>, who: Vec<AccountIdLookupOf<T>>) -> DispatchResult {
1762			let controller = ensure_signed(origin)?;
1763			let ledger = Self::ledger(Controller(controller))?;
1764			let stash = &ledger.stash;
1765
1766			for nom_stash in who
1767				.into_iter()
1768				.map(T::Lookup::lookup)
1769				.collect::<Result<Vec<T::AccountId>, _>>()?
1770				.into_iter()
1771			{
1772				Nominators::<T>::mutate(&nom_stash, |maybe_nom| {
1773					if let Some(ref mut nom) = maybe_nom {
1774						if let Some(pos) = nom.targets.iter().position(|v| v == stash) {
1775							nom.targets.swap_remove(pos);
1776							Self::deposit_event(Event::<T>::Kicked {
1777								nominator: nom_stash.clone(),
1778								stash: stash.clone(),
1779							});
1780						}
1781					}
1782				});
1783			}
1784
1785			Ok(())
1786		}
1787
1788		/// Update the various staking configurations .
1789		///
1790		/// * `min_nominator_bond`: The minimum active bond needed to be a nominator.
1791		/// * `min_validator_bond`: The minimum active bond needed to be a validator.
1792		/// * `max_nominator_count`: The max number of users who can be a nominator at once. When
1793		///   set to `None`, no limit is enforced.
1794		/// * `max_validator_count`: The max number of users who can be a validator at once. When
1795		///   set to `None`, no limit is enforced.
1796		/// * `chill_threshold`: The ratio of `max_nominator_count` or `max_validator_count` which
1797		///   should be filled in order for the `chill_other` transaction to work.
1798		/// * `min_commission`: The minimum amount of commission that each validators must maintain.
1799		///   This is checked only upon calling `validate`. Existing validators are not affected.
1800		///
1801		/// RuntimeOrigin must be Root to call this function.
1802		///
1803		/// NOTE: Existing nominators and validators will not be affected by this update.
1804		/// to kick people under the new limits, `chill_other` should be called.
1805		// We assume the worst case for this call is either: all items are set or all items are
1806		// removed.
1807		#[pallet::call_index(22)]
1808		#[pallet::weight(
1809			T::WeightInfo::set_staking_configs_all_set()
1810				.max(T::WeightInfo::set_staking_configs_all_remove())
1811		)]
1812		pub fn set_staking_configs(
1813			origin: OriginFor<T>,
1814			min_nominator_bond: ConfigOp<BalanceOf<T>>,
1815			min_validator_bond: ConfigOp<BalanceOf<T>>,
1816			max_nominator_count: ConfigOp<u32>,
1817			max_validator_count: ConfigOp<u32>,
1818			chill_threshold: ConfigOp<Percent>,
1819			min_commission: ConfigOp<Perbill>,
1820			max_staked_rewards: ConfigOp<Percent>,
1821		) -> DispatchResult {
1822			ensure_root(origin)?;
1823
1824			macro_rules! config_op_exp {
1825				($storage:ty, $op:ident) => {
1826					match $op {
1827						ConfigOp::Noop => (),
1828						ConfigOp::Set(v) => <$storage>::put(v),
1829						ConfigOp::Remove => <$storage>::kill(),
1830					}
1831				};
1832			}
1833
1834			config_op_exp!(MinNominatorBond<T>, min_nominator_bond);
1835			config_op_exp!(MinValidatorBond<T>, min_validator_bond);
1836			config_op_exp!(MaxNominatorsCount<T>, max_nominator_count);
1837			config_op_exp!(MaxValidatorsCount<T>, max_validator_count);
1838			config_op_exp!(ChillThreshold<T>, chill_threshold);
1839			config_op_exp!(MinCommission<T>, min_commission);
1840			config_op_exp!(MaxStakedRewards<T>, max_staked_rewards);
1841			Ok(())
1842		}
1843		/// Declare a `controller` to stop participating as either a validator or nominator.
1844		///
1845		/// Effects will be felt at the beginning of the next era.
1846		///
1847		/// The dispatch origin for this call must be _Signed_, but can be called by anyone.
1848		///
1849		/// If the caller is the same as the controller being targeted, then no further checks are
1850		/// enforced, and this function behaves just like `chill`.
1851		///
1852		/// If the caller is different than the controller being targeted, the following conditions
1853		/// must be met:
1854		///
1855		/// * `controller` must belong to a nominator who has become non-decodable,
1856		///
1857		/// Or:
1858		///
1859		/// * A `ChillThreshold` must be set and checked which defines how close to the max
1860		///   nominators or validators we must reach before users can start chilling one-another.
1861		/// * A `MaxNominatorCount` and `MaxValidatorCount` must be set which is used to determine
1862		///   how close we are to the threshold.
1863		/// * A `MinNominatorBond` and `MinValidatorBond` must be set and checked, which determines
1864		///   if this is a person that should be chilled because they have not met the threshold
1865		///   bond required.
1866		///
1867		/// This can be helpful if bond requirements are updated, and we need to remove old users
1868		/// who do not satisfy these requirements.
1869		#[pallet::call_index(23)]
1870		#[pallet::weight(T::WeightInfo::chill_other())]
1871		pub fn chill_other(origin: OriginFor<T>, stash: T::AccountId) -> DispatchResult {
1872			// Anyone can call this function.
1873			let caller = ensure_signed(origin)?;
1874			let ledger = Self::ledger(Stash(stash.clone()))?;
1875			let controller = ledger
1876				.controller()
1877				.defensive_proof(
1878					"Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.",
1879				)
1880				.ok_or(Error::<T>::NotController)?;
1881
1882			// In order for one user to chill another user, the following conditions must be met:
1883			//
1884			// * `controller` belongs to a nominator who has become non-decodable,
1885			//
1886			// Or
1887			//
1888			// * A `ChillThreshold` is set which defines how close to the max nominators or
1889			//   validators we must reach before users can start chilling one-another.
1890			// * A `MaxNominatorCount` and `MaxValidatorCount` which is used to determine how close
1891			//   we are to the threshold.
1892			// * A `MinNominatorBond` and `MinValidatorBond` which is the final condition checked to
1893			//   determine this is a person that should be chilled because they have not met the
1894			//   threshold bond required.
1895			//
1896			// Otherwise, if caller is the same as the controller, this is just like `chill`.
1897
1898			if Nominators::<T>::contains_key(&stash) && Nominators::<T>::get(&stash).is_none() {
1899				Self::chill_stash(&stash);
1900				return Ok(())
1901			}
1902
1903			if caller != controller {
1904				let threshold = ChillThreshold::<T>::get().ok_or(Error::<T>::CannotChillOther)?;
1905				let min_active_bond = if Nominators::<T>::contains_key(&stash) {
1906					let max_nominator_count =
1907						MaxNominatorsCount::<T>::get().ok_or(Error::<T>::CannotChillOther)?;
1908					let current_nominator_count = Nominators::<T>::count();
1909					ensure!(
1910						threshold * max_nominator_count < current_nominator_count,
1911						Error::<T>::CannotChillOther
1912					);
1913					MinNominatorBond::<T>::get()
1914				} else if Validators::<T>::contains_key(&stash) {
1915					let max_validator_count =
1916						MaxValidatorsCount::<T>::get().ok_or(Error::<T>::CannotChillOther)?;
1917					let current_validator_count = Validators::<T>::count();
1918					ensure!(
1919						threshold * max_validator_count < current_validator_count,
1920						Error::<T>::CannotChillOther
1921					);
1922					MinValidatorBond::<T>::get()
1923				} else {
1924					Zero::zero()
1925				};
1926
1927				ensure!(ledger.active < min_active_bond, Error::<T>::CannotChillOther);
1928			}
1929
1930			Self::chill_stash(&stash);
1931			Ok(())
1932		}
1933
1934		/// Force a validator to have at least the minimum commission. This will not affect a
1935		/// validator who already has a commission greater than or equal to the minimum. Any account
1936		/// can call this.
1937		#[pallet::call_index(24)]
1938		#[pallet::weight(T::WeightInfo::force_apply_min_commission())]
1939		pub fn force_apply_min_commission(
1940			origin: OriginFor<T>,
1941			validator_stash: T::AccountId,
1942		) -> DispatchResult {
1943			ensure_signed(origin)?;
1944			let min_commission = MinCommission::<T>::get();
1945			Validators::<T>::try_mutate_exists(validator_stash, |maybe_prefs| {
1946				maybe_prefs
1947					.as_mut()
1948					.map(|prefs| {
1949						(prefs.commission < min_commission)
1950							.then(|| prefs.commission = min_commission)
1951					})
1952					.ok_or(Error::<T>::NotStash)
1953			})?;
1954			Ok(())
1955		}
1956
1957		/// Sets the minimum amount of commission that each validators must maintain.
1958		///
1959		/// This call has lower privilege requirements than `set_staking_config` and can be called
1960		/// by the `T::AdminOrigin`. Root can always call this.
1961		#[pallet::call_index(25)]
1962		#[pallet::weight(T::WeightInfo::set_min_commission())]
1963		pub fn set_min_commission(origin: OriginFor<T>, new: Perbill) -> DispatchResult {
1964			T::AdminOrigin::ensure_origin(origin)?;
1965			MinCommission::<T>::put(new);
1966			Ok(())
1967		}
1968
1969		/// Pay out a page of the stakers behind a validator for the given era and page.
1970		///
1971		/// - `validator_stash` is the stash account of the validator.
1972		/// - `era` may be any era between `[current_era - history_depth; current_era]`.
1973		/// - `page` is the page index of nominators to pay out with value between 0 and
1974		///   `num_nominators / T::MaxExposurePageSize`.
1975		///
1976		/// The origin of this call must be _Signed_. Any account can call this function, even if
1977		/// it is not one of the stakers.
1978		///
1979		/// If a validator has more than [`Config::MaxExposurePageSize`] nominators backing
1980		/// them, then the list of nominators is paged, with each page being capped at
1981		/// [`Config::MaxExposurePageSize`.] If a validator has more than one page of nominators,
1982		/// the call needs to be made for each page separately in order for all the nominators
1983		/// backing a validator to receive the reward. The nominators are not sorted across pages
1984		/// and so it should not be assumed the highest staker would be on the topmost page and vice
1985		/// versa. If rewards are not claimed in [`Config::HistoryDepth`] eras, they are lost.
1986		#[pallet::call_index(26)]
1987		#[pallet::weight(T::WeightInfo::payout_stakers_alive_staked(T::MaxExposurePageSize::get()))]
1988		pub fn payout_stakers_by_page(
1989			origin: OriginFor<T>,
1990			validator_stash: T::AccountId,
1991			era: EraIndex,
1992			page: Page,
1993		) -> DispatchResultWithPostInfo {
1994			ensure_signed(origin)?;
1995			Self::do_payout_stakers_by_page(validator_stash, era, page)
1996		}
1997
1998		/// Migrates an account's `RewardDestination::Controller` to
1999		/// `RewardDestination::Account(controller)`.
2000		///
2001		/// Effects will be felt instantly (as soon as this function is completed successfully).
2002		///
2003		/// This will waive the transaction fee if the `payee` is successfully migrated.
2004		#[pallet::call_index(27)]
2005		#[pallet::weight(T::WeightInfo::update_payee())]
2006		pub fn update_payee(
2007			origin: OriginFor<T>,
2008			controller: T::AccountId,
2009		) -> DispatchResultWithPostInfo {
2010			let _ = ensure_signed(origin)?;
2011			let ledger = Self::ledger(StakingAccount::Controller(controller.clone()))?;
2012
2013			ensure!(
2014				(Payee::<T>::get(&ledger.stash) == {
2015					#[allow(deprecated)]
2016					Some(RewardDestination::Controller)
2017				}),
2018				Error::<T>::NotController
2019			);
2020
2021			let _ = ledger
2022				.set_payee(RewardDestination::Account(controller))
2023				.defensive_proof("ledger should have been previously retrieved from storage.")?;
2024
2025			Ok(Pays::No.into())
2026		}
2027
2028		/// Updates a batch of controller accounts to their corresponding stash account if they are
2029		/// not the same. Ignores any controller accounts that do not exist, and does not operate if
2030		/// the stash and controller are already the same.
2031		///
2032		/// Effects will be felt instantly (as soon as this function is completed successfully).
2033		///
2034		/// The dispatch origin must be `T::AdminOrigin`.
2035		#[pallet::call_index(28)]
2036		#[pallet::weight(T::WeightInfo::deprecate_controller_batch(controllers.len() as u32))]
2037		pub fn deprecate_controller_batch(
2038			origin: OriginFor<T>,
2039			controllers: BoundedVec<T::AccountId, T::MaxControllersInDeprecationBatch>,
2040		) -> DispatchResultWithPostInfo {
2041			T::AdminOrigin::ensure_origin(origin)?;
2042
2043			// Ignore controllers that do not exist or are already the same as stash.
2044			let filtered_batch_with_ledger: Vec<_> = controllers
2045				.iter()
2046				.filter_map(|controller| {
2047					let ledger = Self::ledger(StakingAccount::Controller(controller.clone()));
2048					ledger.ok().map_or(None, |ledger| {
2049						// If the controller `RewardDestination` is still the deprecated
2050						// `Controller` variant, skip deprecating this account.
2051						let payee_deprecated = Payee::<T>::get(&ledger.stash) == {
2052							#[allow(deprecated)]
2053							Some(RewardDestination::Controller)
2054						};
2055
2056						if ledger.stash != *controller && !payee_deprecated {
2057							Some(ledger)
2058						} else {
2059							None
2060						}
2061					})
2062				})
2063				.collect();
2064
2065			// Update unique pairs.
2066			let mut failures = 0;
2067			for ledger in filtered_batch_with_ledger {
2068				let _ = ledger.clone().set_controller_to_stash().map_err(|_| failures += 1);
2069			}
2070			Self::deposit_event(Event::<T>::ControllerBatchDeprecated { failures });
2071
2072			Ok(Some(T::WeightInfo::deprecate_controller_batch(controllers.len() as u32)).into())
2073		}
2074
2075		/// Restores the state of a ledger which is in an inconsistent state.
2076		///
2077		/// The requirements to restore a ledger are the following:
2078		/// * The stash is bonded; or
2079		/// * The stash is not bonded but it has a staking lock left behind; or
2080		/// * If the stash has an associated ledger and its state is inconsistent; or
2081		/// * If the ledger is not corrupted *but* its staking lock is out of sync.
2082		///
2083		/// The `maybe_*` input parameters will overwrite the corresponding data and metadata of the
2084		/// ledger associated with the stash. If the input parameters are not set, the ledger will
2085		/// be reset values from on-chain state.
2086		#[pallet::call_index(29)]
2087		#[pallet::weight(T::WeightInfo::restore_ledger())]
2088		pub fn restore_ledger(
2089			origin: OriginFor<T>,
2090			stash: T::AccountId,
2091			maybe_controller: Option<T::AccountId>,
2092			maybe_total: Option<BalanceOf<T>>,
2093			maybe_unlocking: Option<BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>>,
2094		) -> DispatchResult {
2095			T::AdminOrigin::ensure_origin(origin)?;
2096
2097			// cannot restore ledger for virtual stakers.
2098			ensure!(!Self::is_virtual_staker(&stash), Error::<T>::VirtualStakerNotAllowed);
2099
2100			let current_lock = asset::staked::<T>(&stash);
2101			let stash_balance = asset::stakeable_balance::<T>(&stash);
2102
2103			let (new_controller, new_total) = match Self::inspect_bond_state(&stash) {
2104				Ok(LedgerIntegrityState::Corrupted) => {
2105					let new_controller = maybe_controller.unwrap_or(stash.clone());
2106
2107					let new_total = if let Some(total) = maybe_total {
2108						let new_total = total.min(stash_balance);
2109						// enforce lock == ledger.amount.
2110						asset::update_stake::<T>(&stash, new_total);
2111						new_total
2112					} else {
2113						current_lock
2114					};
2115
2116					Ok((new_controller, new_total))
2117				},
2118				Ok(LedgerIntegrityState::CorruptedKilled) => {
2119					if current_lock == Zero::zero() {
2120						// this case needs to restore both lock and ledger, so the new total needs
2121						// to be given by the called since there's no way to restore the total
2122						// on-chain.
2123						ensure!(maybe_total.is_some(), Error::<T>::CannotRestoreLedger);
2124						Ok((
2125							stash.clone(),
2126							maybe_total.expect("total exists as per the check above; qed."),
2127						))
2128					} else {
2129						Ok((stash.clone(), current_lock))
2130					}
2131				},
2132				Ok(LedgerIntegrityState::LockCorrupted) => {
2133					// ledger is not corrupted but its locks are out of sync. In this case, we need
2134					// to enforce a new ledger.total and staking lock for this stash.
2135					let new_total =
2136						maybe_total.ok_or(Error::<T>::CannotRestoreLedger)?.min(stash_balance);
2137					asset::update_stake::<T>(&stash, new_total);
2138
2139					Ok((stash.clone(), new_total))
2140				},
2141				Err(Error::<T>::BadState) => {
2142					// the stash and ledger do not exist but lock is lingering.
2143					asset::kill_stake::<T>(&stash);
2144					ensure!(
2145						Self::inspect_bond_state(&stash) == Err(Error::<T>::NotStash),
2146						Error::<T>::BadState
2147					);
2148
2149					return Ok(());
2150				},
2151				Ok(LedgerIntegrityState::Ok) | Err(_) => Err(Error::<T>::CannotRestoreLedger),
2152			}?;
2153
2154			// re-bond stash and controller tuple.
2155			Bonded::<T>::insert(&stash, &new_controller);
2156
2157			// resoter ledger state.
2158			let mut ledger = StakingLedger::<T>::new(stash.clone(), new_total);
2159			ledger.controller = Some(new_controller);
2160			ledger.unlocking = maybe_unlocking.unwrap_or_default();
2161			ledger.update()?;
2162
2163			ensure!(
2164				Self::inspect_bond_state(&stash) == Ok(LedgerIntegrityState::Ok),
2165				Error::<T>::BadState
2166			);
2167			Ok(())
2168		}
2169
2170		/// Adjusts the staking ledger by withdrawing any excess staked amount.
2171		///
2172		/// This function corrects cases where a user's recorded stake in the ledger
2173		/// exceeds their actual staked funds. This situation can arise due to cases such as
2174		/// external slashing by another pallet, leading to an inconsistency between the ledger
2175		/// and the actual stake.
2176		#[pallet::call_index(32)]
2177		#[pallet::weight(T::DbWeight::get().reads_writes(2, 1))]
2178		pub fn withdraw_overstake(origin: OriginFor<T>, stash: T::AccountId) -> DispatchResult {
2179			let _ = ensure_signed(origin)?;
2180
2181			// Virtual stakers are controlled by some other pallet.
2182			ensure!(!Self::is_virtual_staker(&stash), Error::<T>::VirtualStakerNotAllowed);
2183
2184			let ledger = Self::ledger(Stash(stash.clone()))?;
2185			let stash_balance = T::Currency::free_balance(&stash);
2186
2187			// Ensure there is an overstake.
2188			ensure!(ledger.total > stash_balance, Error::<T>::BoundNotMet);
2189
2190			let force_withdraw_amount = ledger.total.defensive_saturating_sub(stash_balance);
2191
2192			// Update the ledger by withdrawing excess stake.
2193			ledger.update_total_stake(stash_balance).update()?;
2194
2195			// Ensure lock is updated.
2196			debug_assert_eq!(T::Currency::balance_locked(crate::STAKING_ID, &stash), stash_balance);
2197
2198			Self::deposit_event(Event::<T>::Withdrawn { stash, amount: force_withdraw_amount });
2199
2200			Ok(())
2201		}
2202	}
2203}
2204
2205/// Check that list is sorted and has no duplicates.
2206fn is_sorted_and_unique(list: &[u32]) -> bool {
2207	list.windows(2).all(|w| w[0] < w[1])
2208}