Skip to content

Commit ab475d2

Browse files
authored
Use rounded up computation when calculating fee (#1511)
* Use perbill floating point mult when calculating weight * Cosmetic changes * Rename test * Always round up fractional computation * Comments * fmt * comments
1 parent 3dc7902 commit ab475d2

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

pallets/xcm-transactor/src/lib.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -742,10 +742,17 @@ pub mod pallet {
742742
}
743743

744744
/// Returns the fee for a given set of parameters
745+
/// We always round up in case of fractional division
745746
pub fn calculate_fee_per_second(weight: Weight, fee_per_second: u128) -> u128 {
746-
let weight_fee =
747-
fee_per_second.saturating_mul(weight as u128) / (WEIGHT_PER_SECOND as u128);
748-
return weight_fee;
747+
// grab WEIGHT_PER_SECOND as u128
748+
let weight_per_second_u128 = WEIGHT_PER_SECOND as u128;
749+
750+
// we add WEIGHT_PER_SECOND -1 after multiplication to make sure that
751+
// if there is a fractional part we round up the result
752+
let fee_mul_rounded_up = (fee_per_second.saturating_mul(weight as u128))
753+
.saturating_add(weight_per_second_u128 - 1);
754+
755+
fee_mul_rounded_up / weight_per_second_u128
749756
}
750757
}
751758
}

pallets/xcm-transactor/src/tests.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,23 @@ fn test_fee_calculation_works() {
315315
})
316316
}
317317

318+
// Kusama case
319+
#[test]
320+
fn test_fee_calculation_works_kusama_0_9_20_case() {
321+
ExtBuilder::default()
322+
.with_balances(vec![])
323+
.build()
324+
.execute_with(|| {
325+
// 38620923000 * 319324000/1e12 = 12332587.6161
326+
// integer arithmetic would round this to 12332587
327+
// we test here that it rounds up to 12332588 instead
328+
assert_eq!(
329+
XcmTransactor::calculate_fee_per_second(319324000, 38620923000),
330+
12332588
331+
);
332+
})
333+
}
334+
318335
#[test]
319336
fn test_max_transact_weight_migration_works() {
320337
ExtBuilder::default()

0 commit comments

Comments
 (0)