Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article introduces front-running.

Front-running originated as a term in traditional finance, where certain forms of the practice are prohibited. Related transaction-ordering risks also arise on blockchains.

Understanding those risks helps developers recognize vulnerable contract designs. This topic is useful for Solidity developers and researchers interested in bug bounties.

If you are unfamiliar with bug bounties, start here.

[Solidity-Bug Bounty] A Beginner's Guide to Bug Bounties

What is front-running?

Overview of front-running

First, consider the definition.

Definition of front-running

Front-running originally comes from finance. Daiwa Securities' glossary describes the practice as a financial intermediary or its staff trading for their own benefit ahead of a customer's order, using knowledge of that order. Its glossary describes this conduct as prohibited under Japanese financial instruments legislation.

In short, the intermediary uses advance knowledge of a customer's order to obtain a more favorable trade for itself.

Front-running on blockchains

A similar concept appears in blockchain systems.

The referenced explanation describes front-running in Ethereum DeFi as exploiting information about transactions before their execution to obtain an advantage from transaction ordering. It also discusses the difficulty of preventing such behavior in DeFi and mentions Flashbots auctions as an approach to addressing some MEV-related problems, including gas-price competition.

https://bokujyuumai-salon.ethereum-japan.net/wiki/12942

The basic idea resembles the traditional financial definition, although the actors and infrastructure differ.

Front-running

  • Trading ahead of a large order to benefit from the resulting price movement.
  • Displacing or impersonating an intended order.
  • Taking advantage of a disclosed price by trading before the intended counterparty.

In blockchain applications, front-running is often discussed in relation to a mempool, where pending transactions may be held before inclusion in a block.

Transactions can enter the mempool after submission. A higher fee may influence inclusion priority, somewhat like a priority pass, but transactions are not guaranteed to follow arrival order or fee order.

Publicly propagated pending transactions may be observable and analyzed by other participants. Private transaction submission and centralized exchanges have different visibility properties.

A contract that assumes a submitted transaction will execute before competing transactions may therefore be vulnerable to reordering.

Front-running example

Illustration of transaction-ordering risks

The following historical example illustrates a vulnerable Solidity contract. The original article does not execute an actual front-running transaction.

The intended reward is 10 ether for providing a word that matches a known hash.

Code

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract FrontRunning {
    // 正解のハッシュ値。「FrontRunning」と言うワードののハッシュ値。
    bytes32 public constant correctHash = 
        0x5709c8a5dc80ea146197585ab442e5d6ba516723a937be5975b4998afc42ae0f;

    /// @notice ハッシュ値が一致していれば10 etherを送金する。
    function verify(string memory word) public {
        require(correctHash == keccak256(abi.encodePacked(word)), "Incorrect answer");

        (bool sent, ) = msg.sender.call{value: 10 ether}("");
        require(sent, "Failed to send Ether");
    }
}

Code walkthrough

The answer is revealed in the call to verify. If that call is publicly observable before inclusion, a competing transaction may use the same answer.

The contract does not bind the answer to a particular claimant, so the reward may go to a different caller if the execution order changes. Offering a higher fee can influence ordering, but it does not guarantee priority.

Mitigation

One approach is to design the contract so that public visibility of the revealed value does not let another account claim the same reward.

The example introduces a commit-reveal pattern. A participant first records a hash bound to their address, answer, and secret, then reveals the answer and secret in a separate transaction.

The original code is reproduced unchanged below for comparison. It contains an inverted answer check and other limitations discussed after the example; it should not be used as production-ready mitigation.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

import "@openzeppelin/contracts/utils/Strings.sol";

contract FrontRunning {
    // 正解のハッシュ値。「FrontRunning」と言うワードののハッシュ値。
    bytes32 public constant correctHash = 
        0x5709c8a5dc80ea146197585ab442e5d6ba516723a937be5975b4998afc42ae0f;

    // 正解者が出たかどうかのチェック
    bool public ended;

    struct Commit {
        bytes32 solutionHash; // ユーザーから送信してもらうハッシュ値
        uint commitTime; // commitSolutionを実行した時間
    }

    // Mapping to store the commit details with address
    mapping(address => Commit) commits;

    // 正解者が出たかどうかの修飾子
    modifier gameActive() {
        require(!ended, "Already ended");
        _;
    }

    /// @notice _solutionHashを渡して、値をそれぞれ格納する。
    ///         _solutionHash = msg.sender + solution + secret
    ///         例) 0x5B38Da... + 0x5709c8a... + "password"
    function commitSolution(bytes32 _solutionHash) public gameActive {
        Commit storage commit = commits[msg.sender];
        // 特定のユーザーが初めてcommitSolution関数を実行したかチェック
        require(commit.commitTime == 0, "Already committed");
        commit.solutionHash = _solutionHash;
        commit.commitTime = block.timestamp;
    }

    /// @notice ハッシュ値が一致していれば10 etherを送金する。
    function verify(string memory _word, string memory _secret) public gameActive {
        Commit storage commit = commits[msg.sender];
        // commitSolutionが実行されているかチェック
        require(commit.commitTime != 0, "Not committed yet");

        // solutionHashを求めて検証
        bytes32 solutionHash = keccak256(
            abi.encodePacked(Strings.toHexString(msg.sender), _word, _secret)
        );
        require(solutionHash == commit.solutionHash, "Hash doesn't match");

        // 正解のハッシュ値の検証
        require(keccak256(abi.encodePacked(_word)) != correctHash, "Incorrect answer");

        ended = true;

        (bool sent, ) = payable(msg.sender).call{value: 10 ether}("");
        if (!sent) {
            ended = false;
            revert("Failed to send ether.");
        }
    }
}

The intended sequence is as follows.

Intended sequence in the original example

  • User A calls commitSolution with the illustrated hash 4cfa68971ac40874fa207124a57d5e43d8ec216dc2302bbd68da6392e1f92972, associated with the string 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4FrontRunningpassword.
    • The commitment is intended to bind the sender's address, the answer, and an arbitrary secret.
  • The contract stores the supplied commitment and timestamp in the commit structure.
  • A competing transaction could record a commitment before User A's transaction.
  • User A subsequently calls verify with the answer (FrontRunning) and the secret used for the commitment.
  • A competing reveal could also be ordered earlier.
  • A competing caller with a recorded commitment passes the existence check.
  • However, its msg.sender differs from User A's address, so simply copying User A's commitment and reveal does not satisfy the address-bound hash comparison.
  • The intended outcome is that User A can claim the reward while a copied reveal fails.

The original code has important limitations. Its require condition compares the answer hash with correctHash using inequality, so a correct answer fails the check. The example also does not enforce a separate commitment window or minimum delay, does not demonstrate how the contract obtains the reward balance, and uses packed encoding of adjacent dynamic strings. The literal hash and address formatting in the walkthrough are preserved from the original and have not been independently reproduced.

A production implementation must address those issues, use unambiguous encoding, and ensure commitments are established before answers are revealed. The address binding alone is not a complete defense.

The original implementation was based on the following article.

Conclusion

Summary of front-running and commit-reveal

This article introduced front-running and an illustrative commit-reveal design.

Key points

  • Understand what front-running means.
  • Recognize a contract design exposed to transaction-ordering risks.
  • Understand the intended mitigation and its limitations.

The central lesson is to avoid relying on transaction secrecy or a particular execution order for contract correctness.

I regularly write about Solidity, blockchain, and Web3, and share interesting articles on Twitter.

References

https://phemex.com/ja/academy/フロントランニングとは何かそして暗号通貨の注文はどのようにして選択されるのか