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

Commit

Permalink
Refactor CurrencyToVote (#6896)
Browse files Browse the repository at this point in the history
* Refactor CurrencyToVote to avoid calls to total_issuance.

* Update frame/support/src/traits.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Some grumbles

* Fix last grumbles.

* Fix comment

* Final fix

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>
  • Loading branch information
kianenigma and gui1117 authored Oct 8, 2020
1 parent 46e170a commit 90e8abf
Show file tree
Hide file tree
Showing 14 changed files with 157 additions and 199 deletions.
21 changes: 1 addition & 20 deletions bin/node/runtime/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@

//! Some configurable implementations as associated type for the substrate runtime.

use node_primitives::Balance;
use sp_runtime::traits::Convert;
use frame_support::traits::{OnUnbalanced, Currency};
use crate::{Balances, Authorship, NegativeImbalance};

Expand All @@ -29,26 +27,9 @@ 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::*;
use sp_runtime::{assert_eq_error_rate, FixedPointNumber};
use sp_runtime::{assert_eq_error_rate, FixedPointNumber, traits::Convert};
use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment};

use crate::{
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 @@ -448,7 +451,7 @@ parameter_types! {
impl pallet_staking::Trait for Runtime {
type Currency = Balances;
type UnixTime = Timestamp;
type CurrencyToVote = CurrencyToVoteHandler;
type CurrencyToVote = U128CurrencyToVote;
type RewardRemainder = Treasury;
type Event = Event;
type Slash = Treasury; // send the slashed funds to the treasury.
Expand Down Expand Up @@ -574,7 +577,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 @@ -183,23 +183,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
57 changes: 22 additions & 35 deletions frame/elections-phragmen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,25 +83,26 @@

#![cfg_attr(not(feature = "std"), no_std)]

use codec::{Encode, Decode};
use sp_std::prelude::*;
use sp_runtime::{
DispatchError, RuntimeDebug, Perbill,
traits::{Zero, StaticLookup, Convert, Saturating},
};
use codec::{Decode, Encode};
use frame_support::{
decl_storage, decl_event, ensure, decl_module, decl_error,
weights::Weight,
storage::{StorageMap, IterableStorageMap},
decl_error, decl_event, decl_module, decl_storage,
dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo},
ensure,
storage::{IterableStorageMap, StorageMap},
traits::{
Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons,
ChangeMembers, OnUnbalanced, WithdrawReason, Contains, InitializeMembers, BalanceStatus,
ContainsLengthBound,
}
BalanceStatus, ChangeMembers, Contains, ContainsLengthBound, Currency, CurrencyToVote, Get,
InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency,
WithdrawReason, WithdrawReasons,
},
weights::Weight,
};
use sp_npos_elections::{ExtendedBalance, VoteWeight, ElectionResult};
use frame_system::{ensure_signed, ensure_root};
use frame_system::{ensure_root, ensure_signed};
use sp_npos_elections::{ElectionResult, ExtendedBalance};
use sp_runtime::{
traits::{Saturating, StaticLookup, Zero},
DispatchError, Perbill, RuntimeDebug,
};
use sp_std::prelude::*;

mod benchmarking;
mod default_weights;
Expand Down Expand Up @@ -172,7 +173,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 @@ -871,16 +872,13 @@ impl<T: Trait> Module<T> {
}

// 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 to_votes = |b: BalanceOf<T>| T::CurrencyToVote::to_vote(b, total_issuance);
let to_balance = |e: ExtendedBalance| T::CurrencyToVote::to_currency(e, total_issuance);

// used for prime election.
let voters_and_stakes = Voting::<T>::iter()
.map(|(voter, (stake, votes))| { (voter, stake, votes) })
.map(|(voter, (stake, votes))| (voter, stake, votes))
.collect::<Vec<_>>();
// used for phragmen.
let voters_and_votes = voters_and_stakes.iter()
Expand Down Expand Up @@ -1186,17 +1184,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 @@ -1205,7 +1192,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 @@ -198,23 +198,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 = 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 @@ -150,22 +149,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 @@ -172,7 +160,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 @@ -177,7 +164,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

0 comments on commit 90e8abf

Please sign in to comment.