What is Slippage?

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?


Why On-Chain Calculation Fails

The Core Problem: Time and Information

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:

  1. You’re calculating price at execution time - This defeats the purpose
  2. By the time this line runs, the price has already changed - Miner can manipulate
  3. The transaction order matters - MEV attacks can front-run you
  4. You’re trusting on-chain price oracle - Oracles themselves can be stale or manipulated

The MEV Attack: Why On-Chain Fails Catastrophically

Here’s a real attack scenario:

Scenario: You’re swapping on Uniswap