Skip to content
mod.rs 76.4 KiB
Newer Older
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Staking FRAME Pallet.

use frame_election_provider_support::{
	ElectionProvider, ElectionProviderBase, SortedListProvider, VoteWeight,
};
use frame_support::{
	pallet_prelude::*,
	traits::{
		Currency, Defensive, DefensiveSaturating, EnsureOrigin, EstimateNextNewSession, Get,
		InspectLockableCurrency, LockableCurrency, OnUnbalanced, UnixTime, WithdrawReasons,
	weights::Weight,
	BoundedVec,
use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
	traits::{SaturatedConversion, StaticLookup, Zero},
	ArithmeticError, Perbill, Percent,
use sp_staking::{
	StakingAccount::{self, Controller, Stash},
};
	slashing, weights::WeightInfo, AccountIdLookupOf, ActiveEraInfo, BalanceOf, DisablingStrategy,
	EraPayout, EraRewardPoints, Exposure, ExposurePage, Forcing, LedgerIntegrityState,
	MaxNominationsOf, NegativeImbalanceOf, Nominations, NominationsQuota, PositiveImbalanceOf,
	RewardDestination, SessionInterface, StakingLedger, UnappliedSlash, UnlockChunk,
	ValidatorPrefs,
// The speculative number of spans are used as an input of the weight annotation of
// [`Call::unbond`], as the post dispatch weight may depend on the number of slashing span on the
// account which is not provided as an input. The value set should be conservative but sensible.
pub(crate) const SPECULATIVE_NUM_SPANS: u32 = 32;

#[frame_support::pallet]
pub mod pallet {
	use frame_election_provider_support::ElectionDataProvider;

	use crate::{BenchmarkingConfig, PagedExposureMetadata};
	const STORAGE_VERSION: StorageVersion = StorageVersion::new(15);
	#[pallet::storage_version(STORAGE_VERSION)]
	/// Possible operations on the configuration values of this pallet.
	#[derive(TypeInfo, Debug, Clone, Encode, Decode, PartialEq)]
	pub enum ConfigOp<T: Default + Codec> {
		/// Don't change.
		Noop,
		/// Set the given value.
		Set(T),
		/// Remove from storage.
		Remove,
	}

	pub trait Config: frame_system::Config {
				Self::AccountId,
				Moment = BlockNumberFor<Self>,
				Balance = Self::CurrencyBalance,
			> + InspectLockableCurrency<Self::AccountId>;
		/// Just the `Currency::Balance` type; we have this item to allow us to constrain it to
		/// `From<u64>`.
		type CurrencyBalance: sp_runtime::traits::AtLeast32BitUnsigned
			+ codec::FullCodec
			+ Copy
			+ MaybeSerializeDeserialize
			+ sp_std::fmt::Debug
			+ Default
			+ From<u64>
			+ TypeInfo
			+ MaxEncodedLen;
		/// Time used for computing era duration.
		///
		/// It is guaranteed to start being called from the first `on_finalize`. Thus value at
		/// genesis is not used.
		/// Convert a balance into a number used for election calculation. This must fit into a
		/// `u64` but is allowed to be sensibly lossy. The `u64` is used to communicate with the
thiolliere's avatar
thiolliere committed
		/// [`frame_election_provider_support`] crate which accepts u64 numbers and does operations
		/// in 128.
		/// Consequently, the backward convert is used convert the u128s from sp-elections back to a
		/// [`BalanceOf`].
		type CurrencyToVote: sp_staking::currency_to_vote::CurrencyToVote<BalanceOf<Self>>;

		/// Something that provides the election functionality.
		type ElectionProvider: ElectionProvider<
			AccountId = Self::AccountId,
			BlockNumber = BlockNumberFor<Self>,
			// we only accept an election provider that has staking as data provider.
			DataProvider = Pallet<Self>,
		>;
		/// Something that provides the election functionality at genesis.
		type GenesisElectionProvider: ElectionProvider<
			AccountId = Self::AccountId,
			BlockNumber = BlockNumberFor<Self>,
		/// Something that defines the maximum number of nominations per nominator.
		type NominationsQuota: NominationsQuota<BalanceOf<Self>>;
		/// Number of eras to keep in history.
		///
		/// Following information is kept for eras in `[current_era -
		/// HistoryDepth, current_era]`: `ErasStakers`, `ErasStakersClipped`,
		/// `ErasValidatorPrefs`, `ErasValidatorReward`, `ErasRewardPoints`,
		/// `ErasTotalStake`, `ErasStartSessionIndex`, `ClaimedRewards`, `ErasStakersPaged`,
		/// `ErasStakersOverview`.
		///
		/// Must be more than the number of eras delayed by session.
		/// I.e. active era must always be in history. I.e. `active_era >
		/// current_era - history_depth` must be guaranteed.
		///
		/// If migrating an existing pallet from storage value to config value,
		/// this should be set to same value or greater as in storage.
		///
		/// Note: `HistoryDepth` is used as the upper bound for the `BoundedVec`
		/// item `StakingLedger.legacy_claimed_rewards`. Setting this value lower than
		/// the existing value can lead to inconsistencies in the
		/// `StakingLedger` and will need to be handled properly in a migration.
		/// The test `reducing_history_depth_abrupt` shows this effect.
		#[pallet::constant]
		type HistoryDepth: Get<u32>;

		/// Tokens have been minted and are unused for validator-reward.
		/// See [Era payout](./index.html#era-payout).
		type RewardRemainder: OnUnbalanced<NegativeImbalanceOf<Self>>;

		/// The overarching event type.
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

		/// Handler for the unbalanced reduction when slashing a staker.
		type Slash: OnUnbalanced<NegativeImbalanceOf<Self>>;

		/// Handler for the unbalanced increment when rewarding a staker.
		/// NOTE: in most cases, the implementation of `OnUnbalanced` should modify the total
		/// issuance.
		type Reward: OnUnbalanced<PositiveImbalanceOf<Self>>;

		/// Number of sessions per era.
		#[pallet::constant]
		type SessionsPerEra: Get<SessionIndex>;

		/// Number of eras that staked funds must remain bonded for.
		#[pallet::constant]
		type BondingDuration: Get<EraIndex>;

		/// Number of eras that slashes are deferred by, after computation.
		///
		/// This should be less than the bonding duration. Set to 0 if slashes
		/// should be applied immediately, without opportunity for intervention.
		#[pallet::constant]
		type SlashDeferDuration: Get<EraIndex>;

		/// The origin which can manage less critical staking parameters that does not require root.
		///
		/// Supported actions: (1) cancel deferred slash, (2) set minimum commission.
		type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;

		/// Interface for interacting with a session pallet.
		type SessionInterface: SessionInterface<Self::AccountId>;

		/// The payout for validators and the system for the current era.
		/// See [Era payout](./index.html#era-payout).
Loading full blame...