Sandwich Attack
Overview
Remediation Guide: How to Fix Sandwich Attack
The sandwich attack detector identifies swap functions in DEX and aggregator contracts that lack minimum output amount validation and deadline checks. A sandwich attack works by frontrunning the victim’s swap to move the price, letting the victim swap at a worse rate, then backrunning to reverse the price movement and pocket the difference.
Why This Is an Issue
Sandwich attacks extract over $500M annually from Ethereum users. Any swap function that accepts a user’s trade at whatever price the pool offers — without enforcing a minimum acceptable output — is vulnerable. The attacker needs only to observe the pending transaction in the mempool and submit bracketing transactions.
How to Resolve
// Before: Vulnerable — no slippage or deadline protection
function swap(address tokenIn, uint256 amountIn) external returns (uint256) {
uint256 amountOut = pool.swap(tokenIn, amountIn);
IERC20(tokenOut).transfer(msg.sender, amountOut);
return amountOut;
}
// After: Fixed — enforce minimum output and deadline
function swap(
address tokenIn,
uint256 amountIn,
uint256 minAmountOut,
uint256 deadline
) external returns (uint256) {
require(block.timestamp <= deadline, "Transaction expired");
uint256 amountOut = pool.swap(tokenIn, amountIn);
require(amountOut >= minAmountOut, "Insufficient output");
IERC20(tokenOut).transfer(msg.sender, amountOut);
return amountOut;
}
Detection Methodology
- Swap pattern identification: Identifies functions that perform token-for-token exchanges based on call patterns (transfer in, external call, transfer out).
- Minimum output check absence: Flags swap functions without a
require(amountOut >= minAmount)pattern. - Deadline check absence: Flags swap functions without
block.timestampcomparison. - Confidence scoring: Functions with neither check receive highest confidence; those with one of the two receive medium.
Limitations
False positives: Internal swap helpers called by outer functions that enforce slippage may be flagged. False negatives: Custom slippage mechanisms (e.g., oracle-based price floors) may not be recognized.
Related Detectors
- Slippage Validation — detects missing slippage checks broadly
- MEV Vulnerabilities — detects general MEV patterns
- Front-Running — detects frontrunning vulnerabilities