Skip to content

Commit

Permalink
Fix div by 0 in slippage computation (#2024)
Browse files Browse the repository at this point in the history
# Description
If some external API returns a `0` amount for a buy order it will pass
the `execution_respects_order` check and will cause a panic in this
slippage computation due to div by 0.

# Changes
Returns errors when slippage computation would encounter any div by zero
(simply use `.checked_div()`).

## How to test
All unit tests should continue to pass
  • Loading branch information
MartinquaXD authored and sunce86 committed Oct 28, 2023
1 parent 380adf6 commit da30218
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions crates/solver/src/liquidity/slippage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use {
clap::{Parser, ValueEnum as _},
ethcontract::{H160, U256},
model::order::OrderKind,
num::{BigInt, BigRational, Integer as _, ToPrimitive as _},
num::{BigInt, BigRational, CheckedDiv, Integer as _, ToPrimitive as _},
once_cell::sync::OnceCell,
shared::{external_prices::ExternalPrices, http_solver::model::TokenAmount},
std::{
Expand Down Expand Up @@ -327,10 +327,15 @@ impl SlippageCalculator {
) -> Result<(Cow<BigRational>, BigInt)> {
let relative = if let Some(max_absolute_native_token) = self.absolute.clone() {
let price = price.context("missing token price")?;
let max_absolute_slippage =
BigRational::new(max_absolute_native_token, 1.into()) / price;
let max_absolute_slippage = BigRational::new(max_absolute_native_token, 1.into())
.checked_div(price)
.context("price is zero")?;

let max_relative_slippage_respecting_absolute_limit = max_absolute_slippage / &amount;
let amount = BigRational::new(amount.clone(), 1.into());

let max_relative_slippage_respecting_absolute_limit = max_absolute_slippage
.checked_div(&amount)
.context("amount is zero")?;

cmp::min(
Cow::Owned(max_relative_slippage_respecting_absolute_limit),
Expand Down

0 comments on commit da30218

Please sign in to comment.