Transaction Fee Multiplier (#2854)

* added fee calculations; need some type conversions

* cleaned up make_payment and other stuff

* rename vars to compile

* add WeightToFee type

* clean test files after new type added to balances

* fmting

* fix balance configs in tests

* more fixing mocks and tests

* more comprehensive block weight limit test

* fix compilation errors

* more srml/executive tests && started fixing node/executor tests

* new fee multiplier; still overflows :(

* perbill at the end attempt; needs to be changed

* clean fmting, rename some vars

* new PoC implementation.

* test weight_to_fee range and verify functionality

* 12 of 15 tests in node executor are passing

* 1 test failing; big_block imports are failing for wrong reasons

* Update srml/executive/src/lib.rs

Co-Authored-By: Kian Peymani <Kianenigma@users.noreply.github.com>

* Some cleanup.

* consolidate tests in runtime impls

* clean and condition executive for stateful fee range test

* remove comments to self

* Major cleanup.

* More cleanup.

* Fix lock files.

* Fix build.

* Update node-template/runtime/Cargo.toml

Co-Authored-By: Gavin Wood <github@gavwood.com>

* Update node/executor/src/lib.rs

Co-Authored-By: Gavin Wood <github@gavwood.com>

* Update node/executor/src/lib.rs

Co-Authored-By: Gavin Wood <github@gavwood.com>

* Update node/executor/src/lib.rs

Co-Authored-By: Gavin Wood <github@gavwood.com>

* Update node/executor/src/lib.rs

Co-Authored-By: Gavin Wood <github@gavwood.com>

* Update node/executor/src/lib.rs

Co-Authored-By: Gavin Wood <github@gavwood.com>

* Update node/executor/src/lib.rs

Co-Authored-By: Gavin Wood <github@gavwood.com>

* Per-block update.

* nit.

* Update docs.

* Fix contracts test.

* Stateful fee update.

* Update lock files.

* Update node/runtime/src/impls.rs

* Revamped again with fixed64.

* fix cargo file.

* nits.

* Some cleanup.

* Some nits.

* Fix build.

* Bump.

* Rename to WeightMultiplier

* Update node/executor/src/lib.rs

Co-Authored-By: Tomasz Drwięga <tomusdrw@users.noreply.github.com>

* Add weight to election module mock.

* Fix build.

* finalize merge

* Update srml/system/src/lib.rs

* Bring back fees.

* Some nits.

* Code shifting for simplicity.

* Fix build + more tests.

* Update weights.rs

* Update core/sr-primitives/src/weights.rs

* Update lib.rs

* Fix test build
This commit is contained in:
Amar Singh
2019-07-19 14:21:05 +02:00
committed by Kian Peymani
parent a313935947
commit a757dfb222
36 changed files with 1103 additions and 411 deletions
+183 -31
View File
@@ -49,6 +49,7 @@ mod tests {
use node_primitives::{Hash, BlockNumber, AccountId};
use runtime_primitives::traits::{Header as HeaderT, Hash as HashT};
use runtime_primitives::{generic::Era, ApplyOutcome, ApplyError, ApplyResult, Perbill};
use runtime_primitives::weights::{IDEAL_TRANSACTIONS_WEIGHT, WeightMultiplier};
use {balances, contracts, indices, staking, system, timestamp};
use contracts::ContractAddressFor;
use system::{EventRecord, Phase};
@@ -77,8 +78,10 @@ mod tests {
const BLOATY_CODE: &[u8] = node_runtime::WASM_BINARY_BLOATY;
const GENESIS_HASH: [u8; 32] = [69u8; 32];
const TX_FEE: u128 = 3 * CENTS + 460 * MILLICENTS;
// from weight
const TX_FEE: u128 = 146;
// regardless of creation of transfer
const TRANSFER_FEE: u128 = 1 * CENTS;
type TestExternalities<H> = CoreTestExternalities<H, u64>;
@@ -150,13 +153,13 @@ mod tests {
fn panic_execution_with_foreign_code_gives_error() {
let mut t = TestExternalities::<Blake2Hasher>::new_with_code(BLOATY_CODE, map![
blake2_256(&<balances::FreeBalance<Runtime>>::key_for(alice())).to_vec() => {
vec![0u8; 16]
69_u128.encode()
},
twox_128(<balances::TotalIssuance<Runtime>>::key()).to_vec() => {
vec![0u8; 16]
69_u128.encode()
},
twox_128(<indices::NextEnumSet<Runtime>>::key()).to_vec() => {
vec![0u8; 16]
0_u128.encode()
},
blake2_256(&<system::BlockHash<Runtime>>::key_for(0)).to_vec() => {
vec![0u8; 32]
@@ -186,13 +189,13 @@ mod tests {
fn bad_extrinsic_with_native_equivalent_code_gives_error() {
let mut t = TestExternalities::<Blake2Hasher>::new_with_code(COMPACT_CODE, map![
blake2_256(&<balances::FreeBalance<Runtime>>::key_for(alice())).to_vec() => {
vec![0u8; 16]
69_u128.encode()
},
twox_128(<balances::TotalIssuance<Runtime>>::key()).to_vec() => {
vec![0u8; 16]
69_u128.encode()
},
twox_128(<indices::NextEnumSet<Runtime>>::key()).to_vec() => {
vec![0u8; 16]
0_u128.encode()
},
blake2_256(&<system::BlockHash<Runtime>>::key_for(0)).to_vec() => {
vec![0u8; 32]
@@ -249,7 +252,7 @@ mod tests {
assert!(r.is_ok());
runtime_io::with_externalities(&mut t, || {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - 1 * TX_FEE);
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - TX_FEE - TRANSFER_FEE);
assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS);
});
}
@@ -285,7 +288,7 @@ mod tests {
assert!(r.is_ok());
runtime_io::with_externalities(&mut t, || {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - 1 * TX_FEE);
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - TX_FEE - TRANSFER_FEE);
assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS);
});
}
@@ -479,12 +482,11 @@ mod tests {
// session change => consensus authorities change => authorities change digest item appears
let digest = Header::decode(&mut &block2.0[..]).unwrap().digest;
assert_eq!(digest.logs().len(), 0);
// assert!(digest.logs()[0].as_consensus().is_some());
(block1, block2)
}
fn big_block() -> (Vec<u8>, Hash) {
fn block_with_size(time: u64, nonce: u64, size: usize) -> (Vec<u8>, Hash) {
construct_block(
&mut new_test_ext(COMPACT_CODE, false),
1,
@@ -492,11 +494,11 @@ mod tests {
vec![
CheckedExtrinsic {
signed: None,
function: Call::Timestamp(timestamp::Call::set(42)),
function: Call::Timestamp(timestamp::Call::set(time)),
},
CheckedExtrinsic {
signed: Some((alice(), 0)),
function: Call::System(system::Call::remark(vec![0; 120000])),
signed: Some((charlie(), nonce)),
function: Call::System(system::Call::remark(vec![0; size])),
}
]
)
@@ -519,7 +521,7 @@ mod tests {
runtime_io::with_externalities(&mut t, || {
// block1 transfers from alice 69 to bob.
// -1 is the default fee
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - 1 * TX_FEE);
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - TX_FEE - TRANSFER_FEE);
assert_eq!(Balances::total_balance(&bob()), 169 * DOLLARS);
let events = vec![
EventRecord {
@@ -545,7 +547,6 @@ mod tests {
];
assert_eq!(System::events(), events);
});
executor().call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
@@ -557,9 +558,9 @@ mod tests {
runtime_io::with_externalities(&mut t, || {
// bob sends 5, alice sends 15 | bob += 10, alice -= 10
// 111 - 69 - 10 = 32
assert_eq!(Balances::total_balance(&alice()), 32 * DOLLARS - 2 * TX_FEE);
assert_eq!(Balances::total_balance(&alice()), 32 * DOLLARS - 2 * (TX_FEE + TRANSFER_FEE));
// 100 + 69 + 10 = 179
assert_eq!(Balances::total_balance(&bob()), 179 * DOLLARS - 1 * TX_FEE);
assert_eq!(Balances::total_balance(&bob()), 179 * DOLLARS - TX_FEE - TRANSFER_FEE);
let events = vec![
EventRecord {
phase: Phase::ApplyExtrinsic(0),
@@ -615,7 +616,7 @@ mod tests {
runtime_io::with_externalities(&mut t, || {
// block1 transfers from alice 69 to bob.
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - 1 * TX_FEE);
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - (TX_FEE + TRANSFER_FEE));
assert_eq!(Balances::total_balance(&bob()), 169 * DOLLARS);
});
@@ -624,9 +625,9 @@ mod tests {
runtime_io::with_externalities(&mut t, || {
// bob sends 5, alice sends 15 | bob += 10, alice -= 10
// 111 - 69 - 10 = 32
assert_eq!(Balances::total_balance(&alice()), 32 * DOLLARS - 2 * TX_FEE);
assert_eq!(Balances::total_balance(&alice()), 32 * DOLLARS - 2 * (TX_FEE + TRANSFER_FEE));
// 100 + 69 + 10 = 179
assert_eq!(Balances::total_balance(&bob()), 179 * DOLLARS - 1 * TX_FEE);
assert_eq!(Balances::total_balance(&bob()), 179 * DOLLARS - (TX_FEE + TRANSFER_FEE));
});
}
@@ -724,7 +725,6 @@ mod tests {
#[test]
fn deploying_wasm_contract_should_work() {
let transfer_code = wabt::wat2wasm(CODE_TRANSFER).unwrap();
let transfer_ch = <Runtime as system::Trait>::Hashing::hash(&transfer_code);
@@ -795,7 +795,7 @@ mod tests {
4,
COMPACT_CODE,
"Core_execute_block",
&big_block().0
&block_with_size(42, 0, 120_000).0
).is_err()
);
}
@@ -807,7 +807,7 @@ mod tests {
Executor::new(None).call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
&big_block().0,
&block_with_size(42, 0, 120_000).0,
true,
None,
).0.unwrap();
@@ -821,7 +821,7 @@ mod tests {
Executor::new(None).call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
&big_block().0,
&block_with_size(42, 0, 120_000).0,
false,
None,
).0.is_err()
@@ -832,10 +832,10 @@ mod tests {
fn panic_execution_gives_error() {
let mut t = TestExternalities::<Blake2Hasher>::new_with_code(BLOATY_CODE, map![
blake2_256(&<balances::FreeBalance<Runtime>>::key_for(alice())).to_vec() => {
vec![0u8; 16]
0_u128.encode()
},
twox_128(<balances::TotalIssuance<Runtime>>::key()).to_vec() => {
vec![0u8; 16]
0_u128.encode()
},
twox_128(<indices::NextEnumSet<Runtime>>::key()).to_vec() => vec![0u8; 16],
blake2_256(&<system::BlockHash<Runtime>>::key_for(0)).to_vec() => vec![0u8; 32]
@@ -872,7 +872,7 @@ mod tests {
assert_eq!(r, Ok(ApplyOutcome::Success));
runtime_io::with_externalities(&mut t, || {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - 1 * TX_FEE);
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - TX_FEE - TRANSFER_FEE);
assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS);
});
}
@@ -900,8 +900,7 @@ mod tests {
let block1 = changes_trie_block();
let mut t = new_test_ext(COMPACT_CODE, true);
WasmExecutor::new()
.call(&mut t, 8, COMPACT_CODE, "Core_execute_block", &block1.0).unwrap();
WasmExecutor::new().call(&mut t, 8, COMPACT_CODE, "Core_execute_block", &block1.0).unwrap();
assert!(t.storage_changes_root(GENESIS_HASH.into()).unwrap().is_some());
}
@@ -921,6 +920,159 @@ mod tests {
client.import(BlockOrigin::Own, block).unwrap();
}
#[test]
fn weight_multiplier_increases_on_big_block() {
let mut t = new_test_ext(COMPACT_CODE, false);
let mut prev_multiplier = WeightMultiplier::default();
runtime_io::with_externalities(&mut t, || {
assert_eq!(System::next_weight_multiplier(), prev_multiplier);
});
let mut tt = new_test_ext(COMPACT_CODE, false);
let block1 = construct_block(
&mut tt,
1,
GENESIS_HASH.into(),
vec![
CheckedExtrinsic {
signed: None,
function: Call::Timestamp(timestamp::Call::set(42)),
},
CheckedExtrinsic {
signed: Some((charlie(), 0)),
function: Call::System(system::Call::remark(vec![0; (IDEAL_TRANSACTIONS_WEIGHT*2) as usize])),
}
]
);
let block2 = construct_block(
&mut tt,
2,
block1.1.clone(),
vec![
CheckedExtrinsic {
signed: None,
function: Call::Timestamp(timestamp::Call::set(52)),
},
CheckedExtrinsic {
signed: Some((charlie(), 1)),
function: Call::System(system::Call::remark(vec![0; (IDEAL_TRANSACTIONS_WEIGHT*2) as usize])),
}
]
);
// execute a big block.
executor().call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
&block1.0,
true,
None,
).0.unwrap();
// weight multiplier is increased for next block.
runtime_io::with_externalities(&mut t, || {
let fm = System::next_weight_multiplier();
println!("After a big block: {:?} -> {:?}", prev_multiplier, fm);
assert!(fm > prev_multiplier);
prev_multiplier = fm;
});
// execute a big block.
executor().call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
&block2.0,
true,
None,
).0.unwrap();
// weight multiplier is increased for next block.
runtime_io::with_externalities(&mut t, || {
let fm = System::next_weight_multiplier();
println!("After a big block: {:?} -> {:?}", prev_multiplier, fm);
assert!(fm > prev_multiplier);
});
}
#[test]
fn weight_multiplier_decreases_on_small_block() {
let mut t = new_test_ext(COMPACT_CODE, false);
let mut prev_multiplier = WeightMultiplier::default();
runtime_io::with_externalities(&mut t, || {
assert_eq!(System::next_weight_multiplier(), prev_multiplier);
});
let mut tt = new_test_ext(COMPACT_CODE, false);
let block1 = construct_block(
&mut tt,
1,
GENESIS_HASH.into(),
vec![
CheckedExtrinsic {
signed: None,
function: Call::Timestamp(timestamp::Call::set(42)),
},
CheckedExtrinsic {
signed: Some((charlie(), 0)),
function: Call::System(system::Call::remark(vec![0; 120])),
}
]
);
let block2 = construct_block(
&mut tt,
2,
block1.1.clone(),
vec![
CheckedExtrinsic {
signed: None,
function: Call::Timestamp(timestamp::Call::set(52)),
},
CheckedExtrinsic {
signed: Some((charlie(), 1)),
function: Call::System(system::Call::remark(vec![0; 120])),
}
]
);
// execute a big block.
executor().call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
&block1.0,
true,
None,
).0.unwrap();
// weight multiplier is increased for next block.
runtime_io::with_externalities(&mut t, || {
let fm = System::next_weight_multiplier();
println!("After a small block: {:?} -> {:?}", prev_multiplier, fm);
assert!(fm < prev_multiplier);
prev_multiplier = fm;
});
// execute a big block.
executor().call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
&block2.0,
true,
None,
).0.unwrap();
// weight multiplier is increased for next block.
runtime_io::with_externalities(&mut t, || {
let fm = System::next_weight_multiplier();
println!("After a small block: {:?} -> {:?}", prev_multiplier, fm);
assert!(fm < prev_multiplier);
});
}
#[cfg(feature = "benchmarks")]
mod benches {
use super::*;
+214
View File
@@ -0,0 +1,214 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Some configurable implementations as associated type for the substrate runtime.
use node_primitives::Balance;
use runtime_primitives::weights::{Weight, WeightMultiplier, MAX_TRANSACTIONS_WEIGHT, IDEAL_TRANSACTIONS_WEIGHT};
use runtime_primitives::traits::{Convert, Saturating};
use runtime_primitives::Fixed64;
use crate::Balances;
/// 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() }
}
/// A struct that updates the weight multiplier based on the saturation level of the previous block.
/// This should typically be called once per-block.
///
/// This assumes that weight is a numeric value in the u32 range.
///
/// Formula:
/// diff = (ideal_weight - current_block_weight)
/// v = 0.00004
/// next_weight = weight * (1 + (v . diff) + (v . diff)^2 / 2)
///
/// https://research.web3.foundation/en/latest/polkadot/Token%20Economics/#relay-chain-transaction-fees
pub struct WeightMultiplierUpdateHandler;
impl Convert<(Weight, WeightMultiplier), WeightMultiplier> for WeightMultiplierUpdateHandler {
fn convert(previous_state: (Weight, WeightMultiplier)) -> WeightMultiplier {
let (block_weight, multiplier) = previous_state;
let ideal = IDEAL_TRANSACTIONS_WEIGHT as u128;
let block_weight = block_weight as u128;
// determines if the first_term is positive
let positive = block_weight >= ideal;
let diff_abs = block_weight.max(ideal) - block_weight.min(ideal);
// diff is within u32, safe.
let diff = Fixed64::from_rational(diff_abs as i64, MAX_TRANSACTIONS_WEIGHT as u64);
let diff_squared = diff.saturating_mul(diff);
// 0.00004 = 4/100_000 = 40_000/10^9
let v = Fixed64::from_rational(4, 100_000);
// 0.00004^2 = 16/10^10 ~= 2/10^9. Taking the future /2 into account, then it is just 1 parts
// from a billionth.
let v_squared_2 = Fixed64::from_rational(1, 1_000_000_000);
let first_term = v.saturating_mul(diff);
// It is very unlikely that this will exist (in our poor perbill estimate) but we are giving
// it a shot.
let second_term = v_squared_2.saturating_mul(diff_squared);
if positive {
let excess = first_term.saturating_add(second_term);
multiplier.saturating_add(WeightMultiplier::from_fixed(excess))
} else {
// first_term > second_term
let negative = first_term - second_term;
multiplier.saturating_sub(WeightMultiplier::from_fixed(negative))
// despite the fact that apply_to saturates weight (final fee cannot go below 0)
// it is crucially important to stop here and don't further reduce the weight fee
// multiplier. While at -1, it means that the network is so un-congested that all
// transactions are practically free. We stop here and only increase if the network
// became more busy.
.max(WeightMultiplier::from_rational(-1, 1))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use runtime_primitives::weights::{MAX_TRANSACTIONS_WEIGHT, IDEAL_TRANSACTIONS_WEIGHT, Weight};
use runtime_primitives::Perbill;
// poc reference implementation.
#[allow(dead_code)]
fn weight_multiplier_update(block_weight: Weight) -> Perbill {
let block_weight = block_weight as f32;
let v: f32 = 0.00004;
// maximum tx weight
let m = MAX_TRANSACTIONS_WEIGHT as f32;
// Ideal saturation in terms of weight
let ss = IDEAL_TRANSACTIONS_WEIGHT as f32;
// Current saturation in terms of weight
let s = block_weight;
let fm = 1.0 + (v * (s/m - ss/m)) + (v.powi(2) * (s/m - ss/m).powi(2)) / 2.0;
// return a per-bill-like value.
let fm = if fm >= 1.0 { fm - 1.0 } else { 1.0 - fm };
Perbill::from_parts((fm * 1_000_000_000_f32) as u32)
}
fn fm(parts: i64) -> WeightMultiplier {
WeightMultiplier::from_parts(parts)
}
#[test]
fn stateless_weight_mul() {
// Light block. Fee is reduced a little.
assert_eq!(
WeightMultiplierUpdateHandler::convert((1024, WeightMultiplier::default())),
fm(-9990)
);
// a bit more. Fee is decreased less, meaning that the fee increases as the block grows.
assert_eq!(
WeightMultiplierUpdateHandler::convert((1024 * 4, WeightMultiplier::default())),
fm(-9960)
);
// ideal. Original fee.
assert_eq!(
WeightMultiplierUpdateHandler::convert((IDEAL_TRANSACTIONS_WEIGHT as u32, WeightMultiplier::default())),
fm(0)
);
// // More than ideal. Fee is increased.
assert_eq!(
WeightMultiplierUpdateHandler::convert(((IDEAL_TRANSACTIONS_WEIGHT * 2) as u32, WeightMultiplier::default())),
fm(10000)
);
}
#[test]
fn stateful_weight_mul_grow_to_infinity() {
assert_eq!(
WeightMultiplierUpdateHandler::convert((IDEAL_TRANSACTIONS_WEIGHT * 2, WeightMultiplier::default())),
fm(10000)
);
assert_eq!(
WeightMultiplierUpdateHandler::convert((IDEAL_TRANSACTIONS_WEIGHT * 2, fm(10000))),
fm(20000)
);
assert_eq!(
WeightMultiplierUpdateHandler::convert((IDEAL_TRANSACTIONS_WEIGHT * 2, fm(20000))),
fm(30000)
);
// ...
assert_eq!(
WeightMultiplierUpdateHandler::convert((IDEAL_TRANSACTIONS_WEIGHT * 2, fm(1_000_000_000))),
fm(1_000_000_000 + 10000)
);
}
#[test]
fn stateful_weight_mil_collapse_to_minus_one() {
assert_eq!(
WeightMultiplierUpdateHandler::convert((0, WeightMultiplier::default())),
fm(-10000)
);
assert_eq!(
WeightMultiplierUpdateHandler::convert((0, fm(-10000))),
fm(-20000)
);
assert_eq!(
WeightMultiplierUpdateHandler::convert((0, fm(-20000))),
fm(-30000)
);
// ...
assert_eq!(
WeightMultiplierUpdateHandler::convert((0, fm(1_000_000_000 * -1))),
fm(-1_000_000_000)
);
}
#[test]
fn weight_to_fee_should_not_overflow_on_large_weights() {
// defensive-only test. at the moment we are not allowing any weight more than
// 4 * 1024 * 1024 in a block.
let kb = 1024_u32;
let mb = kb * kb;
let max_fm = WeightMultiplier::from_fixed(Fixed64::from_natural(i64::max_value()));
vec![0, 1, 10, 1000, kb, 10 * kb, 100 * kb, mb, 10 * mb, Weight::max_value() / 2, Weight::max_value()]
.into_iter()
.for_each(|i| {
WeightMultiplierUpdateHandler::convert((i, WeightMultiplier::default()));
});
vec![10 * mb, Weight::max_value() / 2, Weight::max_value()]
.into_iter()
.for_each(|i| {
let fm = WeightMultiplierUpdateHandler::convert((
i,
max_fm
));
// won't grow. The convert saturates everything.
assert_eq!(fm, max_fm);
});
}
}
+7 -15
View File
@@ -37,7 +37,7 @@ use client::{
use runtime_primitives::{ApplyResult, impl_opaque_keys, generic, create_runtime_str, key_types};
use runtime_primitives::transaction_validity::TransactionValidity;
use runtime_primitives::traits::{
BlakeTwo256, Block as BlockT, DigestFor, NumberFor, StaticLookup, Convert,
BlakeTwo256, Block as BlockT, DigestFor, NumberFor, StaticLookup,
};
use version::RuntimeVersion;
use elections::VoteIndex;
@@ -56,6 +56,11 @@ pub use runtime_primitives::{Permill, Perbill};
pub use support::StorageValue;
pub use staking::StakerStatus;
/// Implementations for `Convert` and other helper structs passed into runtime modules as associated
/// types.
pub mod impls;
use impls::{CurrencyToVoteHandler, WeightMultiplierUpdateHandler};
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
@@ -122,6 +127,7 @@ impl system::Trait for Runtime {
type AccountId = AccountId;
type Lookup = Indices;
type Header = generic::Header<BlockNumber, BlakeTwo256>;
type WeightMultiplierUpdate = WeightMultiplierUpdateHandler;
type Event = Event;
type BlockHashCount = BlockHashCount;
}
@@ -223,20 +229,6 @@ parameter_types! {
pub const BondingDuration: staking::EraIndex = 24 * 28;
}
pub struct CurrencyToVoteHandler;
impl CurrencyToVoteHandler {
fn factor() -> u128 { (Balances::total_issuance() / u64::max_value() as u128).max(1) }
}
impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 { (x / Self::factor()) as u64 }
}
impl Convert<u128, u128> for CurrencyToVoteHandler {
fn convert(x: u128) -> u128 { x * Self::factor() }
}
impl staking::Trait for Runtime {
type Currency = Balances;
type CurrencyToVote = CurrencyToVoteHandler;