remove OnStakerSlash replace with OnStakingEvents (#14527)

* remove 'OnStakerSlash', replace with 'OnStakingEvents'

* fix other features in pallets

* small fixes

* fix docs

* fix docs

* fix docs

* Update primitives/staking/src/lib.rs

Co-authored-by: Gonçalo Pestana <g6pestana@gmail.com>

---------

Co-authored-by: Gonçalo Pestana <g6pestana@gmail.com>
This commit is contained in:
Kian Paimani
2023-07-09 14:46:18 +02:00
committed by GitHub
parent 53244d64bd
commit 6dd625d568
28 changed files with 261 additions and 177 deletions
+2 -2
View File
@@ -182,7 +182,7 @@ impl onchain::Config for OnChainSeqPhragmen {
impl pallet_staking::Config for Test {
type MaxNominations = ConstU32<16>;
type RewardRemainder = ();
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
@@ -204,7 +204,7 @@ impl pallet_staking::Config for Test {
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = ConstU32<84>;
type OnStakerSlash = ();
type EventListeners = ();
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
+2 -2
View File
@@ -206,7 +206,7 @@ impl onchain::Config for OnChainSeqPhragmen {
impl pallet_staking::Config for Test {
type MaxNominations = ConstU32<16>;
type RewardRemainder = ();
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
@@ -228,7 +228,7 @@ impl pallet_staking::Config for Test {
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = ConstU32<84>;
type OnStakerSlash = ();
type EventListeners = ();
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
@@ -265,7 +265,7 @@ impl pallet_staking::Config for Runtime {
type Currency = Balances;
type CurrencyBalance = Balance;
type UnixTime = Timestamp;
type CurrencyToVote = traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
type Slash = (); // burn slashes
@@ -285,7 +285,7 @@ impl pallet_staking::Config for Runtime {
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = HistoryDepth;
type OnStakerSlash = ();
type EventListeners = ();
type WeightInfo = pallet_staking::weights::SubstrateWeight<Runtime>;
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
}
@@ -26,6 +26,7 @@ sp-io = { version = "23.0.0", default-features = false, path = "../../primitives
sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" }
sp-runtime = { version = "24.0.0", default-features = false, path = "../../primitives/runtime" }
sp-std = { version = "8.0.0", default-features = false, path = "../../primitives/std" }
sp-staking = { default-features = false, path = "../../primitives/staking" }
[dev-dependencies]
pallet-balances = { version = "4.0.0-dev", path = "../balances" }
@@ -101,9 +101,9 @@
use codec::{Decode, Encode};
use frame_support::{
traits::{
defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency,
CurrencyToVote, Get, InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced,
ReservableCurrency, SortedMembers, WithdrawReasons,
defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, Get,
InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency,
SortedMembers, WithdrawReasons,
},
weights::Weight,
};
@@ -113,6 +113,7 @@ use sp_runtime::{
traits::{Saturating, StaticLookup, Zero},
DispatchError, Perbill, RuntimeDebug,
};
use sp_staking::currency_to_vote::CurrencyToVote;
use sp_std::{cmp::Ordering, prelude::*};
#[cfg(any(feature = "try-runtime", test))]
@@ -1424,7 +1425,7 @@ mod tests {
type PalletId = ElectionsPhragmenPalletId;
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type ChangeMembers = TestChangeMembers;
type InitializeMembers = ();
type CandidacyBond = CandidacyBond;
+2 -2
View File
@@ -137,7 +137,7 @@ impl pallet_staking::Config for Runtime {
type Currency = Balances;
type CurrencyBalance = Balance;
type UnixTime = pallet_timestamp::Pallet<Self>;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
type Slash = ();
@@ -157,7 +157,7 @@ impl pallet_staking::Config for Runtime {
type VoterList = pallet_staking::UseNominatorsAndValidatorsMap<Self>;
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type OnStakerSlash = ();
type EventListeners = ();
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
+2 -2
View File
@@ -187,7 +187,7 @@ impl onchain::Config for OnChainSeqPhragmen {
impl pallet_staking::Config for Test {
type MaxNominations = ConstU32<16>;
type RewardRemainder = ();
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
@@ -209,7 +209,7 @@ impl pallet_staking::Config for Test {
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = ConstU32<84>;
type OnStakerSlash = ();
type EventListeners = ();
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
@@ -99,7 +99,7 @@ impl pallet_staking::Config for Runtime {
type Currency = Balances;
type CurrencyBalance = Balance;
type UnixTime = pallet_timestamp::Pallet<Self>;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
type Slash = ();
@@ -120,7 +120,7 @@ impl pallet_staking::Config for Runtime {
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = ConstU32<84>;
type OnStakerSlash = Pools;
type EventListeners = Pools;
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
+3 -7
View File
@@ -326,7 +326,7 @@
//!
//! This section assumes that the slash computation is executed by
//! `pallet_staking::StakingLedger::slash`, which passes the information to this pallet via
//! [`sp_staking::OnStakerSlash::on_slash`].
//! [`sp_staking::OnStakingUpdate::on_slash`].
//!
//! Unbonding pools need to be slashed to ensure all nominators whom where in the bonded pool while
//! it was backing a validator that equivocated are punished. Without these measures a member could
@@ -341,10 +341,6 @@
//! in addition to the unbonding pools. For maintenance simplicity these are not implemented.
//! Related: <https://github.com/paritytech/substrate/issues/10860>
//!
//! **Relevant methods:**
//!
//! * [`Pallet::on_slash`]
//!
//! ### Limitations
//!
//! * PoolMembers cannot vote with their staked funds because they are transferred into the pools
@@ -375,7 +371,7 @@ use sp_runtime::{
},
FixedPointNumber, Perbill,
};
use sp_staking::{EraIndex, OnStakerSlash, StakingInterface};
use sp_staking::{EraIndex, StakingInterface};
use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, ops::Div, vec::Vec};
#[cfg(any(feature = "try-runtime", feature = "fuzzing", test, debug_assertions))]
@@ -3265,7 +3261,7 @@ impl<T: Config> Pallet<T> {
}
}
impl<T: Config> OnStakerSlash<T::AccountId, BalanceOf<T>> for Pallet<T> {
impl<T: Config> sp_staking::OnStakingUpdate<T::AccountId, BalanceOf<T>> for Pallet<T> {
fn on_slash(
pool_account: &T::AccountId,
// Bonded balance is always read directly from staking, therefore we don't need to update
@@ -47,6 +47,7 @@ impl StakingMock {
impl sp_staking::StakingInterface for StakingMock {
type Balance = Balance;
type AccountId = AccountId;
type CurrencyToVote = ();
fn minimum_nominator_bond() -> Self::Balance {
StakingMinBond::get()
@@ -113,7 +113,7 @@ impl pallet_staking::Config for Runtime {
type Currency = Balances;
type CurrencyBalance = Balance;
type UnixTime = pallet_timestamp::Pallet<Self>;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
type Slash = ();
@@ -134,7 +134,7 @@ impl pallet_staking::Config for Runtime {
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = ConstU32<84>;
type OnStakerSlash = Pools;
type EventListeners = Pools;
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
@@ -162,7 +162,7 @@ impl pallet_staking::Config for Test {
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
type UnixTime = pallet_timestamp::Pallet<Self>;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
type Slash = ();
@@ -182,7 +182,7 @@ impl pallet_staking::Config for Test {
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = ConstU32<84>;
type OnStakerSlash = ();
type EventListeners = ();
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
+2 -13
View File
@@ -149,17 +149,6 @@ impl onchain::Config for OnChainSeqPhragmen {
type TargetsBound = ConstU32<{ u32::MAX }>;
}
pub struct OnStakerSlashMock<T: Config>(core::marker::PhantomData<T>);
impl<T: Config> sp_staking::OnStakerSlash<AccountId, Balance> for OnStakerSlashMock<T> {
fn on_slash(
_pool_account: &AccountId,
slashed_bonded: Balance,
slashed_chunks: &BTreeMap<EraIndex, Balance>,
) {
LedgerSlashPerEra::set((slashed_bonded, slashed_chunks.clone()));
}
}
parameter_types! {
pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
pub static Offset: BlockNumber = 0;
@@ -176,7 +165,7 @@ impl pallet_staking::Config for Test {
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
type UnixTime = Timestamp;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
type Slash = ();
@@ -196,7 +185,7 @@ impl pallet_staking::Config for Test {
type MaxUnlockingChunks = ConstU32<32>;
type HistoryDepth = ConstU32<84>;
type VoterList = pallet_staking::UseNominatorsAndValidatorsMap<Self>;
type OnStakerSlash = OnStakerSlashMock<Test>;
type EventListeners = ();
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
@@ -164,7 +164,7 @@ impl pallet_staking::Config for Test {
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
type UnixTime = pallet_timestamp::Pallet<Self>;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
type Slash = ();
@@ -184,7 +184,7 @@ impl pallet_staking::Config for Test {
type HistoryDepth = ConstU32<84>;
type VoterList = pallet_staking::UseNominatorsAndValidatorsMap<Self>;
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type OnStakerSlash = ();
type EventListeners = ();
type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig;
type WeightInfo = ();
}
+2 -2
View File
@@ -26,13 +26,13 @@ use frame_election_provider_support::SortedListProvider;
use frame_support::{
dispatch::UnfilteredDispatchable,
pallet_prelude::*,
traits::{Currency, CurrencyToVote, Get, Imbalance},
traits::{Currency, Get, Imbalance},
};
use sp_runtime::{
traits::{Bounded, One, StaticLookup, TrailingZeroInput, Zero},
Perbill, Percent,
};
use sp_staking::SessionIndex;
use sp_staking::{currency_to_vote::CurrencyToVote, SessionIndex};
use sp_std::prelude::*;
pub use frame_benchmarking::v1::{
+3 -4
View File
@@ -314,7 +314,7 @@ use sp_runtime::{
pub use sp_staking::StakerStatus;
use sp_staking::{
offence::{Offence, OffenceError, ReportOffence},
EraIndex, SessionIndex,
EraIndex, OnStakingUpdate, SessionIndex,
};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
pub use weights::WeightInfo;
@@ -549,7 +549,7 @@ impl<T: Config> StakingLedger<T> {
///
/// `slash_era` is the era in which the slash (which is being enacted now) actually happened.
///
/// This calls `Config::OnStakerSlash::on_slash` with information as to how the slash was
/// This calls `Config::OnStakingUpdate::on_slash` with information as to how the slash was
/// applied.
pub fn slash(
&mut self,
@@ -562,7 +562,6 @@ impl<T: Config> StakingLedger<T> {
}
use sp_runtime::PerThing as _;
use sp_staking::OnStakerSlash as _;
let mut remaining_slash = slash_amount;
let pre_slash_total = self.total;
@@ -667,7 +666,7 @@ impl<T: Config> StakingLedger<T> {
// clean unlocking chunks that are set to zero.
self.unlocking.retain(|c| !c.value.is_zero());
T::OnStakerSlash::on_slash(&self.stash, self.active, &slashed_unlocking);
T::EventListeners::on_slash(&self.stash, self.active, &slashed_unlocking);
pre_slash_total.saturating_sub(self.total)
}
}
+10 -5
View File
@@ -236,7 +236,6 @@ parameter_types! {
pub static HistoryDepth: u32 = 80;
pub static MaxUnlockingChunks: u32 = 32;
pub static RewardOnUnbalanceWasCalled: bool = false;
pub static LedgerSlashPerEra: (BalanceOf<Test>, BTreeMap<EraIndex, BalanceOf<Test>>) = (Zero::zero(), BTreeMap::new());
pub static MaxWinners: u32 = 100;
}
@@ -268,8 +267,14 @@ impl OnUnbalanced<PositiveImbalanceOf<Test>> for MockReward {
}
}
pub struct OnStakerSlashMock<T: Config>(core::marker::PhantomData<T>);
impl<T: Config> sp_staking::OnStakerSlash<AccountId, Balance> for OnStakerSlashMock<T> {
parameter_types! {
pub static LedgerSlashPerEra:
(BalanceOf<Test>, BTreeMap<EraIndex, BalanceOf<Test>>) =
(Zero::zero(), BTreeMap::new());
}
pub struct EventListenerMock;
impl OnStakingUpdate<AccountId, Balance> for EventListenerMock {
fn on_slash(
_pool_account: &AccountId,
slashed_bonded: Balance,
@@ -284,7 +289,7 @@ impl crate::pallet::pallet::Config for Test {
type Currency = Balances;
type CurrencyBalance = <Self as pallet_balances::Config>::Balance;
type UnixTime = Timestamp;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type RewardRemainder = RewardRemainderMock;
type RuntimeEvent = RuntimeEvent;
type Slash = ();
@@ -305,7 +310,7 @@ impl crate::pallet::pallet::Config for Test {
type TargetList = UseValidatorsMap<Self>;
type MaxUnlockingChunks = MaxUnlockingChunks;
type HistoryDepth = HistoryDepth;
type OnStakerSlash = OnStakerSlashMock<Test>;
type EventListeners = EventListenerMock;
type BenchmarkingConfig = TestBenchmarkingConfig;
type WeightInfo = ();
}
+4 -3
View File
@@ -26,8 +26,8 @@ use frame_support::{
dispatch::WithPostDispatchInfo,
pallet_prelude::*,
traits::{
Currency, CurrencyToVote, Defensive, DefensiveResult, EstimateNextNewSession, Get,
Imbalance, LockableCurrency, OnUnbalanced, TryCollect, UnixTime, WithdrawReasons,
Currency, Defensive, DefensiveResult, EstimateNextNewSession, Get, Imbalance,
LockableCurrency, OnUnbalanced, TryCollect, UnixTime, WithdrawReasons,
},
weights::Weight,
};
@@ -38,6 +38,7 @@ use sp_runtime::{
Perbill,
};
use sp_staking::{
currency_to_vote::CurrencyToVote,
offence::{DisableStrategy, OffenceDetails, OnOffenceHandler},
EraIndex, SessionIndex, Stake, StakingInterface,
};
@@ -1568,10 +1569,10 @@ impl<T: Config> SortedListProvider<T::AccountId> for UseNominatorsAndValidatorsM
}
}
// NOTE: in this entire impl block, the assumption is that `who` is a stash account.
impl<T: Config> StakingInterface for Pallet<T> {
type AccountId = T::AccountId;
type Balance = BalanceOf<T>;
type CurrencyToVote = T::CurrencyToVote;
fn minimum_nominator_bond() -> Self::Balance {
MinNominatorBond::<T>::get()
+7 -5
View File
@@ -24,7 +24,7 @@ use frame_support::{
dispatch::Codec,
pallet_prelude::*,
traits::{
Currency, CurrencyToVote, Defensive, DefensiveResult, DefensiveSaturating, EnsureOrigin,
Currency, Defensive, DefensiveResult, DefensiveSaturating, EnsureOrigin,
EstimateNextNewSession, Get, LockIdentifier, LockableCurrency, OnUnbalanced, TryCollect,
UnixTime,
},
@@ -113,7 +113,7 @@ pub mod pallet {
/// in 128.
/// Consequently, the backward convert is used convert the u128s from sp-elections back to a
/// [`BalanceOf`].
type CurrencyToVote: CurrencyToVote<BalanceOf<Self>>;
type CurrencyToVote: sp_staking::currency_to_vote::CurrencyToVote<BalanceOf<Self>>;
/// Something that provides the election functionality.
type ElectionProvider: ElectionProvider<
@@ -261,9 +261,11 @@ pub mod pallet {
#[pallet::constant]
type MaxUnlockingChunks: Get<u32>;
/// A hook called when any staker is slashed. Mostly likely this can be a no-op unless
/// other pallets exist that are affected by slashing per-staker.
type OnStakerSlash: sp_staking::OnStakerSlash<Self::AccountId, BalanceOf<Self>>;
/// Something that listens to staking updates and performs actions based on the data it
/// receives.
///
/// WARNING: this only reports slashing events for the time being.
type EventListeners: sp_staking::OnStakingUpdate<Self::AccountId, BalanceOf<Self>>;
/// Some parameters of the benchmarking.
type BenchmarkingConfig: BenchmarkingConfig;
+1 -4
View File
@@ -102,10 +102,7 @@ pub use dispatch::{
};
mod voting;
pub use voting::{
ClassCountOf, CurrencyToVote, PollStatus, Polling, SaturatingCurrencyToVote,
U128CurrencyToVote, VoteTally,
};
pub use voting::{ClassCountOf, PollStatus, Polling, VoteTally};
mod preimages;
pub use preimages::{Bounded, BoundedInline, FetchResult, Hash, QueryPreimage, StorePreimage};
+1 -72
View File
@@ -20,81 +20,10 @@
use crate::dispatch::{DispatchError, Parameter};
use codec::{HasCompact, MaxEncodedLen};
use sp_arithmetic::{
traits::{SaturatedConversion, UniqueSaturatedFrom, UniqueSaturatedInto},
Perbill,
};
use sp_arithmetic::Perbill;
use sp_runtime::traits::Member;
use sp_std::prelude::*;
/// A trait similar to `Convert` to convert values from `B` an abstract balance type
/// into u64 and back from u128. (This conversion is used in election and other places where complex
/// calculation over balance type is needed)
///
/// Total issuance of the currency is passed in, but an implementation of this trait may or may not
/// use it.
///
/// # WARNING
///
/// the total issuance being passed in implies that the implementation must be aware of the fact
/// that its values can affect the outcome. This implies that if the vote value is dependent on the
/// total issuance, it should never ber written to storage for later re-use.
pub trait CurrencyToVote<B> {
/// Convert balance to u64.
fn to_vote(value: B, issuance: B) -> u64;
/// Convert u128 to balance.
fn to_currency(value: u128, issuance: B) -> B;
}
/// An implementation of `CurrencyToVote` tailored for chain's that have a balance type of u128.
///
/// The factor is the `(total_issuance / u64::MAX).max(1)`, represented as u64. Let's look at the
/// important cases:
///
/// If the chain's total issuance is less than u64::MAX, this will always be 1, which means that
/// the factor will not have any effect. In this case, any account's balance is also less. Thus,
/// both of the conversions are basically an `as`; Any balance can fit in u64.
///
/// If the chain's total issuance is more than 2*u64::MAX, then a factor might be multiplied and
/// divided upon conversion.
pub struct U128CurrencyToVote;
impl U128CurrencyToVote {
fn factor(issuance: u128) -> u128 {
(issuance / u64::MAX as u128).max(1)
}
}
impl CurrencyToVote<u128> for U128CurrencyToVote {
fn to_vote(value: u128, issuance: u128) -> u64 {
(value / Self::factor(issuance)).saturated_into()
}
fn to_currency(value: u128, issuance: u128) -> u128 {
value.saturating_mul(Self::factor(issuance))
}
}
/// A naive implementation of `CurrencyConvert` that simply saturates all conversions.
///
/// # Warning
///
/// This is designed to be used mostly for testing. Use with care, and think about the consequences.
pub struct SaturatingCurrencyToVote;
impl<B: UniqueSaturatedInto<u64> + UniqueSaturatedFrom<u128>> CurrencyToVote<B>
for SaturatingCurrencyToVote
{
fn to_vote(value: B, _: B) -> u64 {
value.unique_saturated_into()
}
fn to_currency(value: u128, _: B) -> B {
B::unique_saturated_from(value)
}
}
pub trait VoteTally<Votes, Class> {
fn new(_: Class) -> Self;
fn ayes(&self, class: Class) -> Votes;