First, let’s establish the concept. Slippage is the difference between the price you expect to pay and the actual price you end up paying when your transaction executes.
Example:
You want to swap 1 ETH for USDC
Expected price: 1 ETH = 2000 USDC
You set slippage tolerance: 0.5%
So you expect to receive: 2000 USDC
Your minimum acceptable: 1990 USDC (0.5% less)
But by the time your transaction executes:
Another big swap happened before yours
Actual received: 1980 USDC
Result: You lose 20 USDC to slippage (transaction still completes)
Now here’s the critical part: Why can’t you calculate this on-chain?
On-chain, you have a fundamental problem:
// VULNERABLE - Attempted on-chain slippage protection
function swapWithSlippage(
uint256 amountIn,
uint256 slippageTolerance // 50 = 0.5%
) public {
// Get current price from AMM
uint256 currentPrice = getPrice(); // Get price NOW, on-chain
// Calculate minimum output
uint256 minOutput = (currentPrice * amountIn) / 100 -
(currentPrice * amountIn * slippageTolerance) / 10000;
// Execute swap
executeSwap(amountIn, minOutput);
}
The problem with this code:
Here’s a real attack scenario:
Scenario: You’re swapping on Uniswap