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