Uniswap Sandwich Attacks: What They Are and How to Protect Yourself
A user submits a transaction on Uniswap to swap 10 ETH for a stablecoin. The transaction sits in the mempool waiting for confirmation. Within seconds, another transaction appears ahead of it—from an attacker who sees the pending trade, executes a similar swap to move the price, and then places the user’s transaction immediately after. The attacker then exits the position behind the user’s trade, capturing the difference as profit. This is a sandwich attack, one of the most common forms of extractive behavior in decentralized finance, and it costs everyday traders millions of dollars each year across Ethereum and Layer 2 networks.
Sandwich attacks exploit the transparent nature of blockchain transactions and the time delay between transaction submission and final settlement. Because every pending transaction is visible in the mempool before it is included in a block, sophisticated attackers and searchers can anticipate where a trade will move the price and position themselves to capture the slippage. On a smart contract DEX like Uniswap, which processes billions in daily volume, the economics are simple: if a single large trade moves the market by even 0.5%, an attacker can extract substantial value by trading ahead and behind it. The difference between what you expect to receive and what you actually get—your price slippage—is where the attacker’s profit comes from.
How sandwich attacks work on Uniswap
The mechanics of a sandwich attack depend on the visibility of pending transactions and the way Uniswap’s automated market maker model prices trades. When a user creates a transaction to swap tokens, that transaction is broadcast to the Ethereum mempool or the relevant Layer 2 network’s transaction pool. In a public mempool, the transaction details—including the input token, output token, and amount—are visible to all nodes and to any searcher monitoring the network. An attacker or MEV (maximal extractable value) searcher can see the exact parameters of your trade before it is confirmed.
Once the attacker identifies a profitable opportunity, they construct two transactions. The first transaction executes a trade in the same direction as the victim—for example, buying the same token or using the same liquidity pool. This pushes the price against the victim. The second part of the attack involves placing the victim’s transaction after the attacker’s first transaction but before the attacker’s exit trade. The victim’s larger trade then executes at a worse price than they expected, and the attacker profits from the difference. This three-part structure—frontrun, victim, backrun—is the classic sandwich pattern.
The economic incentive is straightforward. If you are trying to swap 10 ETH for USDC at a 1% slippage tolerance on Uniswap, you might expect to receive around 16,000 USDC (assuming a rough 1600 USDC/ETH rate). An attacker could front-run your trade by buying USDC first, pushing the price to 1650 USDC/ETH. Your transaction then executes at the worse rate, and you receive only 15,750 USDC instead. The attacker then sells the USDC they bought, exiting the position and pocketing the 250 USDC difference. All of this happens in a single block or across two consecutive blocks, often in under 12 seconds on Ethereum.
The attack is especially effective on Uniswap because the protocol is transparent and non-custodial—properties that make it trust-free but also expose transaction details publicly. The constant product formula (x*y=k) that governs pricing in Uniswap’s liquidity pools means that price impact scales with trade size. Large trades always move the price, and that movement is predictable. An attacker using real-time price feeds or simulating the transaction on-chain can calculate exactly how much slippage will occur and whether an attack is profitable before committing gas fees.
Identifying sandwich attacks and price slippage
The first warning sign of a potential sandwich attack is unexpectedly high price slippage compared to what the Uniswap interface predicted. When you request a quote for a trade, the UI shows a minimum output amount based on the current price and your slippage tolerance setting. If your transaction finally executes and receives significantly less than that minimum—or if the transaction fails with a “INSUFFICIENT_OUTPUT_AMOUNT” revert—a sandwich attack may have occurred. Comparing the quoted price to the executed price is the most straightforward detection method available to any user.
Another signal is the block structure of your transaction. If you inspect the transaction hash on Etherscan or a block explorer, you can see whether other transactions from different addresses executed in the same block immediately before or after your trade. A cluster of transactions all interacting with the same Uniswap pool in the same block, with clear buy-then-sell or sell-then-buy patterns, suggests MEV extraction. This is not definitive proof of a sandwich attack—legitimate users might coincidentally trade the same pool—but it is a pattern worth noting, especially if it consistently happens on large trades.
Gas price and transaction ordering can also hint at manipulation. If you set a reasonable gas price and your transaction still sits in the mempool for several blocks before confirming, while other transactions overtake it, that delay itself can attract attackers. More time in the mempool means more opportunities for searchers to see your trade and construct a response. Conversely, if you suddenly see your transaction confirm next to several others in a dense block, check the prices those other transactions executed at. Public mempools make this easy: mempool aggregators like Eigenphi or MEV-Inspect provide historical data on extracted value.
One practical check is to simulate your transaction locally before submitting it. Tools like Tenderly or MEV-aware wallets allow you to estimate the exact output amount if your trade executes alone. Compare that estimate to the output you actually receive. If the difference is larger than you set your slippage tolerance to allow, the transaction should have failed. If it succeeded anyway, either the UI is not correctly reflecting pool state, or your slippage tolerance was exceeded by a sandwich attack.
Private RPC endpoints and encrypted transactions
The most direct defense against sandwich attacks is to keep your transaction details hidden until it is confirmed. Using a private RPC (remote procedure call) endpoint instead of a public mempool prevents your transaction from being visible to searchers and attackers before it is included in a block. Services like MEV-resistant RPC providers route transactions through private channels, often using MEV-pooling or encrypted transaction bundles that are only decrypted when a block is built.
Several providers now offer privacy-focused RPC endpoints at low or no cost. Flashbots Protect, for example, integrates directly into MetaMask and other wallets, sending transactions to a private relay rather than the public mempool. The trade-off is that you are trusting the RPC provider not to sandwich your transaction themselves and to prioritize honest bundling. Flashbots’ research has shown that properly implemented MEV protection can reduce sandwich attacks by over 90%. However, no private RPC guarantees zero exposure. If the provider itself becomes a target for regulatory action or if block builders have incentives to extract MEV, privacy is not absolute.
MEV-Blocker and similar protocols use threshold encryption, where transactions are encrypted until a threshold of builders or proposers have agreed to include them without extraction. This distributes trust across multiple parties rather than centralizing it with one RPC provider. For on-chain trading on Uniswap, choosing a private relay also slightly delays confirmation—your transaction may not execute in the very next block—but that delay often results in a better price than you would have received after being sandwich-attacked on a public mempool.
The implementation is straightforward for most users. When you connect your wallet to Uniswap or use a DEX aggregator, you can select your RPC endpoint in the wallet settings or through the DEX interface. Rather than pointing to the default public endpoint, you specify the private RPC address provided by MEV-Blocker, Flashbots Protect, or another service. Your transaction then routes through their infrastructure instead of appearing in the public mempool. Gas fees remain the same, and the transaction is guaranteed to execute if it is valid and the private relay is operational.
Slippage tolerance settings and trade sizing
Slippage tolerance is a blunt but important defense mechanism. By setting a lower slippage tolerance, you create a hard constraint: if the price moves more than your limit before the transaction confirms, the entire trade reverts instead of executing at a terrible rate. The default slippage tolerance on many Uniswap interfaces is 0.5% or 1%, which is reasonable for most trades but not for large ones. If you are swapping 100 ETH worth of value or more, a 1% slippage tolerance might be too high.
The paradox is that a very low slippage tolerance—such as 0.1%—makes your transaction less likely to be attacked because the attacker cannot profit enough. A sandwich attacker needs to create at least enough price movement to overcome gas costs and still pocket a meaningful profit. On Ethereum mainnet, where gas can cost $10 to $100 per transaction, the attacker needs to extract at least that much value. If your slippage tolerance is only 0.05%, and the pool is deep enough that moving the price by 0.05% would cost the attacker more in gas than they could profit, they will skip your trade entirely.
However, lowering slippage tolerance too far creates a different problem: normal price volatility might cause your transaction to revert for no reason other than unlucky timing. The sweet spot depends on market conditions, trade size, and liquidity depth. For most small retail trades under 10 ETH, a 0.5% slippage tolerance is adequate and will revert if the worst-case sandwich happens. For larger trades, 0.1% to 0.3% is more appropriate, combined with other protections like private RPCs or limit orders.
Trade sizing itself is a behavioral defense. Breaking one large order into several smaller orders over time makes it harder for attackers to identify a profitable sandwich opportunity. If you split a 100 ETH swap into ten 10 ETH swaps executed at different times, an attacker would need to sandwich each one individually, vastly reducing profitability. This approach trades convenience and speed for safety, but it is a practical option for users who can execute trades across multiple transactions.
MEV protection protocols and order flow auctions
A newer class of solutions uses order flow auctions (OFA) and encrypted mempools to fundamentally change the economics of sandwich attacks. Rather than letting transactions sit in a public mempool where any searcher can see them, these protocols collect transactions, encrypt them, and run an auction where different builders or searchers bid to include them in a block. The user receives protection because no single entity sees the transaction details in plaintext before committing to a specific execution price.
Flashbots Builder, for example, accepts private transactions and bundles them with other orders, inserting them into Ethereum blocks in a way that minimizes extractable value. MEV-Blocker combines multiple relays and builders, further distributing trust. For non-custodial trading on Uniswap, integrating with these services happens at the wallet level—your wallet automatically sends transactions to the protected relay instead of the public mempool. The experience for the user remains identical: you submit a trade and it confirms. The difference is in the backend routing.
Some DEX aggregators now integrate MEV protection natively. Instead of routing your Uniswap trade through a standard public RPC, they can internally submit it to a private relay, compare the execution price against what you would have received on-chain, and choose the better outcome. If the private relay offers a meaningfully better price due to sandwich protection, the aggregator uses it. If the public mempool would be faster with acceptable slippage, they use that instead. This approach requires no additional configuration from the user but does depend on the aggregator implementing the logic correctly.
The limitation of OFA and encrypted mempool solutions is that they shift MEV rather than eliminating it. Instead of a searcher sandwich-attacking you in the public mempool, a builder or relay operator might extract value by ordering your transaction unfavorably within their private block. This is why multiple relays and a distributed model matter: if you trust only one builder with your transaction, they can silently sandwich you. With multiple competing builders and transparent pricing, the incentive for extraction decreases because users will switch to honest providers.
Limit orders and intent-based systems
An alternative to AMM trades is to use limit orders, which specify an exact output amount and let the protocol match your order only if that price or better is available. Uniswap itself does not natively offer limit orders on its core protocol, but smart contract wrappers and intent-based order flows like CoW (Coincidence of Wants) Swap provide this functionality. With a limit order, you state: “Swap 10 ETH for at least 16,000 USDC.” The order does not execute unless that price or better is available, eliminating the sandwich attack entirely because there is no price impact for the attacker to exploit.
The trade-off is that limit orders may not execute immediately, especially if the market never touches your target price. A limit order for 16,000 USDC per 10 ETH might sit unfilled if the best available price is 15,900 USDC per 10 ETH. Additionally, limit order services like CoW Swap introduce a reliance on solvers and infrastructure outside the core Uniswap protocol. However, they do provide stronger guarantees: as long as the order remains active, you cannot be sandwich-attacked because the minimum output price is fixed at submission time.
Intent-based systems go further by encrypting the user’s intent rather than the full transaction. The network knows you want to “swap token A for token B with a minimum output of X,” but not which specific pool you will use or the exact execution mechanism. Multiple solvers compete to fulfill that intent at the best price. This allows for more sophisticated routing than a single Uniswap transaction—the solver might split your order across multiple pools, use bridge liquidity, or defer execution to a later block—all while protecting you from sandwich attacks.
Best practices for protecting yourself on Uniswap
A comprehensive defense combines multiple layers because no single solution is bulletproof. Start with a private RPC endpoint and encrypted transaction service. Flashbots Protect or MEV-Blocker should be your default for any trade worth more than a few thousand dollars. Set your slippage tolerance appropriately based on market conditions and trade size—typically 0.3% to 0.5% for normal retail trades, and lower for larger orders. Always verify the output amount displayed by the Uniswap interface against your expectations before submitting the transaction.
For large trades, consider breaking them into smaller chunks executed over time, or use a limit order service to specify an exact minimum output and avoid any price impact risk. Monitor your confirmed transactions on block explorers and mempools aggregators to identify whether sandwich attacks are occurring repeatedly. If you notice a pattern of unexpectedly low execution prices despite low slippage settings, your RPC provider or wallet might not be routing transactions correctly, and switching providers is appropriate.
Keep your wallet software and browser extensions up to date, as wallet vulnerabilities can expose transactions to attackers before they are encrypted. If you use a hardware wallet for large trades, the signing process itself is isolated, and no sandwich attack can compromise the private key. However, the transaction details still need protection before submission, so private RPC remains important even with hardware wallets. Most importantly, understand that on-chain trading on any smart contract DEX involves exposure to MEV. The goal is not to eliminate that exposure entirely—which is impossible—but to reduce it to a level where the cost of your protection is less than the value you would lose to attacks.
Finally, consider using a uniswap interface or DEX aggregator that natively integrates MEV protection. Many popular alternatives now bundle private RPC access, MEV pooling, or intent-based routing directly into the swap flow, so you get protection without manually configuring endpoints. The additional infrastructure and slight delay in confirmation are usually worth the reduced risk of sandwich attacks, especially when trading larger amounts where a few percentage points of slippage can translate to hundreds or thousands of dollars.
Frequently asked questions
What is a sandwich attack on Uniswap?
A sandwich attack occurs when an attacker sees your pending transaction in the mempool, places their own transaction ahead of yours to move the price, and then executes an exit trade after your transaction confirms. Your trade executes at a worse price, and the attacker profits from the difference. On Uniswap, this is possible because transactions are publicly visible before confirmation and price impact is predictable on the automated market maker model.
How can I protect myself from sandwich attacks on Uniswap?
Use a private RPC endpoint like Flashbots Protect or MEV-Blocker to keep your transaction hidden from the public mempool. Set an appropriate slippage tolerance—lower for large trades—and verify the output amount before submitting. For large trades, consider using limit orders or breaking the swap into smaller chunks executed at different times. Monitor your confirmed transactions to detect patterns of unexpectedly poor execution prices.
Does private RPC completely prevent sandwich attacks?
No. Private RPC services prevent sandwich attacks in the public mempool by encrypting your transaction and routing it through private channels, reducing risk by over 90% in most cases. However, the RPC provider itself or the block builder they work with could theoretically extract MEV. Using multiple competing services and choosing providers with transparent infrastructure reduces this risk further, but no solution is absolutely bulletproof.