Front-running · blockchain

On this page 7

Front-running on a blockchain is the practice of observing a pending transaction before it is confirmed and getting a competing transaction included ahead of it, so that the attacker profits from the price movement or state change the victim’s transaction is about to cause. In the field of Crypto & blockchain, it is one of the best-known threats to smart contracts, because public transaction pools and fee-based ordering make the intentions of every user visible before execution.

The term comes from traditional finance, where a broker trading ahead of a client order is committing a regulated offense. On public chains the situation differs: no intermediary is involved, the information is openly broadcast, and the reordering is often carried out by automated bots, searchers and block builders. Front-running is the most common form of maximal extractable value (MEV), but it is not the only one.

How front-running exploits the transaction pool

Front-running works because a signed transaction is usually visible in the mempool before a block producer includes it. Nodes relay pending transactions to each other, and anyone running a node or subscribing to a mempool feed can read the target contract, the function being called and its arguments in near real time.

The attacker then submits a transaction that reaches the same contract first. On Ethereum and other EVM chains, ordering inside a block is chosen by the block builder, who generally sorts by the priority fee paid per unit of gas or by private payments. A bot that outbids the victim’s fee therefore lands earlier in the block, a pattern often called a priority gas auction.

The sequence below shows the typical lifecycle of a front-running attempt and where each step depends on public information.

StageWhat happensInformation used
DetectionA bot scans pending transactions for profitable targetsCalldata and target address
SimulationThe bot simulates the victim’s effect on contract stateCurrent state and decoded arguments
SubmissionThe attacker sends a copy or counter-trade with a higher feeVictim’s gas price or tip
InclusionThe builder orders the attacker first in the blockFee ranking or private bid
SettlementThe attacker captures the price or state advantageFinal block ordering
Stages of a typical front-running attack

Variants of front-running in smart contracts

Front-running is a family of transaction-ordering attacks, and researchers usually distinguish three classic variants by what the attacker does with the victim’s slot. The variant determines whether the victim’s transaction still succeeds and how much value is lost.

VariantAttacker actionEffect on victim
DisplacementExecutes the same opportunity firstVictim’s transaction fails or becomes worthless
InsertionTrades before the victim and benefits from the price moveVictim executes at a worse price
SuppressionFloods blocks to delay the victimVictim misses a deadline or auction
Sandwich attackBuys before and sells after the victimVictim absorbs maximum allowed slippage
Generalized front-runningCopies any profitable calldata and replaces the recipientVictim loses the whole opportunity
Main forms of front-running and their effect on the victim

The sandwich attack is the most frequent pattern on decentralized exchanges. The bot buys the asset just before a large swap, which raises the price, lets the victim buy at the inflated rate, and then sells immediately afterward. The profit is bounded by the victim’s slippage tolerance, which is why loose slippage settings attract bots.

Generalized front-runners do not need to understand a contract at all. They simulate any pending transaction, replace the beneficiary address with their own and submit it if the simulation shows a profit. This makes unprotected bounty claims, liquidation calls and arbitrage transactions especially exposed.

Front-running is often confused with neighboring terms in the Smart contracts topic, yet each describes a different layer of the problem. MEV is the broader economic measure, while front-running is a specific ordering technique used to capture part of it.

ConceptCore ideaRelation to front-running
MEVValue obtainable by ordering, inserting or excluding transactionsFront-running is one way to extract it
Back-runningPlacing a transaction right after a targetUsually arbitrage that restores prices, less harmful
Reentrancy attackRecursive calls during contract executionA code flaw, not an ordering problem
Broker front-runningTrading ahead of client orders in marketsIllegal insider misuse with an intermediary
Oracle manipulationDistorting a price feed used by a contractSometimes combined with ordering attacks
How front-running relates to similar terms

A key distinction is that on-chain front-running exploits public information plus ordering power, not confidential data. Whether a particular case is merely competitive or abusive is still legally unsettled in most jurisdictions, and courts have treated a few large exploits as fraud mainly when deception was involved.

Defending contracts and users against front-running

No single control removes front-running, so protection combines contract design, transaction routing and user settings. The guiding principle is to make a pending transaction either unreadable or unprofitable to copy before it is final.

CountermeasureHow it helpsTrade-off
Commit-reveal schemeHides the action until a later reveal transactionTwo transactions and extra latency
Tight slippage limitsCaps how much a sandwich can extractMore failed swaps in volatile markets
Private order flowSends transactions directly to buildersTrust in the relay or builder
Batch auctionsSettles orders at one uniform priceDelayed execution and new complexity
Sender-bound logicTies rewards to msg.sender or signaturesMust be designed in from the start
Encrypted mempoolsKeeps transaction content secret until orderingStill experimental on most networks
Common countermeasures and their trade-offs

Developers should ask during design and during a smart contract audit whether any function produces value for whoever calls it first. Minimum output parameters, deadlines on swaps and access control on sensitive actions remove most simple opportunities. A commit-reveal pattern remains the standard fix for auctions, games and name registrations.

Users reduce exposure by setting slippage tolerance below 1 percent for liquid pairs, splitting very large trades and using wallets or RPC endpoints that route through private channels. These measures lower risk, but they shift trust to a relay operator rather than eliminating it.

Limitations and common misconceptions

Several widespread assumptions about front-running are wrong or only partly true, and they lead to weak protection. Understanding them matters for anyone writing or reviewing contracts that handle valuable state changes.

  • Private transactions are not fully safe: a dishonest builder or relay can still exploit the order it receives.
  • Layer 2 networks are not immune: a centralized sequencer usually uses first-come ordering, which changes the attack into a latency race.
  • Higher gas fees do not protect a victim: bots simply bid more as long as the trade stays profitable.
  • Front-running is not always a code bug: a contract can be perfectly correct and still leak value through ordering.
  • Back-running is not front-running: arbitrage after a trade usually does not worsen the victim’s price.

Measuring front-running losses is also difficult. Estimates depend on how researchers classify transactions, and published totals vary widely, so figures should be treated as orders of magnitude rather than precise amounts.

Stripped to the essentials

Imagine announcing in a crowded room that you are about to buy every apple at a market stall. Someone who hears you runs ahead, buys the apples first and sells them back to you at a higher price. That is front-running in essence.

On a public blockchain, every transaction waits in an open queue before it is confirmed, so anyone can read what you are about to do. Automated programs watch that queue and pay a little more to jump ahead of you. The key takeaway is that visibility plus the ability to pay for a better position creates the risk, and good contract design and careful trade settings are the main defenses.

Where it is applied

A treasury manager at a small decentralized project needs to swap the equivalent of 400,000 dollars of a stablecoin for the project’s governance token on an automated market maker. The pool is relatively shallow, and the wallet’s default slippage tolerance is 3 percent.

Within seconds of broadcasting, a bot detects the swap in the public mempool, buys the token with a higher priority fee, lets the treasury trade execute at a worse rate and sells immediately afterward. The treasury receives about 2.7 percent fewer tokens than quoted, a loss of roughly 11,000 dollars.

After the incident, the team adopts a new procedure: large swaps are split into smaller tranches, slippage is limited to 0.5 percent and transactions go through a private order flow endpoint. Later trades of similar size settle within the quoted range, and no further sandwich attacks are detected in their transaction history.