Front-running is a consensus-layer vulnerability where attackers observe pending transactions (sandwich attacks), execute profitable transactions before/after the victim's transaction, and extract MEV (Maximal Extractable Value). Sandwich attacks on DEX swaps, liquidations, and arbitrage have cost DeFi hundreds of millions annually. Firepan's HOUND AI detects front-running vulnerabilities automatically during development and post-deployment monitoring, covering continuous analysis across the full contract lifecycle.
Front-running occurs in public mempool environments where transactions are visible before inclusion in blocks. An attacker observing a pending user transaction can:
Unlike smart contract vulnerabilities, front-running exploits the consensus layer, not code logic. However, contract design can mitigate or enable front-running risk.
Front-running follows a predictable attack sequence:
// VULNERABLE — example only
// Demonstrates: Front-Running
// Do NOT use in production
pragma solidity ^0.8.0;
contract VulnerableDEX {
// VULNERABLE: No slippage protection
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn
) public returns (uint256 amountOut) {
// No minimum output validation
uint256 outputPrice = getSpotPrice(tokenOut) / getSpotPrice(tokenIn);
amountOut = (amountIn * outputPrice) / 1e18;
// VULNERABLE: Attacker can front-run this swap
// Buy tokenOut before swap, execute swap, sell at higher price
return amountOut;
}
// VULNERABLE: Liquidation with no slippage control
function liquidate(address borrower) public returns (uint256 profit) {
uint256 collateralAmount = borrowers[borrower].collateral;
uint256 currentPrice = oracle.getPrice();
// No check on minimum liquidation bonus
// Attacker front-runs: buys collateral, drives price up, liquidates at higher price
uint256 liquidationBonus = (collateralAmount * 110) / 100;
_transferCollateral(msg.sender, liquidationBonus);
return liquidationBonus - collateralAmount;
}
}
contract FrontRunner {
address public dex;
address public token0;
address public token1;
function sandwichSwap(
uint256 victimAmount,
uint256 minOutput // Victim's slippage tolerance
) public {
// STEP 1: Front-run — buy token1 before victim
IDex(dex).swap(token1, token0, victimAmount / 2);
// Price of token0 increases, victim receives less
// This tx will be included before victim's in the block
// STEP 2: Victim's transaction executes (in mempool)
// Victim's swap receives worse price due to attacker's purchase
// STEP 3: Back-run — sell token0 after victim
uint256 profit = IDex(dex).swap(token0, token1, victimAmount / 2);
// Attacker profits from price movement
}
function frontRunLiquidation(address borrower) public {
// STEP 1: Buy collateral token before liquidation
uint256 buyAmount = 1000 ether;
IDex(dex).swap(USDC, collateralToken, buyAmount);
// Collateral price increases slightly
// STEP 2: Liquidation happens (victim's tx)
// Collateral liquidation bonus is now higher
// STEP 3: Sell collateral at new higher price
// Extract arbitrage profit
}
}
| Protocol | Date | Loss | Root Cause | |----------|------|------|-----------| | Generalized MEV | Ongoing | $500M+/year | Sandwich attacks on DEX swaps, liquidations, arbitrage | | OpenSea | 2021 | Hundreds of thousands | Employee front-running NFT listings before public sale | | Uniswap V2 (MEV) | Ongoing | Significant MEV extraction | Slippage tolerance > 1% enables sandwich attacks (not a protocol exploit) |
Detection focuses on price/slippage dependencies and mempool exposure:
Red flags:
Firepan's HOUND AI performs consensus-layer vulnerability analysis:
Firepan's HOUND AI engine identifies front-running vulnerabilities across all monitored contracts.
1. Implement Slippage Protection on Swaps
Always enforce minimum output amount:
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut // Slippage protection
) public returns (uint256 amountOut) {
amountOut = _calculateSwapOutput(tokenIn, tokenOut, amountIn);
// Enforce minimum output
require(amountOut >= minAmountOut, "Insufficient output amount");
_executeSwap(tokenIn, tokenOut, amountIn, amountOut);
return amountOut;
}
2. Use Private Mempool/Encrypted Transactions
Submit transactions through encrypted mempool providers:
// Use MEV-Protect or similar to encrypt transaction visibility
// Prevents frontrunners from seeing transaction details pre-execution
3. Implement MEV-Resistant Ordering
For liquidations, use commit-reveal or auction mechanisms:
// Commit-reveal for liquidations
function commitLiquidation(address borrower, bytes32 commitment) public {
require(liquidationCommits[borrower].timestamp == 0);
liquidationCommits[borrower] = Commitment(commitment, block.timestamp);
}
function revealLiquidation(address borrower, uint256 nonce) public {
require(
keccak256(abi.encode(borrower, nonce)) == liquidationCommits[borrower].commitment,
"Invalid reveal"
);
// Execute liquidation
}
4. Use Order Flow Auctions (OFA)
For high-value transactions, run sealed-bid auction:
function auctionLiquidation(address borrower) public {
// Open bidding phase
auctionActive = true;
auctionDeadline = block.timestamp + 1 minutes;
// Sealed bids — liquidators bid for right to liquidate
// Highest bidder executes liquidation
}
5. Use Threshold Encryption or Time-Locked Puzzles
Delay transaction execution to reduce frontrunning window:
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract TimeLockedSwap {
mapping(bytes32 => TimeLock) public locks;
function timeLockedSwap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOutput,
uint256 delay
) public returns (bytes32 lockId) {
lockId = keccak256(
abi.encode(msg.sender, tokenIn, tokenOut, amountIn, block.timestamp)
);
locks[lockId] = TimeLock({
readyTime: block.timestamp + delay,
user: msg.sender,
tokenIn: tokenIn,
tokenOut: tokenOut,
amountIn: amountIn,
minOutput: minOutput
});
return lockId;
}
function executeTimeLockedSwap(bytes32 lockId) public {
TimeLock memory lock = locks[lockId];
require(block.timestamp >= lock.readyTime, "Not ready yet");
// Execute swap, less vulnerable to frontrunning
_executeSwap(lock.tokenIn, lock.tokenOut, lock.amountIn, lock.minOutput);
}
}
Q: What is front-running in smart contracts?
A: Front-running exploits public mempool visibility by intercepting pending transactions. Attackers submit profitable transactions before/after victims (sandwich attacks), extracting MEV. Unlike code bugs, front-running is a consensus-layer vulnerability, not a smart contract logic error.
Q: Which protocols have been exploited via front-running?
A: All major DEX platforms (Uniswap, SushiSwap, etc.) suffer ongoing sandwich attacks. Liquidation engines on Compound, Aave, and Curve are regularly front-run. OpenSea faced insider NFT listing front-runs. Aggregate MEV extraction exceeds $500M+ annually across DeFi.
Q: How does Firepan detect front-running?
A: Firepan simulates transaction execution under different orderings, calculates MEV extraction feasibility, validates slippage protection on all swaps, and identifies liquidation/arbitrage opportunities vulnerable to frontrunning. It detects ordering-dependent logic vulnerable to mempool attacks.
Q: Can front-running be exploited after deployment?
A: Yes, front-running is exploitable immediately post-deployment. Attackers constantly scan mempool for sandwichable transactions. Any swap without slippage protection or liquidation without output bounds is immediately targeted by MEV extractors.
Q: How do I prevent front-running?
A: Enforce minimum output on all swaps. Use encrypted mempool (MEV-Protect, Flashbots Protect). Implement time-locked execution delays. Use commit-reveal for liquidations. Auction liquidation rights to highest bidder. Aggregate multiple execution paths to reduce single-point MEV.
Front-running extracts $500M+ annually from DeFi, making it the largest-impact vulnerability class by aggregate losses. Front-running is consensus-layer based, not code-based—but contract design can mitigate or enable it. Slippage protection, encrypted mempools, and time-locked execution significantly reduce frontrunning risk. Firepan's HOUND AI identifies unprotected swaps and vulnerable liquidation mechanics across all monitored contracts.
Start securing your smart contracts at https://app.firepan.com/
Firepan
Run a free surface scan — results in minutes, no credit card required.
Run Free Scan →Firepan monitors smart contracts on Ethereum using HOUND AI. Detect reentrancy, flash loan attacks, and 20+ vulnerability classes. Start scanning at app.firepan.com.
Firepan monitors smart contracts on Arbitrum using HOUND AI. Detect reentrancy, flash loan attacks, and 20+ vulnerability classes. Start scanning at app.firepan.com.
Learn how denial of service (dos) works, see real DeFi exploits, and detect it automatically with Firepan HOUND AI across all monitored contracts. Automated ...
Learn how integer overflow & underflow works, see real DeFi exploits, and detect it automatically with Firepan HOUND AI across all monitored contracts.
Learn how business logic error works, see real DeFi exploits, and detect it automatically with Firepan HOUND AI across all monitored contracts. Automated det...