Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
33 changes: 28 additions & 5 deletions contracts/price-oracle/src/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,18 +128,41 @@ pub fn normalize_to_seven(value: i128, input_decimals: u32) -> Result<i128, Erro
/// normalize_to_nine(1_000_000_000_00, 11) => 1_000_000_000 (scale down)
/// ```
pub fn normalize_to_nine(value: i128, native_decimals: u32) -> Result<i128, Error> {
// This normalization is a critical fixed-point boundary.
// To reduce rounding/truncation drift when this function is used
// inside multi-step rate translations, we do the multiply/divide
// sequence in a temporarily up-scaled space.

const TARGET: u32 = 9;
if native_decimals < TARGET {
const INTERIOR_SCALE: i128 = 1_000_000_000_000_000; // 10^15

// NOTE: INTERIOR_SCALE is chosen so that the final result remains within
// the project's 9-decimal fixed-point footprint by dividing back down
// after the translation.

let scaled = value
.checked_mul(INTERIOR_SCALE)
.ok_or(Error::PriceMathOverflow)?;

let normalized_in_interior_space = if native_decimals < TARGET {
let diff = TARGET - native_decimals;
let multiplier = 10_i128.checked_pow(diff).ok_or(Error::PriceMathOverflow)?;
value.checked_mul(multiplier).ok_or(Error::PriceMathOverflow)
scaled
.checked_mul(multiplier)
.ok_or(Error::PriceMathOverflow)?
} else if native_decimals > TARGET {
let diff = native_decimals - TARGET;
let divisor = 10_i128.checked_pow(diff).ok_or(Error::PriceMathOverflow)?;
value.checked_div(divisor).ok_or(Error::PriceMathOverflow)
scaled
.checked_div(divisor)
.ok_or(Error::PriceMathOverflow)?
} else {
Ok(value)
}
scaled
};

normalized_in_interior_space
.checked_div(INTERIOR_SCALE)
.ok_or(Error::PriceMathOverflow)
}

/// Calculate the inverse of a price (e.g., NGN/XLM → XLM/NGN).
Expand Down
6 changes: 6 additions & 0 deletions test_snapshots/test/test_cancel_upgrade.1.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
},
{
"u64": 0
},
{
"u64": 18446744073709551615
}
]
}
Expand Down Expand Up @@ -382,6 +385,9 @@
},
{
"u64": 0
},
{
"u64": 18446744073709551615
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
},
{
"u64": 0
},
{
"u64": 18446744073709551615
}
]
}
Expand Down Expand Up @@ -361,6 +364,9 @@
},
{
"u64": 0
},
{
"u64": 18446744073709551615
}
]
}
Expand Down
Loading