SSSwap

First Flight #41
Beginner FriendlyRust
100 EXP
View results
Submission Details
Severity: high
Valid

Missing Decimal Handling in LP Token Mint Calculation

Description

The liquidity_calculation function calculates the LP tokens to mint as the square root of the product of the raw token amounts. However, it does not account for differences in token decimals, which leads to incorrect LP token amounts when tokens have different decimal precisions.

Impact

  • Incorrect LP token minting causing unfair liquidity representation.

  • Potential economic exploits due to miscalculated LP shares.

  • Pool imbalance and user losses.

Recommendation

Normalize token amounts by their decimals before performing the liquidity calculation to ensure accurate LP token minting.

Fixed Code

fn liquidity_calculation(
amount_token_a: u64,
decimals_token_a: u8,
amount_token_b: u64,
decimals_token_b: u8,
lp_token_decimals: u8,
) -> Result<u64> {
// Convert amounts to u128 for safe math
let amount_a_u128 = amount_token_a as u128;
let amount_b_u128 = amount_token_b as u128;
// Normalize token amounts to a common decimal scale (e.g., 18 decimals)
// Adjust each amount by shifting decimals to 18
let scale = 18u32;
let adjusted_amount_a = amount_a_u128
.checked_mul(10u128.pow((scale - decimals_token_a as u32) as u32))
.ok_or(AmmError::Overflow)?;
let adjusted_amount_b = amount_b_u128
.checked_mul(10u128.pow((scale - decimals_token_b as u32) as u32))
.ok_or(AmmError::Overflow)?;
// Calculate lp amount with normalized amounts
let lp_amount_u128 = adjusted_amount_a
.checked_mul(adjusted_amount_b)
.ok_or(AmmError::Overflow)?
.integer_sqrt();
// Adjust lp amount back to lp_token_decimals
let lp_amount_scaled = lp_amount_u128
.checked_div(10u128.pow((scale - lp_token_decimals as u32) as u32))
.ok_or(AmmError::Overflow)?;
if lp_amount_scaled == 0 {
return err!(AmmError::LpAmountCalculation);
}
Ok(lp_amount_scaled as u64)
}

This function takes the decimals of each token and the LP token as input, normalizes the token amounts to a common precision, performs the square root calculation, and scales the LP token amount accordingly.

Updates

Lead Judging Commences

0xtimefliez Lead Judge 3 days ago
Submission Judgement Published
Validated
Assigned finding tags:

Protocol is incompatible with differenct decimals

Support

FAQs

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