defituna_client/math/
fixed.rs

1use crate::math::U256;
2use crate::TunaError as ErrorCode;
3use std::ops::Mul;
4
5pub enum Rounding {
6    Up,
7    Down,
8}
9
10pub fn mul_u256(x: u128, y: u128) -> U256 {
11    U256::from(x).mul(U256::from(y))
12}
13
14pub fn mul_div_64(x: u64, y: u64, d: u64, rounding: Rounding) -> Result<u64, ErrorCode> {
15    let x_128 = x as u128;
16    let y_128 = y as u128;
17    let d_128 = d as u128;
18
19    match rounding {
20        Rounding::Up => {
21            let result = (x_128 * y_128)
22                .checked_add(d_128.checked_sub(1).ok_or(ErrorCode::MathUnderflow)?)
23                .ok_or(ErrorCode::MathOverflow)?
24                .checked_div(d_128)
25                .ok_or(ErrorCode::MathOverflow)?
26                .try_into()
27                .map_err(|_| ErrorCode::MathOverflow)?;
28            Ok(result)
29        }
30
31        Rounding::Down => {
32            let result: u64 = (x_128 * y_128)
33                .checked_div(d_128)
34                .ok_or(ErrorCode::MathOverflow)?
35                .try_into()
36                .map_err(|_| ErrorCode::MathOverflow)?;
37            Ok(result)
38        }
39    }
40}