Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Refactor CurrencyToVote #6896

Merged
13 commits merged into from
Oct 8, 2020
16 changes: 0 additions & 16 deletions bin/node/runtime/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,6 @@ impl OnUnbalanced<NegativeImbalance> for Author {
}
}

/// Struct that handles the conversion of Balance -> `u64`. This is used for staking's election
/// calculation.
pub struct CurrencyToVoteHandler;

impl CurrencyToVoteHandler {
fn factor() -> Balance { (Balances::total_issuance() / u64::max_value() as Balance).max(1) }
}

impl Convert<Balance, u64> for CurrencyToVoteHandler {
fn convert(x: Balance) -> u64 { (x / Self::factor()) as u64 }
}

impl Convert<u128, Balance> for CurrencyToVoteHandler {
fn convert(x: u128) -> Balance { x * Self::factor() }
}

#[cfg(test)]
mod multiplier_tests {
use super::*;
Expand Down
11 changes: 7 additions & 4 deletions bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ use frame_support::{
Weight, IdentityFee,
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
},
traits::{Currency, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness, LockIdentifier},
traits::{
Currency, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness, LockIdentifier,
U128CurrencyToVote,
},
};
use frame_system::{EnsureRoot, EnsureOneOf};
use frame_support::traits::InstanceFilter;
Expand Down Expand Up @@ -78,7 +81,7 @@ pub use pallet_staking::StakerStatus;

/// Implementations of some helper traits passed into runtime modules as associated types.
pub mod impls;
use impls::{CurrencyToVoteHandler, Author};
use impls::Author;

/// Constant values used within the runtime.
pub mod constants;
Expand Down Expand Up @@ -423,7 +426,7 @@ parameter_types! {
impl pallet_staking::Trait for Runtime {
type Currency = Balances;
type UnixTime = Timestamp;
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
type RewardRemainder = Treasury;
type Event = Event;
type Slash = Treasury; // send the slashed funds to the treasury.
Expand Down Expand Up @@ -533,7 +536,7 @@ impl pallet_elections_phragmen::Trait for Runtime {
// NOTE: this implies that council's genesis members cannot be set directly and must come from
// this module.
type InitializeMembers = Council;
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = U128CurrencyToVote;
type CandidacyBond = CandidacyBond;
type VotingBond = VotingBond;
type LoserCandidate = ();
Expand Down
18 changes: 2 additions & 16 deletions frame/babe/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use sp_runtime::{
Perbill, impl_opaque_keys,
curve::PiecewiseLinear,
testing::{Digest, DigestItem, Header, TestXt,},
traits::{Convert, Header as _, IdentityLookup, OpaqueKeys, SaturatedConversion},
traits::{Header as _, IdentityLookup, OpaqueKeys},
};
use frame_system::InitKind;
use frame_support::{
Expand Down Expand Up @@ -182,23 +182,9 @@ parameter_types! {
pub const StakingUnsignedPriority: u64 = u64::max_value() / 2;
}

pub struct CurrencyToVoteHandler;

impl Convert<u128, u128> for CurrencyToVoteHandler {
fn convert(x: u128) -> u128 {
x
}
}

impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 {
x.saturated_into()
}
}

impl pallet_staking::Trait for Test {
type RewardRemainder = ();
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type Event = ();
type Currency = Balances;
type Slash = ();
Expand Down
37 changes: 12 additions & 25 deletions frame/elections-phragmen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ use codec::{Encode, Decode};
use sp_std::prelude::*;
use sp_runtime::{
DispatchError, RuntimeDebug, Perbill,
traits::{Zero, StaticLookup, Convert},
traits::{Zero, StaticLookup},
};
use frame_support::{
decl_storage, decl_event, ensure, decl_module, decl_error,
Expand All @@ -97,10 +97,10 @@ use frame_support::{
traits::{
Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons,
ChangeMembers, OnUnbalanced, WithdrawReason, Contains, BalanceStatus, InitializeMembers,
ContainsLengthBound,
ContainsLengthBound, CurrencyToVote,
}
};
use sp_npos_elections::{build_support_map, ExtendedBalance, VoteWeight, ElectionResult};
use sp_npos_elections::{build_support_map, VoteWeight, ElectionResult};
use frame_system::{ensure_signed, ensure_root};

mod benchmarking;
Expand Down Expand Up @@ -189,7 +189,7 @@ pub trait Trait: frame_system::Trait {

/// Convert a balance into a number used for election calculation.
/// This must fit into a `u64` but is allowed to be sensibly lossy.
type CurrencyToVote: Convert<BalanceOf<Self>, VoteWeight> + Convert<ExtendedBalance, BalanceOf<Self>>;
type CurrencyToVote: CurrencyToVote<BalanceOf<Self>>;

/// How much should be locked up in order to submit one's candidacy.
type CandidacyBond: Get<BalanceOf<Self>>;
Expand Down Expand Up @@ -893,19 +893,17 @@ impl<T: Trait> Module<T> {
// previous runners_up are also always candidates for the next round.
candidates.append(&mut Self::runners_up_ids());


// helper closures to deal with balance/stake.
let to_votes = |b: BalanceOf<T>| -> VoteWeight {
<T::CurrencyToVote as Convert<BalanceOf<T>, VoteWeight>>::convert(b)
};
let to_balance = |e: ExtendedBalance| -> BalanceOf<T> {
<T::CurrencyToVote as Convert<ExtendedBalance, BalanceOf<T>>>::convert(e)
};
let total_issuance = T::Currency::total_issuance();
let stake_of = |who: &T::AccountId| -> VoteWeight {
to_votes(Self::locked_stake_of(who))
<T::CurrencyToVote>::to_vote(Self::locked_stake_of(who), total_issuance)
};

let voters_and_votes = Voting::<T>::iter()
.map(|(voter, (stake, targets))| { (voter, to_votes(stake), targets) })
.map(|(voter, (stake, targets))|
(voter, <T::CurrencyToVote>::to_vote(stake, total_issuance), targets)
)
.collect::<Vec<_>>();
let maybe_phragmen_result = sp_npos_elections::seq_phragmen::<T::AccountId, Perbill>(
num_to_elect,
Expand Down Expand Up @@ -953,7 +951,7 @@ impl<T: Trait> Module<T> {
"entire new_set was given to build_support_map; en entry must be \
created for each item; qed"
);
(m.clone(), to_balance(support.total))
(m.clone(), <T::CurrencyToVote>::to_currency(support.total, total_issuance))
})
.collect::<Vec<(T::AccountId, BalanceOf<T>)>>();

Expand Down Expand Up @@ -1220,17 +1218,6 @@ mod tests {
}
}

/// Simple structure that exposes how u64 currency can be represented as... u64.
pub struct CurrencyToVoteHandler;
impl Convert<u64, u64> for CurrencyToVoteHandler {
fn convert(x: u64) -> u64 { x }
}
impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 {
x as u64
}
}

parameter_types!{
pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect";
}
Expand All @@ -1239,7 +1226,7 @@ mod tests {
type ModuleId = ElectionsPhragmenModuleId;
type Event = Event;
type Currency = Balances;
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type ChangeMembers = TestChangeMembers;
type InitializeMembers = ();
type CandidacyBond = CandidacyBond;
Expand Down
18 changes: 2 additions & 16 deletions frame/grandpa/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use sp_runtime::{
curve::PiecewiseLinear,
impl_opaque_keys,
testing::{Header, TestXt, UintAuthorityId},
traits::{Convert, IdentityLookup, OpaqueKeys, SaturatedConversion},
traits::{IdentityLookup, OpaqueKeys},
DigestItem, Perbill,
};
use sp_staking::SessionIndex;
Expand Down Expand Up @@ -204,23 +204,9 @@ parameter_types! {
pub const StakingUnsignedPriority: u64 = u64::max_value() / 2;
}

pub struct CurrencyToVoteHandler;

impl Convert<u128, u128> for CurrencyToVoteHandler {
fn convert(x: u128) -> u128 {
x
}
}

impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 {
x.saturated_into()
}
}

impl staking::Trait for Test {
type RewardRemainder = ();
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type Event = TestEvent;
type Currency = Balances;
type Slash = ();
Expand Down
15 changes: 1 addition & 14 deletions frame/offences/benchmarking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ use frame_support::{
};
use frame_system as system;
use sp_runtime::{
SaturatedConversion,
traits::{IdentityLookup, Block as BlockT},
testing::{Header, UintAuthorityId},
};
Expand Down Expand Up @@ -149,22 +148,10 @@ parameter_types! {

pub type Extrinsic = sp_runtime::testing::TestXt<Call, ()>;

pub struct CurrencyToVoteHandler;
impl Convert<u64, u64> for CurrencyToVoteHandler {
fn convert(x: u64) -> u64 {
x
}
}
impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 {
x.saturated_into()
}
}

impl pallet_staking::Trait for Test {
type Currency = Balances;
type UnixTime = pallet_timestamp::Module<Self>;
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type RewardRemainder = ();
type Event = Event;
type Slash = ();
Expand Down
16 changes: 2 additions & 14 deletions frame/session/benchmarking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

#![cfg(test)]

use sp_runtime::traits::{Convert, SaturatedConversion, IdentityLookup};
use sp_runtime::traits::IdentityLookup;
use frame_support::{impl_outer_origin, impl_outer_dispatch, parameter_types};

type AccountId = u64;
Expand All @@ -42,18 +42,6 @@ impl_outer_dispatch! {
}
}

pub struct CurrencyToVoteHandler;
impl Convert<u64, u64> for CurrencyToVoteHandler {
fn convert(x: u64) -> u64 {
x
}
}
impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 {
x.saturated_into()
}
}

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Test;

Expand Down Expand Up @@ -171,7 +159,7 @@ impl<C> frame_system::offchain::SendTransactionTypes<C> for Test where
impl pallet_staking::Trait for Test {
type Currency = Balances;
type UnixTime = pallet_timestamp::Module<Self>;
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type RewardRemainder = ();
type Event = ();
type Slash = ();
Expand Down
15 changes: 1 addition & 14 deletions frame/staking/fuzzer/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

//! Mock file for staking fuzzing.

use sp_runtime::traits::{Convert, SaturatedConversion};
use frame_support::{impl_outer_origin, impl_outer_dispatch, parameter_types};

type AccountId = u64;
Expand All @@ -41,18 +40,6 @@ impl_outer_dispatch! {
}
}

pub struct CurrencyToVoteHandler;
impl Convert<u64, u64> for CurrencyToVoteHandler {
fn convert(x: u64) -> u64 {
x
}
}
impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 {
x.saturated_into()
}
}

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Test;

Expand Down Expand Up @@ -176,7 +163,7 @@ impl<C> frame_system::offchain::SendTransactionTypes<C> for Test where
impl pallet_staking::Trait for Test {
type Currency = Balances;
type UnixTime = pallet_timestamp::Module<Self>;
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type RewardRemainder = ();
type Event = ();
type Slash = ();
Expand Down
Loading