Development of frontrunning protection system
Frontrunning in blockchain — using public mempool visibility to extract profit from other transactions. MEV (Maximal Extractable Value) — broader concept: all value that validators/searchers extract by including/excluding/reordering transactions in block. Sandwich attacks, arbitrage, liquidation MEV — all this is MEV. Users daily lose millions on sandwich attacks alone on Ethereum.
Protection built on multiple levels: transaction privacy, commit-reveal schemes, specialized RPC, on-chain slippage controls.
How sandwich attack works
Attacker monitors mempool, sees large swap (e.g., 50 ETH for USDC through Uniswap). Before this transaction inserts his own — buy ETH (raising price). After victim — sells ETH at raised price. Victim gets USDC at worse price, attacker extracts difference.
Key conditions: sufficiently high slippage tolerance on victim (so transaction doesn't revert), sufficient swap size to cover attacker's gas.
Block N:
tx[0]: Attacker buys ETH (frontrun) — higher gas than victim
tx[1]: Victim swaps 50 ETH → USDC (at inflated price)
tx[2]: Attacker sells ETH (backrun) — lower gas than victim
Protection 1: Private RPC / MEV-blockers
Simplest and most effective for users: send transactions through private mempool, bypassing public Ethereum mempool.
Flashbots Protect RPC (https://rpc.flashbots.net) — free endpoint. Transactions go directly to Flashbots bundle builders, bypassing public mempool. Not suitable for fast arbitrage transactions but excellent for regular user swaps.
MEV Blocker (https://rpc.mevblocker.io) — from CoW Protocol and Gnosis team. Sends transactions to multiple builders simultaneously, first to include gets exclusive access to backrun (without frontrun). Backrun profit returned to user as kickback.
Integration in dApp: add alternative RPC endpoint as option in wallet connection:
const mevProtectedProvider = new ethers.JsonRpcProvider(
'https://rpc.mevblocker.io',
{ chainId: 1, name: 'mainnet' }
)
// Or via wagmi config
const config = createConfig({
chains: [mainnet],
transports: {
[mainnet.id]: http('https://rpc.mevblocker.io'),
},
})
Protection 2: Commit-Reveal scheme
For protocols where parameter confidentiality matters before execution (auctions, lotteries, some AMMs). Two-phase process:
Commit: user sends hash(action + secret) — hidden intent.
Reveal: after deadline all participants reveal secrets, actions execute.
contract CommitRevealAuction {
mapping(address => bytes32) public commitments;
mapping(address => bool) public revealed;
uint256 public commitDeadline;
uint256 public revealDeadline;
// Phase 1: commit
function commit(bytes32 commitment) external {
require(block.timestamp < commitDeadline, "Commit phase over");
commitments[msg.sender] = commitment;
}
// Phase 2: reveal
function reveal(uint256 bidAmount, bytes32 secret) external {
require(block.timestamp >= commitDeadline, "Still in commit phase");
require(block.timestamp < revealDeadline, "Reveal phase over");
require(!revealed[msg.sender], "Already revealed");
bytes32 expectedCommitment = keccak256(abi.encodePacked(bidAmount, secret, msg.sender));
require(commitments[msg.sender] == expectedCommitment, "Invalid reveal");
revealed[msg.sender] = true;
_processBid(msg.sender, bidAmount);
}
}
Commit-reveal vulnerability: if reveal transactions visible in mempool — attacker can frontrun last reveal, seeing successful bids of others. Protection: encrypted reveal via threshold encryption (SUAVE, Shutter Network).
Protection 3: On-chain slippage controls
Tight on-chain slippage limits don't protect from sandwich (attack adapts to tolerance) but limit potential damage.
Uniswap v3 sqrtPriceLimitX96 — hard limit on execution price. If price exceeds limit — swap stops (partial fill), doesn't fully revert. Better than full transaction rollback on minimal slippage.
For AMM with custom price mechanics — add minAmountOut check:
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut // slippage protection
) external returns (uint256 amountOut) {
amountOut = _executeSwap(tokenIn, tokenOut, amountIn);
require(amountOut >= minAmountOut, "Slippage exceeded");
return amountOut;
}
minAmountOut should be calculated frontend with real slippage (usually 0.1-1%). Recommend max 0.5% slippage to users — reduces sandwich attack effectiveness.
Protection 4: TWAP for on-chain pricing
Protocols using AMM spot price for calculations (liquidation price, collateral valuation) — vulnerable to flash loan manipulation. TWAP (time-weighted average price) from Uniswap v3 resistant to single-block manipulation.
// Get TWAP from last 30 minutes from Uniswap v3
function getTWAP(address pool, uint32 twapInterval) internal view returns (uint256 price) {
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = twapInterval; // 1800 seconds = 30 minutes
secondsAgos[1] = 0;
(int56[] memory tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
int24 timeWeightedAverageTick = int24(tickCumulativesDelta / int32(twapInterval));
price = TickMath.getSqrtRatioAtTick(timeWeightedAverageTick);
// Convert sqrtPriceX96 to readable price
}
30-minute TWAP means attacker needs to maintain distorted price for 30 minutes — expensive and economically unreasonable.
Protection 5: EIP-3074 and EIP-7702 (future)
EIP-7702 (active in Pectra upgrade 2025) allows EOAs to temporarily delegate execution to contract. Opens path to transaction bundles at wallet level — multiple transactions atomically, making sandwich impossible (can't insert transaction inside atomic bundle).
For new protocols targeting Pectra-compatible wallets — promising protection architecture.
Comparison of approaches
| Method | Sandwich protection | Complexity | UX Impact |
|---|---|---|---|
| Private RPC | High | Minimal | Minimal |
| Commit-Reveal | High | High | High (2 tx) |
| Slippage controls | Partial | Low | None |
| TWAP oracle | Flash loan protection | Medium | None |
| MEV Blocker | High + rebate | Minimal | Minimal |
Practical recommendation: for dApp — integrate MEV Blocker or Flashbots Protect RPC as default transport + strict slippage recommendations (max 0.5% for stablecoins, max 1% for volatile assets). This covers 90% of sandwich vectors without architectural changes.
Development of custom protection system (commit-reveal for auction, TWAP integration) — 2-4 weeks depending on mechanics.







