diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 6c0bbc33a4e3d..3ea66e937e83c 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -305,7 +305,7 @@ use frame_support::{ }; use pallet_session::historical; use sp_runtime::{ - Percent, Perbill, PerU16, InnerOf, RuntimeDebug, DispatchError, + Percent, Perbill, PerU16, RuntimeDebug, DispatchError, curve::PiecewiseLinear, traits::{ Convert, Zero, StaticLookup, CheckedSub, Saturating, SaturatedConversion, @@ -2991,10 +2991,7 @@ impl Module { /// No storage item is updated. pub fn do_phragmen( iterations: usize, - ) -> Option> - where - ExtendedBalance: From>, - { + ) -> Option> { let weight_of = Self::slashable_balance_of_fn(); let mut all_nominators: Vec<(T::AccountId, VoteWeight, Vec)> = Vec::new(); let mut all_validators = Vec::new(); diff --git a/frame/staking/src/offchain_election.rs b/frame/staking/src/offchain_election.rs index 2ab29b7105d9c..4f80d75086e7e 100644 --- a/frame/staking/src/offchain_election.rs +++ b/frame/staking/src/offchain_election.rs @@ -29,7 +29,7 @@ use sp_npos_elections::{ ExtendedBalance, CompactSolution, }; use sp_runtime::{ - offchain::storage::StorageValueRef, traits::TrailingZeroInput, PerThing, RuntimeDebug, + offchain::storage::StorageValueRef, traits::TrailingZeroInput, RuntimeDebug, }; use sp_std::{convert::TryInto, prelude::*}; @@ -326,10 +326,7 @@ pub fn prepare_submission( ) -> Result< (Vec, CompactAssignments, ElectionScore, ElectionSize), OffchainElectionError, -> -where - ExtendedBalance: From<::Inner>, -{ +> { // make sure that the snapshot is available. let snapshot_validators = >::snapshot_validators().ok_or(OffchainElectionError::SnapshotUnavailable)?; diff --git a/primitives/arithmetic/src/lib.rs b/primitives/arithmetic/src/lib.rs index ca02df0d1d4bb..9b1e8711da8c6 100644 --- a/primitives/arithmetic/src/lib.rs +++ b/primitives/arithmetic/src/lib.rs @@ -114,19 +114,16 @@ impl_normalize_for_numeric!(u8, u16, u32, u64, u128); impl Normalizable

for Vec

{ fn normalize(&self, targeted_sum: P) -> Result, &'static str> { - let inners = self - .iter() - .map(|p| p.clone().deconstruct().into()) - .collect::>(); - - let normalized = normalize(inners.as_ref(), targeted_sum.deconstruct().into())?; - - Ok( - normalized - .into_iter() - .map(|i: UpperOf

| P::from_parts(i.saturated_into())) - .collect() - ) + let uppers = + self.iter().map(|p| >::from(p.clone().deconstruct())).collect::>(); + + let normalized = + normalize(uppers.as_ref(), >::from(targeted_sum.deconstruct()))?; + + Ok(normalized + .into_iter() + .map(|i: UpperOf

| P::from_parts(i.saturated_into::())) + .collect()) } } diff --git a/primitives/arithmetic/src/per_things.rs b/primitives/arithmetic/src/per_things.rs index c6a31a0ffe869..5c86e55c2f4e8 100644 --- a/primitives/arithmetic/src/per_things.rs +++ b/primitives/arithmetic/src/per_things.rs @@ -22,6 +22,7 @@ use sp_std::{ops, fmt, prelude::*, convert::TryInto}; use codec::{Encode, CompactAs}; use crate::traits::{ SaturatedConversion, UniqueSaturatedInto, Saturating, BaseArithmetic, Bounded, Zero, Unsigned, + One, }; use sp_debug_derive::RuntimeDebug; @@ -37,13 +38,17 @@ pub trait PerThing: Sized + Saturating + Copy + Default + Eq + PartialEq + Ord + PartialOrd + Bounded + fmt::Debug { /// The data type used to build this per-thingy. - type Inner: BaseArithmetic + Unsigned + Copy + fmt::Debug; + type Inner: BaseArithmetic + Unsigned + Copy + Into + fmt::Debug; /// A data type larger than `Self::Inner`, used to avoid overflow in some computations. /// It must be able to compute `ACCURACY^2`. - type Upper: - BaseArithmetic + Copy + From + TryInto + - UniqueSaturatedInto + Unsigned + fmt::Debug; + type Upper: BaseArithmetic + + Copy + + From + + TryInto + + UniqueSaturatedInto + + Unsigned + + fmt::Debug; /// The accuracy of this type. const ACCURACY: Self::Inner; @@ -65,14 +70,14 @@ pub trait PerThing: fn from_percent(x: Self::Inner) -> Self { let a: Self::Inner = x.min(100.into()); let b: Self::Inner = 100.into(); - Self::from_rational_approximation(a, b) + Self::from_rational_approximation::(a, b) } /// Return the product of multiplication of this value by itself. fn square(self) -> Self { let p = Self::Upper::from(self.deconstruct()); let q = Self::Upper::from(Self::ACCURACY); - Self::from_rational_approximation(p * p, q * q) + Self::from_rational_approximation::(p * p, q * q) } /// Multiplication that always rounds down to a whole number. The standard `Mul` rounds to the @@ -91,8 +96,10 @@ pub trait PerThing: /// # } /// ``` fn mul_floor(self, b: N) -> N - where N: Clone + From + UniqueSaturatedInto + ops::Rem + - ops::Div + ops::Mul + ops::Add + Unsigned + where + N: Clone + UniqueSaturatedInto + ops::Rem + + ops::Div + ops::Mul + ops::Add + Unsigned, + Self::Inner: Into, { overflow_prune_mul::(b, self.deconstruct(), Rounding::Down) } @@ -113,8 +120,10 @@ pub trait PerThing: /// # } /// ``` fn mul_ceil(self, b: N) -> N - where N: Clone + From + UniqueSaturatedInto + ops::Rem + - ops::Div + ops::Mul + ops::Add + Unsigned + where + N: Clone + UniqueSaturatedInto + ops::Rem + + ops::Div + ops::Mul + ops::Add + Unsigned, + Self::Inner: Into { overflow_prune_mul::(b, self.deconstruct(), Rounding::Up) } @@ -129,9 +138,11 @@ pub trait PerThing: /// # } /// ``` fn saturating_reciprocal_mul(self, b: N) -> N - where N: Clone + From + UniqueSaturatedInto + ops::Rem + - ops::Div + ops::Mul + ops::Add + Saturating + - Unsigned + where + N: Clone + UniqueSaturatedInto + ops::Rem + + ops::Div + ops::Mul + ops::Add + Saturating + + Unsigned, + Self::Inner: Into, { saturating_reciprocal_mul::(b, self.deconstruct(), Rounding::Nearest) } @@ -149,9 +160,11 @@ pub trait PerThing: /// # } /// ``` fn saturating_reciprocal_mul_floor(self, b: N) -> N - where N: Clone + From + UniqueSaturatedInto + ops::Rem + - ops::Div + ops::Mul + ops::Add + Saturating + - Unsigned + where + N: Clone + UniqueSaturatedInto + ops::Rem + + ops::Div + ops::Mul + ops::Add + Saturating + + Unsigned, + Self::Inner: Into, { saturating_reciprocal_mul::(b, self.deconstruct(), Rounding::Down) } @@ -169,9 +182,11 @@ pub trait PerThing: /// # } /// ``` fn saturating_reciprocal_mul_ceil(self, b: N) -> N - where N: Clone + From + UniqueSaturatedInto + ops::Rem + - ops::Div + ops::Mul + ops::Add + Saturating + - Unsigned + where + N: Clone + UniqueSaturatedInto + ops::Rem + + ops::Div + ops::Mul + ops::Add + Saturating + + Unsigned, + Self::Inner: Into, { saturating_reciprocal_mul::(b, self.deconstruct(), Rounding::Up) } @@ -199,14 +214,16 @@ pub trait PerThing: /// # fn main () { /// // 989/100 is technically closer to 99%. /// assert_eq!( - /// Percent::from_rational_approximation(989u64, 1000), - /// Percent::from_parts(98), - /// ); + /// Percent::from_rational_approximation(989u64, 1000), + /// Percent::from_parts(98), + /// ); /// # } /// ``` fn from_rational_approximation(p: N, q: N) -> Self - where N: Clone + Ord + From + TryInto + TryInto + - ops::Div + ops::Rem + ops::Add + Unsigned; + where + N: Clone + Ord + TryInto + TryInto + + ops::Div + ops::Rem + ops::Add + Unsigned, + Self::Inner: Into; } /// The rounding method to use. @@ -221,15 +238,12 @@ enum Rounding { /// Saturating reciprocal multiplication. Compute `x / self`, saturating at the numeric /// bounds instead of overflowing. -fn saturating_reciprocal_mul( - x: N, - part: P::Inner, - rounding: Rounding, -) -> N +fn saturating_reciprocal_mul(x: N, part: P::Inner, rounding: Rounding) -> N where - N: Clone + From + UniqueSaturatedInto + ops::Div + ops::Mul + ops::Div + ops::Mul + ops::Add + ops::Rem + Saturating + Unsigned, P: PerThing, + P::Inner: Into, { let maximum: N = P::ACCURACY.into(); let c = rational_mul_correction::( @@ -242,15 +256,12 @@ where } /// Overflow-prune multiplication. Accurately multiply a value by `self` without overflowing. -fn overflow_prune_mul( - x: N, - part: P::Inner, - rounding: Rounding, -) -> N +fn overflow_prune_mul(x: N, part: P::Inner, rounding: Rounding) -> N where - N: Clone + From + UniqueSaturatedInto + ops::Div + ops::Mul + ops::Div + ops::Mul + ops::Add + ops::Rem + Unsigned, P: PerThing, + P::Inner: Into, { let maximum: N = P::ACCURACY.into(); let part_n: N = part.into(); @@ -267,19 +278,15 @@ where /// /// Take the remainder of `x / denom` and multiply by `numer / denom`. The result can be added /// to `x / denom * numer` for an accurate result. -fn rational_mul_correction( - x: N, - numer: P::Inner, - denom: P::Inner, - rounding: Rounding, -) -> N +fn rational_mul_correction(x: N, numer: P::Inner, denom: P::Inner, rounding: Rounding) -> N where - N: From + UniqueSaturatedInto + ops::Div + ops::Mul + ops::Div + ops::Mul + ops::Add + ops::Rem + Unsigned, P: PerThing, + P::Inner: Into { let numer_upper = P::Upper::from(numer); - let denom_n = N::from(denom); + let denom_n: N = denom.into(); let denom_upper = P::Upper::from(denom); let rem = x.rem(denom_n); // `rem` is less than `denom`, which fits in `P::Inner`. @@ -362,14 +369,17 @@ macro_rules! implement_per_thing { } fn from_rational_approximation(p: N, q: N) -> Self - where N: Clone + Ord + From + TryInto + TryInto - + ops::Div + ops::Rem + ops::Add + Unsigned + where + N: Clone + Ord + TryInto + TryInto + + ops::Div + ops::Rem + ops::Add + Unsigned + + Zero + One, + Self::Inner: Into, { let div_ceil = |x: N, f: N| -> N { let mut o = x.clone() / f.clone(); let r = x.rem(f.clone()); - if r > N::from(0) { - o = o + N::from(1); + if r > N::zero() { + o = o + N::one(); } o }; @@ -464,54 +474,66 @@ macro_rules! implement_per_thing { /// See [`PerThing::from_rational_approximation`]. pub fn from_rational_approximation(p: N, q: N) -> Self - where N: Clone + Ord + From<$type> + TryInto<$type> + + where N: Clone + Ord + TryInto<$type> + TryInto<$upper_type> + ops::Div + ops::Rem + - ops::Add + Unsigned + ops::Add + Unsigned, + $type: Into, { ::from_rational_approximation(p, q) } /// See [`PerThing::mul_floor`]. pub fn mul_floor(self, b: N) -> N - where N: Clone + From<$type> + UniqueSaturatedInto<$type> + - ops::Rem + ops::Div + ops::Mul + - ops::Add + Unsigned + where + N: Clone + UniqueSaturatedInto<$type> + + ops::Rem + ops::Div + ops::Mul + + ops::Add + Unsigned, + $type: Into, + { PerThing::mul_floor(self, b) } /// See [`PerThing::mul_ceil`]. pub fn mul_ceil(self, b: N) -> N - where N: Clone + From<$type> + UniqueSaturatedInto<$type> + - ops::Rem + ops::Div + ops::Mul + - ops::Add + Unsigned + where + N: Clone + UniqueSaturatedInto<$type> + + ops::Rem + ops::Div + ops::Mul + + ops::Add + Unsigned, + $type: Into, { PerThing::mul_ceil(self, b) } /// See [`PerThing::saturating_reciprocal_mul`]. pub fn saturating_reciprocal_mul(self, b: N) -> N - where N: Clone + From<$type> + UniqueSaturatedInto<$type> + ops::Rem + - ops::Div + ops::Mul + ops::Add + - Saturating + Unsigned + where + N: Clone + UniqueSaturatedInto<$type> + ops::Rem + + ops::Div + ops::Mul + ops::Add + + Saturating + Unsigned, + $type: Into, { PerThing::saturating_reciprocal_mul(self, b) } /// See [`PerThing::saturating_reciprocal_mul_floor`]. pub fn saturating_reciprocal_mul_floor(self, b: N) -> N - where N: Clone + From<$type> + UniqueSaturatedInto<$type> + ops::Rem + - ops::Div + ops::Mul + ops::Add + - Saturating + Unsigned + where + N: Clone + UniqueSaturatedInto<$type> + ops::Rem + + ops::Div + ops::Mul + ops::Add + + Saturating + Unsigned, + $type: Into, { PerThing::saturating_reciprocal_mul_floor(self, b) } /// See [`PerThing::saturating_reciprocal_mul_ceil`]. pub fn saturating_reciprocal_mul_ceil(self, b: N) -> N - where N: Clone + From<$type> + UniqueSaturatedInto<$type> + ops::Rem + - ops::Div + ops::Mul + ops::Add + - Saturating + Unsigned + where + N: Clone + UniqueSaturatedInto<$type> + ops::Rem + + ops::Div + ops::Mul + ops::Add + + Saturating + Unsigned, + $type: Into, { PerThing::saturating_reciprocal_mul_ceil(self, b) } @@ -611,8 +633,9 @@ macro_rules! implement_per_thing { /// This is tailored to be used with a balance type. impl ops::Mul for $name where - N: Clone + From<$type> + UniqueSaturatedInto<$type> + ops::Rem + N: Clone + UniqueSaturatedInto<$type> + ops::Rem + ops::Div + ops::Mul + ops::Add + Unsigned, + $type: Into, { type Output = N; fn mul(self, b: N) -> Self::Output { diff --git a/primitives/election-providers/src/onchain.rs b/primitives/election-providers/src/onchain.rs index 496ba7fda47e9..b50dff2ff17d9 100644 --- a/primitives/election-providers/src/onchain.rs +++ b/primitives/election-providers/src/onchain.rs @@ -17,7 +17,6 @@ //! An implementation of [`ElectionProvider`] that does an on-chain sequential phragmen. -use sp_arithmetic::InnerOf; use crate::{ElectionDataProvider, ElectionProvider}; use sp_npos_elections::*; use sp_std::{collections::btree_map::BTreeMap, marker::PhantomData, prelude::*}; @@ -58,10 +57,7 @@ pub trait Config { type DataProvider: ElectionDataProvider; } -impl ElectionProvider for OnChainSequentialPhragmen -where - ExtendedBalance: From>, -{ +impl ElectionProvider for OnChainSequentialPhragmen { type Error = Error; type DataProvider = T::DataProvider; diff --git a/primitives/npos-elections/benches/phragmen.rs b/primitives/npos-elections/benches/phragmen.rs index 07d07658a46a1..d48c246558844 100644 --- a/primitives/npos-elections/benches/phragmen.rs +++ b/primitives/npos-elections/benches/phragmen.rs @@ -65,7 +65,6 @@ mod bench_closure_and_slice { ) -> Vec> where T: sp_std::ops::Mul, - ExtendedBalance: From<::Inner>, { ratio .into_iter() diff --git a/primitives/npos-elections/src/helpers.rs b/primitives/npos-elections/src/helpers.rs index 4a2099947ea10..10a49a084f102 100644 --- a/primitives/npos-elections/src/helpers.rs +++ b/primitives/npos-elections/src/helpers.rs @@ -17,11 +17,8 @@ //! Helper methods for npos-elections. -use crate::{ - Assignment, Error, ExtendedBalance, IdentifierT, PerThing128, StakedAssignment, VoteWeight, - WithApprovalOf, -}; -use sp_arithmetic::{InnerOf, PerThing}; +use crate::{Assignment, Error, IdentifierT, PerThing128, StakedAssignment, VoteWeight, WithApprovalOf}; +use sp_arithmetic::PerThing; use sp_std::prelude::*; /// Converts a vector of ratio assignments into ones with absolute budget value. @@ -33,7 +30,6 @@ pub fn assignment_ratio_to_staked( ) -> Vec> where for<'r> FS: Fn(&'r A) -> VoteWeight, - ExtendedBalance: From>, { ratios .into_iter() @@ -51,7 +47,6 @@ pub fn assignment_ratio_to_staked_normalized ) -> Result>, Error> where for<'r> FS: Fn(&'r A) -> VoteWeight, - ExtendedBalance: From>, { let mut staked = assignment_ratio_to_staked(ratio, &stake_of); staked @@ -68,24 +63,19 @@ where /// Note that this will NOT attempt at normalizing the result. pub fn assignment_staked_to_ratio( staked: Vec>, -) -> Vec> -where - ExtendedBalance: From>, -{ +) -> Vec> { staked.into_iter().map(|a| a.into_assignment()).collect() } /// Same as [`assignment_staked_to_ratio`] and try and do normalization. pub fn assignment_staked_to_ratio_normalized( staked: Vec>, -) -> Result>, Error> -where - ExtendedBalance: From>, -{ +) -> Result>, Error> { let mut ratio = staked.into_iter().map(|a| a.into_assignment()).collect::>(); - ratio.iter_mut().map(|a| - a.try_normalize().map_err(|err| Error::ArithmeticError(err)) - ).collect::>()?; + ratio + .iter_mut() + .map(|a| a.try_normalize().map_err(|err| Error::ArithmeticError(err))) + .collect::>()?; Ok(ratio) } diff --git a/primitives/npos-elections/src/lib.rs b/primitives/npos-elections/src/lib.rs index 2f6e133f1dc79..d45698e1747bb 100644 --- a/primitives/npos-elections/src/lib.rs +++ b/primitives/npos-elections/src/lib.rs @@ -75,7 +75,7 @@ use sp_arithmetic::{ traits::{Bounded, UniqueSaturatedInto, Zero}, - InnerOf, Normalizable, PerThing, Rational128, ThresholdOrd, + Normalizable, PerThing, Rational128, ThresholdOrd, }; use sp_std::{ cell::RefCell, @@ -209,7 +209,6 @@ pub trait CompactSolution: Sized { where for<'r> FS: Fn(&'r A) -> VoteWeight, A: IdentifierT, - ExtendedBalance: From>, { let ratio = self.into_assignment(voter_at, target_at)?; let staked = helpers::assignment_ratio_to_staked_normalized(ratio, stake_of)?; @@ -332,14 +331,14 @@ impl Voter { /// Note that this might create _un-normalized_ assignments, due to accuracy loss of `P`. Call /// site might compensate by calling `normalize()` on the returned `Assignment` as a /// post-precessing. - pub fn into_assignment(self) -> Option> - where - ExtendedBalance: From>, - { + pub fn into_assignment(self) -> Option> { let who = self.who; let budget = self.budget; - let distribution = self.edges.into_iter().filter_map(|e| { - let per_thing = P::from_rational_approximation(e.weight, budget); + let distribution = self + .edges + .into_iter() + .filter_map(|e| { + let per_thing = P::from_rational_approximation(e.weight, budget); // trim zero edges. if per_thing.is_zero() { None } else { Some((e.who, per_thing)) } }).collect::>(); @@ -507,7 +506,6 @@ impl StakedAssignment { /// can never be re-created and does not mean anything useful anymore. pub fn into_assignment(self) -> Assignment where - ExtendedBalance: From>, AccountId: IdentifierT, { let stake = self.total(); @@ -706,10 +704,7 @@ where /// greater or less than `that`. /// /// Note that the third component should be minimized. -pub fn is_score_better(this: ElectionScore, that: ElectionScore, epsilon: P) -> bool -where - ExtendedBalance: From>, -{ +pub fn is_score_better(this: ElectionScore, that: ElectionScore, epsilon: P) -> bool { match this .iter() .zip(that.iter()) diff --git a/primitives/npos-elections/src/mock.rs b/primitives/npos-elections/src/mock.rs index 57b2204a72b48..ea8f3780e0e6a 100644 --- a/primitives/npos-elections/src/mock.rs +++ b/primitives/npos-elections/src/mock.rs @@ -22,7 +22,7 @@ use crate::*; use sp_arithmetic::{ traits::{One, SaturatedConversion, Zero}, - InnerOf, PerThing, + PerThing, }; use sp_runtime::assert_eq_error_rate; use sp_std::collections::btree_map::BTreeMap; @@ -321,9 +321,7 @@ pub(crate) fn run_and_compare( voters: Vec<(AccountId, Vec)>, stake_of: &Box VoteWeight>, to_elect: usize, -) where - ExtendedBalance: From>, -{ +) { // run fixed point code. let ElectionResult { winners, assignments } = seq_phragmen::<_, Output>( to_elect, diff --git a/primitives/npos-elections/src/phragmen.rs b/primitives/npos-elections/src/phragmen.rs index 24a6b81af31a7..dad65666738c7 100644 --- a/primitives/npos-elections/src/phragmen.rs +++ b/primitives/npos-elections/src/phragmen.rs @@ -27,7 +27,7 @@ use crate::{ use sp_arithmetic::{ helpers_128bit::multiply_by_rational, traits::{Bounded, Zero}, - InnerOf, Rational128, + Rational128, }; use sp_std::prelude::*; @@ -68,10 +68,7 @@ pub fn seq_phragmen( initial_candidates: Vec, initial_voters: Vec<(AccountId, VoteWeight, Vec)>, balance: Option<(usize, ExtendedBalance)>, -) -> Result, crate::Error> -where - ExtendedBalance: From>, -{ +) -> Result, crate::Error> { let (candidates, voters) = setup_inputs(initial_candidates, initial_voters); let (candidates, mut voters) = seq_phragmen_core::( diff --git a/primitives/npos-elections/src/phragmms.rs b/primitives/npos-elections/src/phragmms.rs index b37d3432f9d7e..ad93d2f18ef9a 100644 --- a/primitives/npos-elections/src/phragmms.rs +++ b/primitives/npos-elections/src/phragmms.rs @@ -25,7 +25,7 @@ use crate::{ IdentifierT, ElectionResult, ExtendedBalance, setup_inputs, VoteWeight, Voter, CandidatePtr, balance, PerThing128, }; -use sp_arithmetic::{PerThing, InnerOf, Rational128, traits::Bounded}; +use sp_arithmetic::{PerThing, Rational128, traits::Bounded}; use sp_std::{prelude::*, rc::Rc}; /// Execute the phragmms method. @@ -46,10 +46,7 @@ pub fn phragmms( initial_candidates: Vec, initial_voters: Vec<(AccountId, VoteWeight, Vec)>, balancing_config: Option<(usize, ExtendedBalance)>, -) -> Result, &'static str> -where - ExtendedBalance: From>, -{ +) -> Result, &'static str> { let (candidates, mut voters) = setup_inputs(initial_candidates, initial_voters); let mut winners = vec![]; @@ -89,7 +86,7 @@ where pub(crate) fn calculate_max_score( candidates: &[CandidatePtr], voters: &[Voter], -) -> Option> where ExtendedBalance: From> { +) -> Option> { for c_ptr in candidates.iter() { let mut candidate = c_ptr.borrow_mut(); if !candidate.elected {