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

Implement FixedPoint trait. #5877

Merged
merged 45 commits into from
May 21, 2020
Merged
Show file tree
Hide file tree
Changes from 35 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
2416411
Implement Fixed trait.
marcio-diaz May 1, 2020
0c0c1da
Merge branch 'master' into md-fixed-point
marcio-diaz May 4, 2020
aa5d54d
Fix tests
marcio-diaz May 4, 2020
854e24b
Fix tests
marcio-diaz May 4, 2020
1b0bf3d
Fix tests 2
marcio-diaz May 4, 2020
087bca8
Address review comment regarding from_i129.
marcio-diaz May 4, 2020
45b625a
Remove precision by using log10() as suggested in review.
marcio-diaz May 4, 2020
7868978
Add small comments.
marcio-diaz May 4, 2020
14e1fac
Use checked versions + panic for ops::*.
marcio-diaz May 4, 2020
2133c2f
Remove repeated test.
marcio-diaz May 4, 2020
6c34aba
Uncomment test.
marcio-diaz May 4, 2020
9c93490
Remove casts.
marcio-diaz May 4, 2020
091991c
Add more comments.
marcio-diaz May 5, 2020
9ed7371
Add tests.
marcio-diaz May 5, 2020
838b97e
Panic on saturating_div_int
marcio-diaz May 5, 2020
86408cd
More tests.
marcio-diaz May 5, 2020
5819666
More docs.
marcio-diaz May 6, 2020
b1647ec
Saturating renames.
marcio-diaz May 6, 2020
698a452
Fix to_bound doc.
marcio-diaz May 6, 2020
75d5756
Move some impl to trait.
marcio-diaz May 6, 2020
a119bfa
Add range
marcio-diaz May 6, 2020
993e821
Add macro pre.
marcio-diaz May 6, 2020
d742b5e
More round() tests.
marcio-diaz May 6, 2020
514c76b
Delete confusion.
marcio-diaz May 7, 2020
0f05701
Merge branch 'master' into md-fixed-point
marcio-diaz May 7, 2020
c0deb6c
More impl to trait
marcio-diaz May 7, 2020
c39cd72
Add doc for fixedpoint op.
marcio-diaz May 7, 2020
e4a4bac
Remove trailing spaces.
marcio-diaz May 7, 2020
caebcad
Suggested docs changes.
marcio-diaz May 7, 2020
881a8e0
More tests and comments for roundings.
marcio-diaz May 7, 2020
50856ea
Some quickcheck tests.
marcio-diaz May 7, 2020
afd0e2e
Add missing panic, more test/comments.
marcio-diaz May 11, 2020
917fa0d
Merge branch 'master' into md-fixed-point
marcio-diaz May 12, 2020
19460a7
Nits.
marcio-diaz May 12, 2020
a6f4fd2
Rename.
marcio-diaz May 12, 2020
fd8f6c0
Remove primitives-types import.
marcio-diaz May 14, 2020
3054ba2
Merge branch 'master' into md-fixed-point
marcio-diaz May 18, 2020
e730534
Apply review suggestions
marcio-diaz May 18, 2020
9b4369c
Fix long lines and add some fuzz.
marcio-diaz May 19, 2020
cb9b29e
fix long line
marcio-diaz May 19, 2020
2907c24
Update fuzzer
marcio-diaz May 21, 2020
bfa811f
Merge branch 'master' into md-fixed-point
marcio-diaz May 21, 2020
66eb8d0
Bump impl
marcio-diaz May 21, 2020
0ef1888
Merge branch 'master' into md-fixed-point
gavofyork May 21, 2020
b5543d1
fix warnings
shawntabrizi May 21, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions bin/node/executor/tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use sp_core::{
NeverNativeValue, map, traits::Externalities, storage::{well_known_keys, Storage},
};
use sp_runtime::{
ApplyExtrinsicResult, Fixed128,
ApplyExtrinsicResult, Fixed128, FixedPointNumber,
traits::{Hash as HashT, Convert, BlakeTwo256},
transaction_validity::InvalidTransaction,
};
Expand Down Expand Up @@ -59,7 +59,7 @@ fn transfer_fee<E: Encode>(extrinsic: &E, fee_multiplier: Fixed128) -> Balance {
let weight = default_transfer_call().get_dispatch_info().weight;
let weight_fee = <Runtime as pallet_transaction_payment::Trait>::WeightToFee::convert(weight);

base_fee + fee_multiplier.saturated_multiply_accumulate(length_fee + weight_fee)
base_fee + fee_multiplier.saturating_mul_acc_int(length_fee + weight_fee)
}

fn xt() -> UncheckedExtrinsic {
Expand Down
4 changes: 2 additions & 2 deletions bin/node/executor/tests/fees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use frame_support::{
weights::{GetDispatchInfo, constants::ExtrinsicBaseWeight},
};
use sp_core::{NeverNativeValue, map, storage::Storage};
use sp_runtime::{Fixed128, Perbill, traits::{Convert, BlakeTwo256}};
use sp_runtime::{FixedPointNumber, Fixed128, Perbill, traits::{Convert, BlakeTwo256}};
use node_runtime::{
CheckedExtrinsic, Call, Runtime, Balances, TransactionPayment,
TransactionByteFee, WeightFeeCoefficient,
Expand All @@ -39,7 +39,7 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() {
let mut t = new_test_ext(COMPACT_CODE, false);

// initial fee multiplier must be zero
let mut prev_multiplier = Fixed128::from_parts(0);
let mut prev_multiplier = Fixed128::from_inner(0);

t.execute_with(|| {
assert_eq!(TransactionPayment::next_fee_multiplier(), prev_multiplier);
Expand Down
36 changes: 15 additions & 21 deletions bin/node/runtime/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@

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

use core::num::NonZeroI128;
use node_primitives::Balance;
use sp_runtime::traits::{Convert, Saturating};
use sp_runtime::{Fixed128, Perquintill};
use sp_runtime::{FixedPointNumber, Fixed128, Perquintill};
use frame_support::{traits::{OnUnbalanced, Currency, Get}, weights::Weight};
use crate::{Balances, System, Authorship, MaximumBlockWeight, NegativeImbalance};

Expand Down Expand Up @@ -78,18 +77,14 @@ impl<T: Get<Perquintill>> Convert<Fixed128, Fixed128> for TargetedFeeAdjustment<
// determines if the first_term is positive
let positive = block_weight >= target_weight;
let diff_abs = block_weight.max(target_weight) - block_weight.min(target_weight);
// safe, diff_abs cannot exceed u64 and it can always be computed safely even with the lossy
// `Fixed128::from_rational`.
let diff = Fixed128::from_rational(
diff_abs as i128,
NonZeroI128::new(max_weight.max(1) as i128).unwrap(),
);
// safe, diff_abs cannot exceed u64.
let diff = Fixed128::saturating_from_rational(diff_abs, max_weight.max(1));
let diff_squared = diff.saturating_mul(diff);

// 0.00004 = 4/100_000 = 40_000/10^9
let v = Fixed128::from_rational(4, NonZeroI128::new(100_000).unwrap());
let v = Fixed128::saturating_from_rational(4, 100_000);
// 0.00004^2 = 16/10^10 Taking the future /2 into account... 8/10^10
let v_squared_2 = Fixed128::from_rational(8, NonZeroI128::new(10_000_000_000).unwrap());
let v_squared_2 = Fixed128::saturating_from_rational(8, 10_000_000_000u64);

let first_term = v.saturating_mul(diff);
let second_term = v_squared_2.saturating_mul(diff_squared);
Expand All @@ -108,7 +103,7 @@ impl<T: Get<Perquintill>> Convert<Fixed128, Fixed128> for TargetedFeeAdjustment<
// multiplier. While at -1, it means that the network is so un-congested that all
// transactions have no weight fee. We stop here and only increase if the network
// became more busy.
.max(Fixed128::from_natural(-1))
.max(Fixed128::saturating_from_integer(-1))
}
}
}
Expand All @@ -120,7 +115,6 @@ mod tests {
use crate::{MaximumBlockWeight, AvailableBlockRatio, Runtime};
use crate::{constants::currency::*, TransactionPayment, TargetBlockFullness};
use frame_support::weights::Weight;
use core::num::NonZeroI128;

fn max() -> Weight {
MaximumBlockWeight::get()
Expand All @@ -143,7 +137,7 @@ mod tests {
let s = block_weight;

let fm = v * (s/m - ss/m) + v.powi(2) * (s/m - ss/m).powi(2) / 2.0;
let addition_fm = Fixed128::from_parts((fm * Fixed128::accuracy() as f64).round() as i128);
let addition_fm = Fixed128::from_inner((fm * Fixed128::accuracy() as f64).round() as i128);
previous.saturating_add(addition_fm)
}

Expand All @@ -158,7 +152,7 @@ mod tests {

#[test]
fn fee_multiplier_update_poc_works() {
let fm = Fixed128::from_rational(0, NonZeroI128::new(1).unwrap());
let fm = Fixed128::saturating_from_rational(0, 1);
let test_set = vec![
(0, fm.clone()),
(100, fm.clone()),
Expand All @@ -172,7 +166,7 @@ mod tests {
fee_multiplier_update(w, fm),
TargetedFeeAdjustment::<TargetBlockFullness>::convert(fm),
// Error is only 1 in 10^18
Fixed128::from_parts(1),
Fixed128::from_inner(1),
);
})
})
Expand All @@ -188,7 +182,7 @@ mod tests {
loop {
let next = TargetedFeeAdjustment::<TargetBlockFullness>::convert(fm);
fm = next;
if fm == Fixed128::from_natural(-1) { break; }
if fm == Fixed128::saturating_from_integer(-1) { break; }
iterations += 1;
}
println!("iteration {}, new fm = {:?}. Weight fee is now zero", iterations, fm);
Expand Down Expand Up @@ -227,7 +221,7 @@ mod tests {
fm = next;
iterations += 1;
let fee = <Runtime as pallet_transaction_payment::Trait>::WeightToFee::convert(tx_weight);
let adjusted_fee = fm.saturated_multiply_accumulate(fee);
let adjusted_fee = fm.saturating_mul_acc_int(fee);
println!(
"iteration {}, new fm = {:?}. Fee at this point is: {} units / {} millicents, \
{} cents, {} dollars",
Expand Down Expand Up @@ -330,8 +324,8 @@ mod tests {

// ... stops going down at -1
assert_eq!(
TargetedFeeAdjustment::<TargetBlockFullness>::convert(Fixed128::from_natural(-1)),
Fixed128::from_natural(-1)
TargetedFeeAdjustment::<TargetBlockFullness>::convert(Fixed128::saturating_from_integer(-1)),
Fixed128::saturating_from_integer(-1)
);
})
}
Expand All @@ -340,7 +334,7 @@ mod tests {
fn weight_to_fee_should_not_overflow_on_large_weights() {
let kb = 1024 as Weight;
let mb = kb * kb;
let max_fm = Fixed128::from_natural(i128::max_value());
let max_fm = Fixed128::saturating_from_integer(i128::max_value());

// check that for all values it can compute, correctly.
vec![
Expand All @@ -363,7 +357,7 @@ mod tests {
run_with_system_weight(i, || {
let next = TargetedFeeAdjustment::<TargetBlockFullness>::convert(Fixed128::default());
let truth = fee_multiplier_update(i, Fixed128::default());
assert_eq_error_rate!(truth, next, Fixed128::from_parts(50_000_000));
assert_eq_error_rate!(truth, next, Fixed128::from_inner(50_000_000));
});
});

Expand Down
4 changes: 2 additions & 2 deletions frame/balances/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ macro_rules! decl_tests {
($test:ty, $ext_builder:ty, $existential_deposit:expr) => {

use crate::*;
use sp_runtime::{Fixed128, traits::{SignedExtension, BadOrigin}};
use sp_runtime::{FixedPointNumber, Fixed128, traits::{SignedExtension, BadOrigin}};
marcio-diaz marked this conversation as resolved.
Show resolved Hide resolved
use frame_support::{
assert_noop, assert_ok, assert_err,
traits::{
Expand Down Expand Up @@ -153,7 +153,7 @@ macro_rules! decl_tests {
.monied(true)
.build()
.execute_with(|| {
pallet_transaction_payment::NextFeeMultiplier::put(Fixed128::from_natural(1));
pallet_transaction_payment::NextFeeMultiplier::put(Fixed128::saturating_from_integer(1));
Balances::set_lock(ID_1, &1, 10, WithdrawReason::Reserve.into());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath),
Expand Down
19 changes: 9 additions & 10 deletions frame/transaction-payment/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use frame_support::{
dispatch::DispatchResult,
};
use sp_runtime::{
Fixed128,
Fixed128, FixedPointNumber,
transaction_validity::{
TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError,
TransactionValidity,
Expand Down Expand Up @@ -79,7 +79,7 @@ pub trait Trait: frame_system::Trait {

decl_storage! {
trait Store for Module<T: Trait> as TransactionPayment {
pub NextFeeMultiplier get(fn next_fee_multiplier): Multiplier = Multiplier::from_parts(0);
pub NextFeeMultiplier get(fn next_fee_multiplier): Multiplier = Multiplier::from_inner(0);
}
}

Expand Down Expand Up @@ -156,7 +156,7 @@ impl<T: Trait> Module<T> {
// the adjustable part of the fee
let adjustable_fee = len_fee.saturating_add(unadjusted_weight_fee);
let targeted_fee_adjustment = NextFeeMultiplier::get();
let adjusted_fee = targeted_fee_adjustment.saturated_multiply_accumulate(adjustable_fee.saturated_into());
let adjusted_fee = targeted_fee_adjustment.saturating_mul_acc_int(adjustable_fee.saturated_into());

let base_fee = Self::weight_to_fee(T::ExtrinsicBaseWeight::get());
base_fee.saturating_add(adjusted_fee.saturated_into()).saturating_add(tip)
Expand All @@ -174,7 +174,7 @@ impl<T: Trait> Module<T> {
{
let fee = UniqueSaturatedInto::<u128>::unique_saturated_into(Self::weight_to_fee(weight));
UniqueSaturatedFrom::unique_saturated_from(
NextFeeMultiplier::get().saturated_multiply_accumulate(fee)
NextFeeMultiplier::get().saturating_mul_acc_int(fee)
)
}

Expand Down Expand Up @@ -313,7 +313,6 @@ impl<T: Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> whe
#[cfg(test)]
mod tests {
use super::*;
use core::num::NonZeroI128;
use codec::Encode;
use frame_support::{
impl_outer_dispatch, impl_outer_origin, parameter_types,
Expand Down Expand Up @@ -547,7 +546,7 @@ mod tests {
.execute_with(||
{
let len = 10;
NextFeeMultiplier::put(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap()));
NextFeeMultiplier::put(Fixed128::saturating_from_rational(1, 2));

let pre = ChargeTransactionPayment::<Runtime>::from(5 /* tipped */)
.pre_dispatch(&2, CALL, &info_from_weight(100), len)
Expand Down Expand Up @@ -635,7 +634,7 @@ mod tests {
.execute_with(||
{
// all fees should be x1.5
NextFeeMultiplier::put(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap()));
NextFeeMultiplier::put(Fixed128::saturating_from_rational(1, 2));
let len = 10;

assert!(
Expand Down Expand Up @@ -663,7 +662,7 @@ mod tests {
.execute_with(||
{
// all fees should be x1.5
NextFeeMultiplier::put(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap()));
NextFeeMultiplier::put(Fixed128::saturating_from_rational(1, 2));

assert_eq!(
TransactionPayment::query_info(xt, len),
Expand Down Expand Up @@ -692,7 +691,7 @@ mod tests {
.execute_with(||
{
// Next fee multiplier is zero
assert_eq!(NextFeeMultiplier::get(), Fixed128::from_natural(0));
assert_eq!(NextFeeMultiplier::get(), Fixed128::saturating_from_integer(0));

// Tip only, no fees works
let dispatch_info = DispatchInfo {
Expand Down Expand Up @@ -732,7 +731,7 @@ mod tests {
.execute_with(||
{
// Add a next fee multiplier
NextFeeMultiplier::put(Fixed128::from_rational(1, NonZeroI128::new(2).unwrap())); // = 1/2 = .5
NextFeeMultiplier::put(Fixed128::saturating_from_rational(1, 2)); // = 1/2 = .5
// Base fee is unaffected by multiplier
let dispatch_info = DispatchInfo {
weight: 0,
Expand Down
1 change: 1 addition & 0 deletions primitives/arithmetic/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ primitive-types = { version = "0.7.0", default-features = false }
rand = "0.7.2"
criterion = "0.3"
serde_json = "1.0"
quickcheck = "0.9"
marcio-diaz marked this conversation as resolved.
Show resolved Hide resolved

[features]
default = ["std"]
Expand Down
Loading