Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

biguint math toolings #971

Merged
merged 23 commits into from
Nov 16, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
12 changes: 12 additions & 0 deletions Cargo.lock

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

5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,7 @@ path = "crates/settings"
path = "crates/quote"

[workspace.dependencies.rain_orderbook_test_fixtures]
path = "crates/test_fixtures"
path = "crates/test_fixtures"

[workspace.dependencies.rain_orderbook_math]
path = "crates/math"
17 changes: 17 additions & 0 deletions crates/math/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "rain_orderbook_math"
description = "Math toolings for Rain Orderbooks crates"
version.workspace = true
edition.workspace = true
license.workspace = true
homepage.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
thiserror = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_bytes = { workspace = true }
once_cell = { workspace = true }
alloy = { workspace = true, features = ["rand"] }
164 changes: 164 additions & 0 deletions crates/math/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
use alloy::primitives::{
ruint::UintTryFrom,
utils::{parse_units, ParseUnits, Unit, UnitsError},
U256,
};
use once_cell::sync::Lazy;

/// 1e18 oe one ether in U256
pub static ONE18: Lazy<U256> = Lazy::new(|| U256::from(1_000_000_000_000_000_000_u64));

/// Converts a value to a 18 fixed point U256 given the decimals point,
/// A valid ethereum decimals point range is always less than 77
pub fn to_18_decimals<T, D: TryInto<Unit, Error = UnitsError>>(
amount: T,
decimals: D,
) -> Result<U256, UnitsError>
where
U256: UintTryFrom<T>,
{
Ok(parse_units(
thedavidmeister marked this conversation as resolved.
Show resolved Hide resolved
&ParseUnits::U256(U256::from(amount)).format_units(decimals.try_into()?),
18,
)?
.get_absolute())
}

/// A trait that provide math operations as Uint256
pub trait BigUintMath<T> {
/// Scales the value to 18 point decimals U256
fn scale_18<D: TryInto<Unit, Error = UnitsError>>(self, decimals: D) -> Result<U256, UnitsError>
where
Self: Sized,
U256: UintTryFrom<Self>,
{
to_18_decimals(self, decimals)
}

/// Performs mulDiv operation
fn mul_div<K, U>(self, mul: K, div: U) -> U256
where
Self: Sized,
K: Sized,
U: Sized,
U256: UintTryFrom<Self> + UintTryFrom<K> + UintTryFrom<U>,
{
U256::from(self)
.saturating_mul(U256::from(mul))
thedavidmeister marked this conversation as resolved.
Show resolved Hide resolved
.checked_div(U256::from(div))
thedavidmeister marked this conversation as resolved.
Show resolved Hide resolved
.unwrap_or(U256::MAX)
}

/// Performs 18 fixed point mul operation
fn mul_18<K>(self, other: K) -> U256
where
Self: Sized,
K: Sized,
U256: UintTryFrom<Self> + UintTryFrom<K>,
{
U256::from(self).mul_div(other, *ONE18)
}

/// Performs 18 fixed point div operation
fn div_18<K>(self, other: K) -> U256
where
Self: Sized,
K: Sized,
U256: UintTryFrom<Self> + UintTryFrom<K>,
{
U256::from(self).mul_div(*ONE18, other)
}
}

// implement this trait for all rust native usigned integer types
// as well as all alloy usigned units such as U8, U16, ... U128, U256
impl<T> BigUintMath<T> for T where U256: UintTryFrom<T> {}

#[cfg(test)]
mod test {
use super::*;
use alloy::primitives::U256;
use std::str::FromStr;

#[test]
fn test_to_18_decimals_happy() {
// u8
let value = 45_u8;
let result = to_18_decimals(value, 1).unwrap();
let expected = U256::from_str("4_500_000_000_000_000_000").unwrap();
assert_eq!(result, expected);

// u32
let value = 123456789_u32;
let result = to_18_decimals(value, 12).unwrap();
let expected = U256::from_str("123_456_789_000_000").unwrap();
assert_eq!(result, expected);

// U256
let value = U256::from(123456789u32);
let result = to_18_decimals(value, 12).unwrap();
let expected = U256::from_str("123_456_789_000_000").unwrap();
assert_eq!(result, expected);
}

#[test]
fn test_to_18_decimals_unhappy() {
let result = to_18_decimals(
U256::from_str("4_500_000_000_000_000_000").unwrap(),
99, // invalid ethereum decimals unit
);
assert!(result.is_err());
}

#[test]
fn test_big_uint_math_scale_18() {
// u8
let value = 121_u8;
let result = value.scale_18(4).unwrap();
let expected = U256::from_str("12_100_000_000_000_000").unwrap();
assert_eq!(result, expected);

// u32
let value = 123456789_u32;
let result = value.scale_18(12).unwrap();
let expected = U256::from_str("123_456_789_000_000").unwrap();
assert_eq!(result, expected);

// U256
let value = U256::from(123456789u32);
let result = value.scale_18(12).unwrap();
let expected = U256::from_str("123_456_789_000_000").unwrap();
assert_eq!(result, expected);
}

#[test]
fn test_big_uint_math_mul_div() {
// (10_000 * 8) / 2 = 40_000
let value = 10_000_u16;
let mul_value = U256::from(8);
let div_value = 2_u8;
let result = value.mul_div(mul_value, div_value);
let expected = U256::from(40_000_u32);
assert_eq!(result, expected);
}

#[test]
fn test_big_uint_math_mul_18() {
// 10_000 * 3 = 30_000
let value = 10_000_u32.scale_18(0).unwrap();
let mul_value = 3_u16.scale_18(0).unwrap();
let result = value.mul_18(mul_value);
let expected = U256::from_str("30_000_000_000_000_000_000_000").unwrap();
assert_eq!(result, expected);
}

#[test]
fn test_big_uint_math_div_18() {
// 10_000 / 3 = 3_333.3333...
let value = 10_000_u64.scale_18(0).unwrap();
let mul_value = 3_u8.scale_18(0).unwrap();
let result = value.div_18(mul_value);
let expected = U256::from_str("3_333_333_333_333_333_333_333").unwrap();
assert_eq!(result, expected);
}
}
Loading