# Front running in smart contracts: how it works and how to prevent it

URL: https://shield.quillaudits.com/learn/vulnerabilities/front-running/

Front running is when someone sees a transaction waiting to be included in a block and gets their own transaction executed first, so they profit from what yours was about to do. In a smart contract it becomes a vulnerability when the result of a call depends on transaction order and the contract lets whoever arrives first win: a bounty for a public answer, an initializer anyone can call, a first deposit or a trade with no price limit. Design so the order of two transactions can't change who gets paid: commit before you reveal, bind each action to its sender, and let users set their own limits.

Last updated 3 December 2026. 6 minute read. By the QuillAudits Team.

## How does front running work?

On most chains a transaction is visible before it is in a block, and whoever builds the block decides the order. The SWC Registry calls the resulting bug transaction order dependence: ["A race condition vulnerability occurs when code depends on the order of the transactions submitted to it."](https://swcregistry.io/docs/SWC-114/)

A front runner watches pending transactions for one worth racing, then sends its own with a higher fee, or directly to a block builder, so it lands first. Automated bots can do this for any call whose calldata they can copy and profit from, so the attacker doesn't need to understand your protocol; [Paradigm's account](https://www.paradigm.xyz/writing/ethereum-is-a-dark-forest) of losing a rescue to one is below.

It takes four forms:

- **Copying.** The attacker submits your call with their own address, ahead of yours. Bounties for a correct answer and claims that pay the first caller are the usual targets.
- **Displacing.** The attacker takes something only one caller can have: the first call to `initialize`, a pool's opening price, a unique name or the first deposit into a vault. The [ERC-4626 inflation attack](https://shield.quillaudits.com/learn/vulnerabilities/erc4626-inflation-attack/) is a displacing attack on a vault's first deposit.
- **Inserting.** The attacker trades before and after you. On a swap this is a [sandwich attack](https://shield.quillaudits.com/learn/vulnerabilities/sandwich-attack/).
- **Suppressing.** The attacker delays your transaction until a deadline or an auction end has passed.

## What does vulnerable code look like?

This contract pays its balance to the first caller who submits text that hashes to a stored value. The answer travels in the clear in the pending transaction.

**Vulnerable: the answer is visible before it is mined (illustrative, not audited code)** `HashBounty.sol`

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

contract HashBounty {
    bytes32 public immutable answerHash;
    bool public solved;

    constructor(bytes32 answerHash_) payable {
        answerHash = answerHash_;
    }

    // Anyone who sees this call pending can copy the answer
    // and get it mined first with a higher fee.
    function solve(string calldata answer) external {
        require(!solved, "already solved");
        require(keccak256(bytes(answer)) == answerHash, "wrong answer");
        solved = true;
        (bool ok, ) = msg.sender.call{value: address(this).balance}("");
        require(ok, "payment failed");
    }
}
```

A bot copies the calldata, pays a higher priority fee and collects the bounty. The honest solver's transaction is mined next and reverts with `already solved`.

## How do you fix it?

Split the action in two. The solver first commits a hash of the answer, their own address and a secret salt. Only after the commitment is at least a few blocks old can they reveal the answer, and the contract checks the reveal against the commitment made by that same address.

**Fixed: commit, wait, then reveal (illustrative, not audited code)** `CommitRevealBounty.sol`

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

contract CommitRevealBounty {
    bytes32 public immutable answerHash;
    uint256 public constant REVEAL_DELAY = 5; // blocks
    bool public solved;
    mapping(address => bytes32) public commitments;
    mapping(address => uint256) public committedAt;

    constructor(bytes32 answerHash_) payable {
        answerHash = answerHash_;
    }

    // Step 1: publish keccak256(abi.encode(answer, sender, salt)).
    // A copier learns nothing it can use, because the hash names the sender.
    function commit(bytes32 commitment) external {
        commitments[msg.sender] = commitment;
        committedAt[msg.sender] = block.number;
    }

    // Step 2: reveal after the delay. A copier who sees this call can't
    // have committed early enough, because they only learn the answer now.
    function reveal(string calldata answer, bytes32 salt) external {
        require(!solved, "already solved");
        uint256 at = committedAt[msg.sender];
        require(at != 0, "no commitment");
        require(block.number >= at + REVEAL_DELAY, "too early");
        require(keccak256(abi.encode(answer, msg.sender, salt)) == commitments[msg.sender], "bad reveal");
        require(keccak256(bytes(answer)) == answerHash, "wrong answer");
        solved = true;
        (bool ok, ) = msg.sender.call{value: address(this).balance}("");
        require(ok, "payment failed");
    }
}
```

The delay is what makes it work. Without it, a copier who sees the reveal could commit and reveal in one transaction of their own, placed ahead of yours.

- **Bind actions to their sender.** If a reward, a claim or an order is meant for one address, check `msg.sender` or a signature that names it.
- **Let the user set the limits.** A minimum output, a maximum price and a deadline chosen when the user signed turn an inserted trade into a failed transaction instead of a loss.
- **Leave no gap between deployment and setup.** A contract deployed in one transaction and initialized in another can be initialized by someone else in between. See [uninitialized proxy](https://shield.quillaudits.com/learn/vulnerabilities/uninitialized-proxy/).
- **Treat private submission as a user-side measure.** Sending a transaction straight to a block builder hides it from public bots, but a contract that is only safe when users do that still has the bug.

## How has front running cost real money?

| Protocol | Paradigm's Uniswap rescue attempt |
| --- | --- |
| Date | 28 August 2020 |
| Chain | Ethereum |
| Loss | Uniswap liquidity tokens worth around $12,000 |
| What happened | In a post published on 28 August 2020, Paradigm's Dan Robinson and Georgios Konstantopoulos describe trying to recover Uniswap liquidity tokens worth around $12,000 that someone had sent to the pair contract by mistake. Anyone could claim them by calling the pair's burn function, so the authors split their rescue into two transactions to hide that call. The second transaction was delayed into a later block, a generalized frontrunner took the tokens first, and their own call failed. |
| Sources | [Paradigm](https://www.paradigm.xyz/writing/ethereum-is-a-dark-forest) |

Nothing in the pair contract was broken: anyone was allowed to call burn, and the first caller won. The authors describe generalized frontrunners as bots that look for any transaction they could profitably frontrun by copying it, which is why the copying form above needs no understanding of your protocol. The date shown is the post's publication date; the post places the rescue on a Wednesday without giving the date.

## What should a reviewer check?

- Which functions reward whoever calls first? List them.
- Does any call carry a secret in plain calldata: an answer, a sealed bid, an order price?
- Is there a gap between deployment and `initialize`, a pool's first price or a vault's first deposit that another account could use?
- Do swaps, mints and redemptions take a minimum output and a deadline from the caller, rather than a value computed on-chain during execution?
- Do signed messages name the address allowed to use them?
- For ERC-20 allowance changes, does the front end set the allowance to zero first, or does the token offer functions that adjust it relative to its current value?
- Is there a test in which a second account sends the same calldata first?

## Which SWC entry covers front running?

[SWC-114, Transaction Order Dependence](https://swcregistry.io/docs/SWC-114/). Its two examples are a reward for solving a puzzle, where a node operator copies the answer and outbids the solver, and the ERC-20 approve race. Its fixes are a commit-reveal scheme and an approve function that takes the expected current allowance. The [registry](https://swcregistry.io/) says it has not been thoroughly updated since 2020, so use it as a naming reference rather than a complete list.

## How does QuillShield check for front running?

Front running is a property of order, not of any one line, so it shows up when a reviewer walks each external function and asks what changes if another caller gets there first. A QuillShield full audit covers the Solidity codebase in your Foundry project: it builds a security graph of the code, lists the invariants the code must keep, and has a separate reviewer agent try to disprove each finding before it reaches you. A finding that holds up carries the exact lines, the impact and a recommended fix, plus a proof of concept on full audits.

Ordering bugs tend to arrive with new features, such as a new claim function or one more deployment step. QuillShield checks every pull request on GitHub or GitLab.com against the audit's security graph, and on GitHub, with branch protection or rulesets, a required QuillShield check blocks the merge while a pull request has a High or Critical finding.

If a launch depends on an initializer or a first deposit going to the right account, [run a full audit](https://shield.quillaudits.com/register) on the deployment code before mainnet. Teams that would rather not run it themselves can [talk to an auditor](https://calendly.com/akshadh-a-quillaudits/30min), and QuillAudits auditors run QuillShield on their code.

## FAQ

### Is front running the same as MEV?

Front running is one way to capture MEV, the value someone can extract by choosing the order of transactions in a block. Back running and sandwiching are others.

### Does sending through a private mempool stop front running?

It hides a transaction from public bots, but the block builder still sees it, and it protects only the users who send that way. A contract that is safe only when its users send privately still has the bug.

### Can a commit-reveal scheme be front-run?

The commitment can be copied, but it's useless to anyone else because it hashes in the committer's address. The reveal must come at least one block after the commitment, or a copier could commit and reveal in a single transaction.

### Can a permit signature be front-run?

Yes. [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) warns that another party can always submit a permit before the intended caller does. The approval still goes to the spender the owner named, so the usual damage is a reverted call in a contract that assumed the permit was unused.

### What is the ERC-20 approve race?

When an owner changes an allowance from N to M, the spender can spend N first and then M once the change lands. SWC-114 suggests an approve that checks the current allowance, and [EIP-20](https://eips.ethereum.org/EIPS/eip-20) asks wallets to set the allowance to zero before setting a new value.

## Sources

- [SWC-114: Transaction Order Dependence, SWC Registry](https://swcregistry.io/docs/SWC-114/) · checked 3 December 2026
- [Smart Contract Weakness Classification Registry, SWC Registry](https://swcregistry.io/) · checked 3 December 2026
- [ERC-2612: Permit Extension for EIP-20 Signed Approvals, Ethereum Improvement Proposals](https://eips.ethereum.org/EIPS/eip-2612) · checked 3 December 2026
- [ERC-20: Token Standard, Ethereum Improvement Proposals](https://eips.ethereum.org/EIPS/eip-20) · checked 3 December 2026
- [Ethereum is a Dark Forest, Paradigm](https://www.paradigm.xyz/writing/ethereum-is-a-dark-forest) · checked 3 December 2026
