SSSwap

First Flight #41
Beginner FriendlyRust
100 EXP
View results
Submission Details
Impact: high
Likelihood: high
Invalid

Invalid formula for swap with fee in swap_exact_in

Root + Impact

Description

  • `swap_exact_in` is supposed to perform swap operation with exact amount in between two tokens by following constant product formula (inspired by Uniswap V2)

  • current implementation uses bad formula for swap with fee

let numerator: u128 = (reserve_b as u128).checked_mul(amount_in as u128).ok_or(AmmError::Overflow)?;
let denominator: u128 = (reserve_a as u128).checked_add(amount_in as u128).ok_or(AmmError::Overflow)?;
if denominator == 0 {
return err!(AmmError::DivisionByZero);
}
let mut amount_out: u64 = numerator.div_floor(&denominator) as u64;
let lp_fees = (amount_out as u128 * 3).div_floor(&1000) as u64;
amount_out = amount_out - lp_fees;

Risk

Likelihood:

  • High, every swap with exact amount in is affected

Impact:

  • High, incorrect formula leads to unpredictable behaviour, including severe fund loss, pool drain etc.

Proof of Concept

// current, invalid formula:
// reserve_b * amount_in
// amount_out = ---------------------
// reserve_a * amount_in
let mut amount_out: u64 = numerator.div_floor(&denominator) as u64;
// 3
// lp_fees = amount_out * ------
// 1000
let lp_fees = (amount_out as u128 * 3).div_floor(&1000) as u64;
amount_out = amount_out - lp_fees;

Recommended Mitigation

Apply correct formula calculation:

amount_in * (1 - fee) * reserve_b
amount_out = ------------------------------------
reserve_a + amount_in * (1 - fee)
Updates

Lead Judging Commences

0xtimefliez Lead Judge 6 days ago
Submission Judgement Published
Invalidated
Reason: Too generic

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.