Sandwich attack: how it works and how a contract prevents it

A sandwich attack is when someone sees a pending swap, buys the same asset just before it and sells just after it, so the swap fills at a worse price and the attacker keeps the difference. It works whenever a swap will accept a bad price, because its minimum output is zero, too loose, or worked out on-chain from the very price the attacker just moved. The fix is a minimum output and a deadline that come from outside the transaction: set by the user, or checked against a price one block can't move.

Last updated . 6 minute read. By the QuillAudits Team.

How does a sandwich attack work?

  1. A swap waits in the public mempool, for example 10 ETH into USDC, with a minimum output well below the current quote.
  2. The attacker's first trade, the front run, sells ETH into the same pool just before it and moves the price against the swap.
  3. The swap fills at the worse price. It gets less USDC but still more than its minimum, so it succeeds.
  4. The attacker's second trade, the back run, sells the USDC back. The pool has moved further, and the attacker ends up with more ETH than it started with.

Here are the numbers for a pool that holds 1,000 ETH and 3,000,000 USDC, so 1 ETH starts at 3,000 USDC:

Step ETH in pool USDC in pool Result
No attack: the user sells 10 ETH 1,010 2,970,297 User receives 29,703 USDC
Front run: the attacker sells 100 ETH 1,100 2,727,273 Attacker receives 272,727 USDC
The user sells 10 ETH 1,110 2,702,703 User receives 24,570 USDC, 5,133 less
Back run: the attacker sells its 272,727 USDC 1,008.26 2,975,430 Attacker receives 101.74 ETH, 1.74 more than it sold

The user's minimum output is the attacker's budget. In this example a minimum of 24,570 USDC or less lets this attack through. A minimum 1% under the quote, about 29,406 USDC, makes the user's swap revert against a 100 ETH front run, and a smaller sandwich can take at most the gap of about 297 USDC. A bot sizes its first trade so the victim's output lands just above whatever minimum was set.

Who gets sandwiched: users or contracts?

Users get sandwiched when a wallet or front end sends a loose limit. Contracts get sandwiched when they swap on their own account: a vault selling its rewards, a protocol rebalancing liquidity, a liquidation that sells seized collateral, or a router that passes a minimum of zero. Those swaps are often public functions, so the attacker can also choose the moment by calling the function themselves between their two trades.

That makes a protocol swap a better target than a user's: the attacker doesn't have to wait for it, and it can be as large as the protocol's whole balance.

What does vulnerable code look like?

This vault sells its reward token for its underlying asset whenever anyone calls harvest. It passes a minimum output of zero and a deadline of block.timestamp, so any price at any time is accepted.

Vulnerable: a public harvest that accepts any price (illustrative, not audited code) HarvestVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
}

interface IRouter {
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

contract HarvestVault {
    IERC20 public immutable reward;
    IERC20 public immutable asset;
    IRouter public immutable router;

    constructor(IERC20 reward_, IERC20 asset_, IRouter router_) {
        reward = reward_;
        asset = asset_;
        router = router_;
    }

    // Anyone can call this, at a moment of their choosing.
    function harvest() external {
        uint256 amount = reward.balanceOf(address(this));
        require(reward.approve(address(router), amount), "approve failed");
        address[] memory path = new address[](2);
        path[0] = address(reward);
        path[1] = address(asset);
        // A minimum of 0 accepts any price, and a deadline of
        // block.timestamp passes in whatever block this lands.
        router.swapExactTokensForTokens(amount, 0, path, address(this), block.timestamp);
    }
}

An attacker wraps the call in one transaction: sell the asset into the pool, call harvest, buy the asset back. They choose the moment, and the vault's whole reward balance is sold at the price they set.

How do you fix it?

Take the minimum from outside the transaction, and check it against a price that is expensive to move. In this version only a keeper can harvest, the keeper passes a minimum and a deadline computed off-chain, and the contract refuses any minimum more than 1% below a reference price.

Fixed: a keeper's minimum, checked against a reference price (illustrative, not audited code) GuardedHarvestVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
}

interface IRouter {
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

// A price source that one transaction can't move, such as a time-weighted
// average over a deep pool or an aggregated feed.
interface IPriceOracle {
    function quote(address tokenIn, address tokenOut, uint256 amountIn) external view returns (uint256);
}

contract GuardedHarvestVault {
    IERC20 public immutable reward;
    IERC20 public immutable asset;
    IRouter public immutable router;
    IPriceOracle public immutable oracle;
    address public immutable keeper;
    uint256 public constant MAX_SLIPPAGE_BPS = 100; // 1%

    constructor(IERC20 reward_, IERC20 asset_, IRouter router_, IPriceOracle oracle_, address keeper_) {
        reward = reward_;
        asset = asset_;
        router = router_;
        oracle = oracle_;
        keeper = keeper_;
    }

    function harvest(uint256 minOut, uint256 deadline) external {
        require(msg.sender == keeper, "not keeper");
        uint256 amount = reward.balanceOf(address(this));
        // Even the keeper can't accept a fill far below the reference price.
        uint256 fair = oracle.quote(address(reward), address(asset), amount);
        require(minOut >= (fair * (10_000 - MAX_SLIPPAGE_BPS)) / 10_000, "minOut too low");
        require(reward.approve(address(router), amount), "approve failed");
        address[] memory path = new address[](2);
        path[0] = address(reward);
        path[1] = address(asset);
        router.swapExactTokensForTokens(amount, minOut, path, address(this), deadline);
    }
}
  • Never compute the minimum from the pool you are about to trade in. A minimum derived inside the same call from the pool's current reserves follows the attacker's price, so it limits nothing.
  • Check the caller's minimum against a reference price that one block can't move. The oracle price manipulation page covers how to choose one.
  • Pass a real deadline. block.timestamp as the deadline always passes, so a transaction held back for later still executes.
  • Make large protocol swaps smaller and less predictable. Splitting a harvest into several trades, or settling many orders at one price in a batch, reduces what a single sandwich can take.
  • Don't rely on `tx.origin` to stop atomic sandwiches. EIP-7702 lists breaking 'atomic sandwich protections which rely on tx.origin' among its security considerations.

How has a sandwich attack hit a real swap?

Protocol Ethereum Foundation ETH sale
Date 9 October 2023
Chain Ethereum
Loss about $9.1K on a sale of 1,700 ETH
What happened On 9 October 2023 the Ethereum Foundation sold 1,700 ETH for USDC through Uniswap's UniversalRouter. EigenPhi traced a sandwich around the swap: the bot took a 7,300 WETH flash loan from Balancer, borrowed 1,632 WETH on Aave and sold it for about 2.64 million USDC on Uniswap V3, raising USDC's price by about 0.46%. The Foundation's swap then filled at that price for 2,738,345 USDC, and the bot unwound its position in the back run. EigenPhi puts the Foundation's loss at about $9.1K and the bot's profit, after a 3.0945 ETH builder fee and gas, at $4,060.
Sources EigenPhi

The move was under half a percent, and it still paid for a flash loan, a builder fee and gas. The larger the swap and the looser its limit, the more room a bot has, which is why a treasury or vault selling in size needs a minimum taken from outside the transaction.

What should a reviewer check?

  • Find every swap the protocol makes on its own account: harvests, rebalances, liquidations, fee conversions, buybacks, zaps.
  • For each, where does the minimum output come from? Zero, a constant, the pool's current price, or a value from outside the transaction?
  • Who can trigger each swap, and can they choose its timing and size?
  • Is the deadline a real time limit, or block.timestamp?
  • Is the minimum checked against a price that one transaction can't move?
  • For user-facing routers, does the front end compute the minimum from a fresh quote, and does the contract refuse a minimum of zero?
  • Is there a test that moves the pool price before the protocol's swap and restores it after, and expects a revert?

How does QuillShield check for sandwich attacks?

Whether a swap can be sandwiched depends on where its limits come from, and that is often several calls away from the swap itself. QuillShield runs a full audit of a Solidity codebase in a Foundry project, builds a security graph of the code and lists the invariants it must keep. A separate reviewer agent then tries to disprove every finding, and each one that survives arrives with the exact lines, the impact, a recommended fix and, on a full audit, a proof of concept.

If your protocol trusts a particular keeper, oracle or price window, say so in the context you can add before an audit, alongside the whitepaper, privileged roles and previous audit reports. Once the audit is done, QuillShield checks every pull request on GitHub or GitLab.com against the same security graph, so a new harvest or rebalance path is reviewed before it merges.

Run a full audit on the code that trades for your protocol: vaults, routers, keepers and liquidation paths. Sign-up is free. New accounts get $50 in credit, good for up to half of an order. The credit expires after six months.

FAQ

What is the difference between front running and a sandwich attack?

Front running is trading ahead of a transaction. A sandwich adds a second trade straight after it, so the attacker profits from the price move the victim's own trade causes and ends close to where they started. See front running.

Does a swap deadline stop a sandwich attack?

No. A deadline limits how long a transaction can wait, which stops it being held and filled later at a stale price. The minimum output is what limits a sandwich.

What slippage tolerance should a protocol use?

There is no universal number. Set the limit from a fresh quote and the depth of the pool, and keep it as tight as the trade allows, because the attacker can take up to the gap between the quote and the minimum.

Can a contract tell that it is being sandwiched?

Not from inside one call. It can refuse fills that differ from a reference price by more than a set amount, which caps what an attacker can take.

Is a sandwich attack in the SWC Registry?

Not by name. SWC-114, Transaction Order Dependence, covers code whose result depends on the order of transactions, which is the class a sandwich belongs to.

Sources

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts