Skip to content
Basis Desk

New from Basis Desk: free Telegram proxies for places where Telegram is blocked or slowed down.Connect in one tap →

DeFi · 6 min read Last reviewed October 27, 2026

How to Protect Your DeFi Swaps From Sandwich Attacks

A guide to understanding how maximal extractable value (MEV) bots exploit public mempools, and the tools decentralized finance users can deploy to secure their trades.

Editorial oversight: Julian Mercer, Chief Editor
Neutral

Key points

  • Sandwich attacks occur when bots exploit pending trades in the public mempool by manipulating asset prices before and after execution.
  • Wide slippage tolerances give bots the profit margin necessary to execute front-running attacks.
  • Private RPCs protect users by routing transactions directly to block builders, bypassing the public mempool entirely.
  • Batch auctions and intent-based routing neutralize sandwich attacks by executing trades simultaneously or delegating execution to competing solvers.

Decentralized finance users can protect their token swaps from sandwich attacks by utilizing private remote procedure call (RPC) endpoints and minimizing slippage tolerances. These tools prevent automated bots from viewing pending transactions in the public mempool and exploiting the price impact of large trades.

Automated market makers process trades differently than traditional limit order books. Understanding the mechanics of block construction, transaction ordering, and liquidity pools is essential for securing decentralized exchange (DEX) operations.

The Mechanics of a Sandwich Attack

In traditional finance, front-running involves a broker executing a trade for their own account before filling a customer's order, profiting from the anticipated price movement. In decentralized finance (DeFi), this concept manifests as a sandwich attack, a specific form of maximal extractable value (MEV). MEV refers to the maximum profit a block producer or validator can extract by including, excluding, or reordering transactions within a block.

When a user submits a trade on a decentralized exchange, the transaction does not execute instantly. It enters a holding area called the public mempool. Automated searcher bots constantly scan this mempool for profitable opportunities. If a user submits a large buy order for Ethereum ($ETH), the bot calculates that this trade will increase the price of the asset within the liquidity pool.

The bot then submits two of its own transactions. The first is a buy order placed immediately before the user's transaction, purchasing the asset at the current lower price. The user's transaction executes next, pushing the price of the asset higher. Finally, the bot's second transaction executes immediately after the user's trade, selling the newly acquired asset at the artificially inflated price. The user is left paying a worse exchange rate, while the bot extracts the difference as risk-free profit.

The Role of the Public Mempool

The public mempool is the fundamental vulnerability that enables sandwich attacks. It acts as a transparent waiting room where unconfirmed transactions broadcast by wallets reside before validators select them for inclusion in the next block. Because blockchain networks operate on transparency, the data within the public mempool—including the sender, the tokens being swapped, the transaction size, and the maximum slippage tolerance—is visible to anyone running a network node.

Searcher bots use this transparency to simulate the outcome of pending trades. They monitor network gas fees, which dictate the priority validators assign to transactions. To execute a sandwich attack, the bot pays a higher gas fee for its front-running transaction to ensure it is processed first, and a precise fee for its back-running transaction to ensure it executes immediately after the target. This targeted fee manipulation guarantees the desired transaction ordering within the block.

Users evaluating their security posture across decentralized platforms must consider how their transactions are routed. The DeFi Risk Checklist: Evaluating Smart Contracts, Oracles, Governance, and Custody outlines broader platform vulnerabilities, but transaction-level risks like MEV require specific user interventions.

Slippage Tolerance: The Attack Vector

To ensure trades execute despite normal market volatility, decentralized exchanges require users to set a slippage tolerance. Slippage is the difference between the expected price of a trade and the actual price at which the trade executes. By setting a slippage tolerance, the user specifies the maximum price movement they are willing to accept before the transaction reverts and fails.

Wide slippage tolerances create the profit margin for sandwich attacks. If a user sets a slippage tolerance of 5%, they signal to the market that they are willing to accept up to 5% fewer tokens than the current quoted rate. A searcher bot will exploit this exact margin, manipulating the pool's price right up to the user's maximum acceptable limit.

Consider a numeric example using a standard constant product automated market maker (AMM). Assume a liquidity pool contains 1,000 $ETH and 2,000,000 USD Coin ($USDC). The constant product formula is x * y = k, so 1,000 * 2,000,000 = 2,000,000,000 (k). The current price of 1 ETH is 2,000 USDC.

A user submits a swap to buy 10 ETH with a 3% slippage tolerance. Without interference, buying 10 ETH would require approximately 20,202 USDC. However, a bot sees this 3% buffer. The bot buys 20 ETH first, shifting the pool ratio so the price of ETH rises. The user's transaction then executes at a worse rate, barely staying within their 3% limit, yielding them 10 ETH for roughly 20,800 USDC instead of 20,202 USDC. The bot then sells its 20 ETH back into the pool at the higher price, pocketing the USDC difference extracted from the user's slippage buffer.

Users can mitigate this by manually lowering their slippage tolerance to 0.5% or 0.1%, depending on the liquidity of the trading pair. While this reduces the attack surface, it increases the risk of the transaction failing (reverting) if organic market movements push the price beyond the tight tolerance, costing the user network gas fees for a failed trade.

Private RPCs: Bypassing the Mempool

The most effective defense against sandwich attacks is removing the transaction from public view. Network communication occurs through Remote Procedure Call endpoints, which serve as the bridge between user wallets and blockchain nodes. By default, most wallets route transactions to public RPCs, which broadcast them directly to the public mempool.

Private RPCs offer an alternative routing mechanism. These endpoints send transactions directly to specialized block builders or validators, bypassing the public mempool entirely. Because the transaction is never broadcast to the wider network, searcher bots cannot view it, simulate it, or front-run it.

Services like Flashbots Protect pioneered this approach on Ethereum by creating a direct channel between users and MEV-aware block builders. When a user submits a swap through a private RPC, the block builder promises to include the transaction in a block only if it does not fail and is not front-run. If the trade cannot be executed fairly, it is simply dropped, protecting the user from both sandwich attacks and the gas costs associated with reverted transactions.

While private RPCs are highly effective, they introduce centralization trade-offs. Users must trust the entity operating the private endpoint not to exploit the transaction themselves or leak the order flow to affiliated searchers.

Batch Auctions and Intent-Based Routing

Beyond private RPCs, the decentralized finance ecosystem has developed alternative exchange architectures that structurally eliminate sandwich attacks. The most prominent model is the batch auction, utilized by protocols like CowSwap.

Instead of executing trades sequentially as they arrive, batch auctions collect user orders over a specific time period. The protocol groups these orders together and executes them simultaneously at a uniform clearing price. Because all trades in the batch settle at the same price, transaction ordering becomes irrelevant, completely neutralizing the front-running and back-running mechanics required for a sandwich attack.

This architecture is often paired with intent-based routing. Rather than broadcasting a specific transaction to interact with a smart contract, users sign an off-chain message stating their intent (e.g., "I want to exchange 1,000 USDC for at least 0.4 ETH"). Specialized participants called solvers compete to find the optimal routing path across various decentralized exchanges to fulfill this intent. The protocol selects the solver offering the best execution price.

Intent-based architectures shift the burden of execution and MEV protection from the user to professional solvers. If a solver fails to secure the requested price or attempts to exploit the user, the protocol penalizes them. This model protects users from slippage exploitation while often securing better execution prices than a single AMM could provide.

Common Misconceptions

  • Private RPCs guarantee faster execution: Routing transactions through private RPCs can occasionally result in slower execution times. Because the transaction is only sent to specific block builders rather than the entire network of validators, users may have to wait longer for one of those specific builders to win a block proposal.
  • Low slippage guarantees a good price: While setting a low slippage tolerance prevents bots from extracting a large margin, it does not guarantee the underlying exchange rate is optimal. Users can still receive poor execution if they trade on an illiquid decentralized exchange with a wide spread.
  • All MEV is malicious: Not all maximal extractable value harms users. Arbitrage bots that align prices across different decentralized exchanges are a form of MEV that ensures market efficiency. Sandwich attacks are a specific, predatory subset of MEV.

What to Watch

The landscape of MEV protection is shifting toward protocol-level solutions rather than relying solely on user-configured RPCs. Network architects are actively researching mechanisms to encrypt the mempool or implement delayed execution models that separate transaction inclusion from transaction ordering.

Regulators are also examining MEV extraction. Jurisdictions like the European Union, under the Markets in Crypto-Assets (MiCA) framework, are analyzing whether certain types of MEV, including sandwich attacks, constitute market abuse or illegal front-running. As decentralized finance matures, the legal classification of searcher bots and block builders will heavily influence the infrastructure designed to protect retail order flow.

Questions this story raises

What is a sandwich attack in DeFi?
A sandwich attack is a strategy where an automated bot spots a pending trade in the public mempool, buys the asset just before the user to raise the price, and sells it immediately after the user's trade to extract a profit.
How does slippage tolerance affect my trade?
Slippage tolerance determines the maximum negative price movement you will accept. A high tolerance allows bots to manipulate the price further, extracting more value from your trade.
What is a private RPC?
A private Remote Procedure Call (RPC) endpoint is a network gateway that routes your transactions directly to block builders instead of the public mempool, keeping your trades hidden from searcher bots.
Do private RPCs cost money?
Generally, setting up and using a private RPC for MEV protection is free for users, as the block builders profit from other non-toxic forms of MEV or general transaction volume.

References

  1. [1] Flashbots Protect Documentation — Flashbots
  2. [2] Ethereum Whitepaper and Documentation: MEV — Ethereum Foundation

Evergreen explainer written by Basis Desk's system and checked by an independent model pass for factual errors and advice language. Figures, fees and rules change — the references above are where to verify current specifics. Market figures marked "at the time of writing" come from live exchange data. Report an error: corrections@basisdesk.news · corrections policy.

The Daily Brief, in your inbox at 07:00 ET

Five stories, the numbers that moved, what to watch. Three minutes. No hype, no advice, unsubscribe in one click.

Not financial advice. Basis Desk publishes information, not recommendations. Crypto assets are volatile and you can lose what you invest.