Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
11 changes: 8 additions & 3 deletions crates/driver/src/domain/competition/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use {
},
util::{Bytes, math},
},
ethrpc::alloy::conversions::IntoLegacy,
ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy},
futures::{StreamExt, future::Either, stream::FuturesUnordered},
itertools::Itertools,
num::Zero,
Expand Down Expand Up @@ -495,8 +495,13 @@ impl Competition {
// following: `available + (fee * available / sell) <= allocated_balance`
if let order::Partial::Yes { available } = &mut order.partial {
*available = order::TargetAmount(
math::mul_ratio(available.0, allocated_balance.0, max_sell.0)
.unwrap_or_default(),
math::mul_ratio(
available.0.into_alloy(),
allocated_balance.0.into_alloy(),
max_sell.0.into_alloy(),
)
.unwrap_or_default()
.into_legacy(),
);
}
if order.available().is_zero() {
Expand Down
26 changes: 18 additions & 8 deletions crates/driver/src/domain/competition/order/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use {
util::{self, Bytes},
},
derive_more::{From, Into},
ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy},
model::order::{BuyTokenDestination, SellTokenSource},
};
pub use {fees::FeePolicy, signature::Signature};
Expand Down Expand Up @@ -149,14 +150,23 @@ impl Order {
};
let target = self.target();

amounts.sell.amount = util::math::mul_ratio(amounts.sell.amount.0, available.0, target.0)
.unwrap_or_default()
.into();

amounts.buy.amount =
util::math::mul_ratio_ceil(amounts.buy.amount.0, available.0, target.0)
.unwrap_or_default()
.into();
amounts.sell.amount = util::math::mul_ratio(
amounts.sell.amount.0.into_alloy(),
available.0.into_alloy(),
target.0.into_alloy(),
)
.unwrap_or_default()
.into_legacy()
.into();

amounts.buy.amount = util::math::mul_ratio_ceil(
amounts.buy.amount.0.into_alloy(),
available.0.into_alloy(),
target.0.into_alloy(),
)
.unwrap_or_default()
.into_legacy()
.into();

amounts
}
Expand Down
104 changes: 96 additions & 8 deletions crates/driver/src/util/math.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use ethereum_types::U256;
use alloy::primitives::{U256, U512};

/// Computes `x * q / d` rounding down.
///
Expand All @@ -13,7 +13,16 @@ pub fn mul_ratio(x: U256, q: U256, d: U256) -> Option<U256> {
return Some(res / d);
}

x.full_mul(q).checked_div(d.into())?.try_into().ok()
// SAFETY: at this point !d.is_zero() upholds
let div = (x.widening_mul(q)) / U512::from(d);

// After the division, check the most significant limbs (>U256) for overflow
let limbs = div.into_limbs();
if limbs[4..] != [0, 0, 0, 0] {
return None;
}

Some(U256::from_limbs_slice(&limbs[..4]))
}

/// Computes `x * q / d` rounding up.
Expand All @@ -26,12 +35,91 @@ pub fn mul_ratio_ceil(x: U256, q: U256, d: U256) -> Option<U256> {

// fast path when math in U256 doesn't overflow
if let Some(p) = x.checked_mul(q) {
let (div, rem) = p.div_mod(d);
return div.checked_add(u8::from(!rem.is_zero()).into());
let (div, rem) = (p / d, p % d);
return div.checked_add(U256::from(!rem.is_zero()));
}

let p = x.widening_mul(q);
let d = U512::from(d);
// SAFETY: at this point !d.is_zero() upholds
let (div, rem) = (p / d, p % d);

// After the division, check the most significant limbs (>U256) for overflow
let limbs = div.into_limbs();
if limbs[4..] != [0, 0, 0, 0] {
return None;
}

let result = U256::from_limbs_slice(&div.into_limbs()[..4]);
result.checked_add(U256::from(!rem.is_zero()))
}

#[cfg(test)]
mod test {
use {
crate::util::math::{mul_ratio, mul_ratio_ceil},
alloy::primitives::U256,
};

#[test]
fn mul_ratio_zero() {
assert!(mul_ratio(U256::from(10), U256::from(10), U256::ZERO).is_none());
}

let p = x.full_mul(q);
let (div, rem) = p.div_mod(d.into());
let result = U256::try_from(div).ok()?;
result.checked_add(u8::from(!rem.is_zero()).into())
#[test]
fn mul_ratio_overflow() {
assert!(mul_ratio(U256::MAX, U256::from(2), U256::ONE).is_none());
}

#[test]
fn mul_ratio_ceil_zero() {
assert!(mul_ratio_ceil(U256::from(10), U256::from(10), U256::ZERO).is_none());
}

#[test]
fn mul_ratio_ceil_overflow() {
assert!(mul_ratio_ceil(U256::MAX, U256::from(2), U256::ONE).is_none());
}

#[test]
fn mul_ratio_normal() {
// Exact division
assert_eq!(
mul_ratio(U256::from(100), U256::from(5), U256::from(10)),
Some(U256::from(50))
);

// Division with remainder (rounds down)
assert_eq!(
mul_ratio(U256::from(100), U256::from(3), U256::from(10)),
Some(U256::from(30))
);

// Large values that don't overflow
assert_eq!(
mul_ratio(U256::from(u128::MAX), U256::from(2), U256::from(4)),
Some(U256::from(u128::MAX / 2))
);
}

#[test]
fn mul_ratio_ceil_normal() {
// Exact division (no rounding needed)
assert_eq!(
mul_ratio_ceil(U256::from(100), U256::from(5), U256::from(10)),
Some(U256::from(50))
);

// Division with remainder (rounds up)
assert_eq!(
mul_ratio_ceil(U256::from(10), U256::from(3), U256::from(4)),
Some(U256::from(8))
);

// Large values that don't overflow
assert_eq!(
mul_ratio_ceil(U256::from(u128::MAX), U256::from(2), U256::from(4)),
Some(U256::from(u128::MAX / 2 + 1))
);
}
}
Loading