Skip to content

Commit 6948075

Browse files
authored
feat: increase precision for average tft price #435 (#438)
1 parent 53598f9 commit 6948075

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

substrate-node/pallets/pallet-tft-price/src/lib.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,9 @@ impl<T: Config> Pallet<T> {
400400
fn calc_avg() -> u32 {
401401
let queue = Self::queue_transient();
402402
let items = queue.get_all_values();
403-
items.iter().fold(0_u32, |a, b| a.saturating_add(*b)) / items.len() as u32
403+
let sum = items.iter().fold(0_u32, |a, b| a.saturating_add(*b));
404+
(U32F32::from_num(sum) / U32F32::from_num(items.len()))
405+
.round()
406+
.to_num::<u32>()
404407
}
405408
}

substrate-node/pallets/pallet-tft-price/src/tests.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,28 @@ fn test_set_allowed_origin_by_wrong_origin_fails() {
2828
})
2929
}
3030

31+
#[test]
32+
fn test_calc_avg_rounding_works() {
33+
let mut t = ExternalityBuilder::build();
34+
t.execute_with(|| {
35+
let mut queue = TFTPriceModule::queue_transient();
36+
queue.push(499); // avg = 499.0
37+
assert_eq!(TFTPriceModule::calc_avg(), 499);
38+
queue.push(500); // avg = 499.5
39+
assert_eq!(TFTPriceModule::calc_avg(), 500);
40+
queue.push(500); // avg = 499.66
41+
assert_eq!(TFTPriceModule::calc_avg(), 500);
42+
queue.push(500); // avg = 499.75
43+
assert_eq!(TFTPriceModule::calc_avg(), 500);
44+
queue.push(499); // avg = 499.66
45+
assert_eq!(TFTPriceModule::calc_avg(), 500);
46+
queue.push(499); // avg = 499.5
47+
assert_eq!(TFTPriceModule::calc_avg(), 500);
48+
queue.push(499); // avg = 499.25
49+
assert_eq!(TFTPriceModule::calc_avg(), 499);
50+
})
51+
}
52+
3153
#[test]
3254
fn test_set_prices_works() {
3355
let mut t = ExternalityBuilder::build();

0 commit comments

Comments
 (0)