Slippage Protection Remediation
How to fix missing slippage protection in token swaps.
Slippage Protection Remediation
Overview
Related Detector: Slippage Protection
Swaps without minimum output bounds are vulnerable to sandwich attacks. The fix is to accept a user-supplied min_amount_out parameter and reject transactions where the output falls below this threshold.
Recommended Fix
Before (Vulnerable)
let output = execute_swap(pool, amount_in)?;
transfer_tokens(output)?; // No minimum check
After (Fixed)
let output = execute_swap(pool, amount_in)?;
require!(output >= min_amount_out, ErrorCode::SlippageExceeded);
transfer_tokens(output)?;
Alternative Mitigations
Pre/Post Price Comparison
Compare pool price before and after the swap to detect manipulation:
let price_before = get_pool_price(&ctx.accounts.pool)?;
let output = execute_swap(&ctx.accounts.pool, amount_in)?;
let price_after = get_pool_price(&ctx.accounts.pool)?;
let price_change = price_before.abs_diff(price_after) * 10000 / price_before;
require!(price_change <= max_price_impact_bps, ErrorCode::ExcessivePriceImpact);
Common Mistakes
Mistake: Zero as Default Minimum
// WRONG: min_amount_out defaults to 0 if not provided
pub fn swap(ctx: Context<Swap>, amount: u64, min_out: Option<u64>) -> Result<()> {
let min = min_out.unwrap_or(0); // Effectively no protection
Require min_amount_out as a mandatory parameter with no default.