Prevent Front Running
Implement commit-reveal, strict slippage bounds, and MEV-resistant submission via Flashbots to prevent front-running, sandwich attacks, and transaction reordering that extracts value from users.
Why This Is Best Practice
Adopted by: OWASP Smart Contract Top 10 SC08 (Front-Running). Flashbots (ethereum.org/en/developers/docs/mev) is the canonical solution for MEV protection, used by Ethereum validators and adopted by Uniswap, Curve, and 1inch for protected routing. Uniswap V3's amountOutMinimum parameter is the standard slippage protection pattern. The Ethereum Foundation's MEV documentation mandates commit-reveal for any outcome dependent on transaction order.
Impact: Flashbots' MEV-Explore dashboard estimates cumulative MEV extracted from Ethereum exceeds $1.5B (2020–2024). Sandwich attacks are the most common user-facing MEV: an attacker sees a large swap in the mempool, buys before it (raising the price), lets the victim's swap execute at a worse price, then sells — consistently extracting value from victims with no capital risk. JaredFromSubway.eth (a prominent MEV bot) extracted $40M in 2023 from sandwich attacks alone. The 2022 Solana NFT mint exploits used front-running bots to win "fair" lotteries.
Why best: Transaction ordering in public mempools is not first-come-first-served — miners/validators can reorder, insert, or censor transactions within a block. Slippage bounds limit the price a swap can accept, making sandwiches unprofitable. Commit-reveal hides transaction intent until the block is sealed. Private mempool submission (Flashbots, MEV Blocker) routes transactions directly to validators, bypassing the public mempool entirely.
Sources: OWASP Smart Contract Top 10 SC08; Flashbots MEV documentation; Ethereum Foundation MEV guide; Uniswap V3 router documentation
Steps
Enforce strict slippage tolerance in AMM swaps:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
contract SlippageProtectedSwap {
ISwapRouter public immutable router;
constructor(address _router) {
router = ISwapRouter(_router);
}
function swapWithProtection(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut, // caller must specify minimum — never 0
uint24 fee
) external returns (uint256 amountOut) {
require(minAmountOut > 0, "Slippage protection required");
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: fee,
recipient: msg.sender,
deadline: block.timestamp + 20 minutes, // also require deadline
amountIn: amountIn,
amountOutMinimum: minAmountOut, // reverts if price moves beyond tolerance
sqrtPriceLimitX96: 0
});
amountOut = router.exactInputSingle(params);
}
}
Implement commit-reveal for order-sensitive operations:
contract CommitRevealAuction {
struct Commitment {
bytes32 hash;
uint256 blockNumber;
}
mapping(address => Commitment) public commitments;
uint256 private constant COMMIT_PERIOD = 20; // blocks
uint256 private constant REVEAL_DEADLINE = 40; // blocks after commit
// Phase 1: Submit hash(bid, salt) — intent hidden from mempool watchers
function commit(bytes32 commitment) external {
commitments[msg.sender] = Commitment({
hash: commitment,
blockNumber: block.number
});
}
// Phase 2: Reveal actual bid after commit period
function reveal(uint256 bid, bytes32 salt) external {
Commitment memory c = commitments[msg.sender];
require(block.number >= c.blockNumber + COMMIT_PERIOD, "Commit period not ended");
require(block.number <= c.blockNumber + REVEAL_DEADLINE, "Reveal deadline passed");
require(
keccak256(abi.encodePacked(bid, salt, msg.sender)) == c.hash,
"Invalid reveal"
);
// Process bid — all bids revealed before winner determined
_processBid(msg.sender, bid);
delete commitments[msg.sender];
}
}
Add deadline parameter to time-sensitive transactions:
function executeOperation(
address asset,
uint256 amount,
uint256 deadline // always require explicit deadline
) external {
require(block.timestamp <= deadline, "Transaction expired");
// Prevents delayed mining of a transaction when market conditions change
}
Use Flashbots for private transaction submission (off-chain):
// ethers.js + Flashbots SDK
import { FlashbotsBundleProvider } from "@flashbots/ethers-provider-bundle";
import { ethers } from "ethers";
const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
const flashbotsProvider = await FlashbotsBundleProvider.create(
provider,
ethers.Wallet.createRandom(), // reputation signer
"https://relay.flashbots.net"
);
const signedBundle = await flashbotsProvider.signBundle([{
signer: wallet,
transaction: {
chainId: 1,
to: CONTRACT_ADDRESS,
data: swapCalldata,
gasLimit: 200000,
maxFeePerGas: ethers.utils.parseUnits("50", "gwei"),
maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei"),
}
}]);
// Submit directly to validators — bypasses public mempool
const bundleSubmission = await flashbotsProvider.sendRawBundle(
signedBundle,
targetBlockNumber
);
For NFT mints: random assignment after reveal:
// Prevent sniper bots from selecting rare traits at mint time
contract AntiSnipeMint {
bool public revealed = false;
uint256 public revealBlock;
uint256 public revealSeed;
function mint(uint256 quantity) external payable {
// Mint token IDs without revealing traits
_mintTokens(msg.sender, quantity);
}
function reveal() external {
require(!revealed && block.number > revealBlock);
// Use future block hash — not known at mint time
revealSeed = uint256(blockhash(revealBlock));
revealed = true;
}
function getTraits(uint256 tokenId) external view returns (uint256) {
require(revealed, "Not yet revealed");
return uint256(keccak256(abi.encodePacked(revealSeed, tokenId))) % NUM_TRAITS;
}
}
Rules
- Never use
amountOutMinimum: 0 in swap calls — this accepts any price including one manipulated by a sandwicher.
- Deadline parameters must be caller-supplied and checked against
block.timestamp — a transaction sitting in the mempool for hours may execute under completely different market conditions.
- Commit-reveal salts must be random and kept secret until reveal — a guessable or reused salt defeats the commitment scheme.
- For large trades, consider using aggregators with MEV protection (CoW Protocol, 1inch Fusion) rather than routing directly through DEXes.
Common Mistakes
deadline: block.timestamp — using the current block's timestamp as the deadline means the transaction never expires, defeating the purpose.
- Small slippage only for large swaps — a 0.5% slippage tolerance on a $1M swap is still $5,000 of extractable value; consider splitting large swaps.
- Commit-reveal without salt —
keccak256(bid) is brute-forceable for small bid spaces; always combine with a large random salt.
- Not testing with a fork that simulates MEV — Foundry supports mainnet fork testing; simulate front-running by having a bot contract observe and front-run your test transaction.
1---2name: prevent-front-running3description: Use when writing DeFi smart contracts with user-submitted transactions — implementing commit-reveal, slippage tolerance, and MEV-resistant patterns to prevent front-running and sandwich attacks.4source: 'OWASP Smart Contract Top 10 SC08 (owasp.org/www-project-smart-contract-top-10/); Ethereum Foundation MEV documentation; Flashbots research; Uniswap slippage documentation'5tags: [security, owasp, solidity, smart-contracts, mev, front-running, defi, ethereum]6metadata:7 source: https://skillmd.com/skills/jeffreytse/prevent-front-running8---910# Prevent Front Running1112Implement commit-reveal, strict slippage bounds, and MEV-resistant submission via Flashbots to prevent front-running, sandwich attacks, and transaction reordering that extracts value from users.1314## Why This Is Best Practice1516**Adopted by:** OWASP Smart Contract Top 10 SC08 (Front-Running). Flashbots (ethereum.org/en/developers/docs/mev) is the canonical solution for MEV protection, used by Ethereum validators and adopted by Uniswap, Curve, and 1inch for protected routing. Uniswap V3's `amountOutMinimum` parameter is the standard slippage protection pattern. The Ethereum Foundation's MEV documentation mandates commit-reveal for any outcome dependent on transaction order.17**Impact:** Flashbots' MEV-Explore dashboard estimates cumulative MEV extracted from Ethereum exceeds $1.5B (2020–2024). Sandwich attacks are the most common user-facing MEV: an attacker sees a large swap in the mempool, buys before it (raising the price), lets the victim's swap execute at a worse price, then sells — consistently extracting value from victims with no capital risk. JaredFromSubway.eth (a prominent MEV bot) extracted $40M in 2023 from sandwich attacks alone. The 2022 Solana NFT mint exploits used front-running bots to win "fair" lotteries.18**Why best:** Transaction ordering in public mempools is not first-come-first-served — miners/validators can reorder, insert, or censor transactions within a block. Slippage bounds limit the price a swap can accept, making sandwiches unprofitable. Commit-reveal hides transaction intent until the block is sealed. Private mempool submission (Flashbots, MEV Blocker) routes transactions directly to validators, bypassing the public mempool entirely.1920Sources: OWASP Smart Contract Top 10 SC08; Flashbots MEV documentation; Ethereum Foundation MEV guide; Uniswap V3 router documentation2122## Steps23241. **Enforce strict slippage tolerance in AMM swaps**:2526 ```solidity27 // SPDX-License-Identifier: MIT28 pragma solidity ^0.8.19;2930 import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";3132 contract SlippageProtectedSwap {33 ISwapRouter public immutable router;3435 constructor(address _router) {36 router = ISwapRouter(_router);37 }3839 function swapWithProtection(40 address tokenIn,41 address tokenOut,42 uint256 amountIn,43 uint256 minAmountOut, // caller must specify minimum — never 044 uint24 fee45 ) external returns (uint256 amountOut) {46 require(minAmountOut > 0, "Slippage protection required");4748 ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({49 tokenIn: tokenIn,50 tokenOut: tokenOut,51 fee: fee,52 recipient: msg.sender,53 deadline: block.timestamp + 20 minutes, // also require deadline54 amountIn: amountIn,55 amountOutMinimum: minAmountOut, // reverts if price moves beyond tolerance56 sqrtPriceLimitX96: 057 });5859 amountOut = router.exactInputSingle(params);60 }61 }62 ```63642. **Implement commit-reveal for order-sensitive operations**:6566 ```solidity67 contract CommitRevealAuction {68 struct Commitment {69 bytes32 hash;70 uint256 blockNumber;71 }7273 mapping(address => Commitment) public commitments;74 uint256 private constant COMMIT_PERIOD = 20; // blocks75 uint256 private constant REVEAL_DEADLINE = 40; // blocks after commit7677 // Phase 1: Submit hash(bid, salt) — intent hidden from mempool watchers78 function commit(bytes32 commitment) external {79 commitments[msg.sender] = Commitment({80 hash: commitment,81 blockNumber: block.number82 });83 }8485 // Phase 2: Reveal actual bid after commit period86 function reveal(uint256 bid, bytes32 salt) external {87 Commitment memory c = commitments[msg.sender];88 require(block.number >= c.blockNumber + COMMIT_PERIOD, "Commit period not ended");89 require(block.number <= c.blockNumber + REVEAL_DEADLINE, "Reveal deadline passed");90 require(91 keccak256(abi.encodePacked(bid, salt, msg.sender)) == c.hash,92 "Invalid reveal"93 );94 // Process bid — all bids revealed before winner determined95 _processBid(msg.sender, bid);96 delete commitments[msg.sender];97 }98 }99 ```1001013. **Add deadline parameter to time-sensitive transactions**:102103 ```solidity104 function executeOperation(105 address asset,106 uint256 amount,107 uint256 deadline // always require explicit deadline108 ) external {109 require(block.timestamp <= deadline, "Transaction expired");110 // Prevents delayed mining of a transaction when market conditions change111 }112 ```1131144. **Use Flashbots for private transaction submission (off-chain)**:115116 ```javascript117 // ethers.js + Flashbots SDK118 import { FlashbotsBundleProvider } from "@flashbots/ethers-provider-bundle";119 import { ethers } from "ethers";120121 const provider = new ethers.providers.JsonRpcProvider(RPC_URL);122 const flashbotsProvider = await FlashbotsBundleProvider.create(123 provider,124 ethers.Wallet.createRandom(), // reputation signer125 "https://relay.flashbots.net"126 );127128 const signedBundle = await flashbotsProvider.signBundle([{129 signer: wallet,130 transaction: {131 chainId: 1,132 to: CONTRACT_ADDRESS,133 data: swapCalldata,134 gasLimit: 200000,135 maxFeePerGas: ethers.utils.parseUnits("50", "gwei"),136 maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei"),137 }138 }]);139140 // Submit directly to validators — bypasses public mempool141 const bundleSubmission = await flashbotsProvider.sendRawBundle(142 signedBundle,143 targetBlockNumber144 );145 ```1461475. **For NFT mints: random assignment after reveal**:148149 ```solidity150 // Prevent sniper bots from selecting rare traits at mint time151 contract AntiSnipeMint {152 bool public revealed = false;153 uint256 public revealBlock;154 uint256 public revealSeed;155156 function mint(uint256 quantity) external payable {157 // Mint token IDs without revealing traits158 _mintTokens(msg.sender, quantity);159 }160161 function reveal() external {162 require(!revealed && block.number > revealBlock);163 // Use future block hash — not known at mint time164 revealSeed = uint256(blockhash(revealBlock));165 revealed = true;166 }167168 function getTraits(uint256 tokenId) external view returns (uint256) {169 require(revealed, "Not yet revealed");170 return uint256(keccak256(abi.encodePacked(revealSeed, tokenId))) % NUM_TRAITS;171 }172 }173 ```174175## Rules176177- Never use `amountOutMinimum: 0` in swap calls — this accepts any price including one manipulated by a sandwicher.178- Deadline parameters must be caller-supplied and checked against `block.timestamp` — a transaction sitting in the mempool for hours may execute under completely different market conditions.179- Commit-reveal salts must be random and kept secret until reveal — a guessable or reused salt defeats the commitment scheme.180- For large trades, consider using aggregators with MEV protection (CoW Protocol, 1inch Fusion) rather than routing directly through DEXes.181182## Common Mistakes183184- **`deadline: block.timestamp`** — using the current block's timestamp as the deadline means the transaction never expires, defeating the purpose.185- **Small slippage only for large swaps** — a 0.5% slippage tolerance on a $1M swap is still $5,000 of extractable value; consider splitting large swaps.186- **Commit-reveal without salt** — `keccak256(bid)` is brute-forceable for small bid spaces; always combine with a large random salt.187- **Not testing with a fork that simulates MEV** — Foundry supports mainnet fork testing; simulate front-running by having a bot contract observe and front-run your test transaction.