Front-Running & MEV
Front-Running & MEV
Front-running and Maximum Extractable Value (MEV) attacks exploit transaction ordering in the mempool to gain unfair advantages.
What is Front-Running?
Front-running occurs when an attacker observes a pending transaction in the mempool and submits their own transaction with a higher gas price to have it executed first.
Types of MEV Attacks
1. Sandwich Attacks
In DEX transactions:
1. Attacker sees your buy order in mempool
2. Attacker places a buy order before yours (front-run)
3. Your transaction executes at a worse price
4. Attacker sells immediately after (back-run)
5. Attacker profits from the price movement
2. Liquidation MEV
Bots compete to be first to liquidate undercollateralized positions in lending protocols, earning liquidation rewards.
3. Arbitrage MEV
Exploiting price differences across DEXs by being the first to execute arbitrage trades.
Vulnerable Patterns
Price-Sensitive Transactions
// Vulnerable: No slippage protection
function swap(uint amountIn) public {
uint amountOut = getPrice(amountIn);
token.transferFrom(msg.sender, address(this), amountIn);
outputToken.transfer(msg.sender, amountOut);
}Prevention Strategies
1. Slippage Protection
function swap(uint amountIn, uint minAmountOut) public {
uint amountOut = getPrice(amountIn);
require(amountOut >= minAmountOut, "Slippage too high");
token.transferFrom(msg.sender, address(this), amountIn);
outputToken.transfer(msg.sender, amountOut);
}2. Commit-Reveal Scheme
For sensitive operations, use two-phase commits:
mapping(bytes32 => uint) public commits;
function commit(bytes32 hash) public {
commits[hash] = block.number;
}
function reveal(uint value, bytes32 salt) public {
bytes32 hash = keccak256(abi.encodePacked(msg.sender, value, salt));
require(commits[hash] > 0, "No commit found");
require(block.number > commits[hash] + 10, "Too early");
// Execute with revealed value
}3. Batch Transactions
Submit multiple operations in a single transaction to prevent interference.
4. Flashbots / Private Mempools
Use Flashbots Protect or similar services to submit transactions directly to miners, bypassing the public mempool.
Design Considerations
1. **Minimize MEV Surface**: Reduce opportunities for extractable value
2. **Use Oracles**: Time-weighted average prices (TWAP) are more resistant to manipulation
3. **Add Delays**: Introduce time delays for critical operations
4. **Set Bounds**: Implement minimum/maximum values for sensitive parameters
Tools & Resources
- **Flashbots**: https://docs.flashbots.net/
- **MEV-Inspect**: Tool for analyzing MEV activity
- **OpenMEV**: Research and tooling for MEV
Best Practices
1. Always implement slippage protection for price-sensitive operations
2. Consider using commit-reveal for sensitive actions
3. Use TWAP oracles instead of spot prices
4. Add deadline parameters to time-sensitive transactions
5. Consider MEV in economic model design
6. Monitor mempool for suspicious activity