Phoenix-Protocol-Group / phoenix-contracts

Source code of the smart contracts of the Phoenix DeFi hub DEX protocol
GNU General Public License v3.0
10 stars 6 forks source link

PHOAM-013: Integer overflow will prevent depositors from adding liquidity to stable pool #343

Open gangov opened 2 months ago

gangov commented 2 months ago

Location

./contracts/pool_stable/src/math.rs:75

Description The compute_d function, called when providing liquidity, contains an integer overflow that prevents liquidity providers from adding funds to the stable pool. This issue occurs when the multiplication of two u128 values results in a number too large for the from_u128 function, which expects a u128, causing it to panic.

let d_product = d.pow(3).div(&U256::from_u128(
  env,
  amount_a_times_coins * amount_b_times_coins,
));

This problem is exacerbated by scaling these values to 18 decimals before passing them to the compute_d function, increasing the likelihood of an overflow.

let new_invariant = compute_d(
  &env,
  amp as u128,
  &[
    scale_value(new_balance_a, token_a_decimals, DECIMAL_PRECISION),
    scale_value(new_balance_b, token_b_decimals, DECIMAL_PRECISION),
  ],
);

This issue could have been detected if the testing suite used more common amounts rather than just fractions of a token.

Recommendation Cast each amount to U256 before applying the multiplication, as shown in the following example.