Sandwich Attack on Dex: Spotting Bad Swaps and Cutting Risk | Mobee Academy
DeFi November 19, 2026 Intermediate

Sandwich Attack on Dex: Spotting Bad Swaps and Cutting Risk

Author Bayu Samudera
Read time 8 min
Sandwich Attack on Dex: Spotting Bad Swaps and Cutting Risk

A sandwich attack is a MEV swap pattern on a DEX where an attacker places trades before and after yours to move the price and capture the difference.

It relies on DEX frontrunning, meaning someone spots your pending transaction and races to act before it settles.

You usually notice it when the execution price is far from the quote and the tokens received sit near the minimum.

Key Points

  • Definition: A sandwich attack wraps your swap with entry and exit orders to worsen your execution price.
  • Mechanism: MEV swap activity appears when an attacker sees a pending trade and moves price before it confirms.
  • Signs: Symmetric trades around your swap, wider slippage, and lower received tokens are common clues.
  • Mitigation: Tighter slippage limits, smaller orders, and private routes reduce the attacker's room to maneuver.
  • Audit: Compare quote, minimum received, and final balance before calling a swap sandwiched.

Sandwich Attacks and Dex Frontrunning

On an automated market maker DEX, price follows the ratio of pooled tokens. That design makes large or poorly timed orders visible in the price itself, which is why order flow around a swap can be exploited.

• The Role of Mev Swap

MEV swap value comes from the order of transactions around a trade. An attacker scans pending swaps, then submits an order that benefits from the price move your swap will cause. When it works, the cost lands on the user whose trade confirms later.

• Dex Frontrunning Position

DEX frontrunning means getting ahead of a visible pending trade. The attacker does not need your private key; faster gas or a privileged route can be enough. Ordinary users often lose the race without realizing they were targeted.

• The Backrun That Closes the Trade

After your swap executes at the worse price, the attacker sells the token bought at the start. This closing trade is the backrun. The profit comes from the gap you paid through execution, not from a long-term market forecast.

• Victim and Attacker Profiles

Victims are often users with wide slippage or large orders in thin pools. Attackers can be automated bots, route operators, or parties with block-order access. The more visible pending trades are, the easier the pattern becomes.

A Simple Transaction-Order Diagram

A simple diagram shows that a sandwich is not one magic transaction. It is a sequence: you submit a swap, the attacker enters first, and the attacker exits after your trade.

StepActionPrice Effect
1You submit the swapPrice is unchanged
2Attacker buys the target tokenTarget token price rises
3Your swap executesYou buy at a higher price
4Attacker sells the tokenDifference becomes attacker profit

• Frontrun Raises the Starting Price

The attacker's opening buy takes the target token before your swap is processed. Pool reserves shift, so the token becomes more expensive for everyone trading after that order. Your swap then executes above the original quote and receives fewer tokens.

• Your Swap Fills at a Worse Price

Your transaction can still succeed if it stays within the slippage limit. Success does not mean a good fill. You may receive fewer tokens, and that gap becomes a hidden cost that the first screen did not show.

• Backrun Locks the Difference

Once your swap pushes the price higher, the attacker sells the tokens bought earlier. That sale moves price back while realizing the gain. For you, the loss is already fixed at the execution price, not at the later price.

• Thin Liquidity Makes It Easier

Pools with small reserves move more when a medium order arrives. A swap that looks modest can shift price far more in a thin pool than in a deep one. Choosing liquid markets is a basic defense before blaming MEV.

Explorer Clues to Check

A block explorer is the most practical audit tool because it shows transaction order, swap parameters, and balance changes. You do not need special software to inspect the pattern around your own trade.

• Symmetric Token Transfers

Look for a buy of the target token just before your swap and a sell just after it. Similar size and opposite direction are common sandwich clues. Check the addresses and pool context before drawing a firm conclusion.

• Close Block or Time Spacing

On the explorer, compare block position and timestamp. If the attacker's trade sits one or two positions from yours, MEV interaction is plausible. Normal arbitrage can look similar, so match the timing with price direction and final balance.

• Unusual Gas Costs

Attacker transactions sometimes pay much higher gas to jump the queue. High gas alone is not proof, but it matters when paired with buy and sell trades around your swap. Compare it with other transactions in the same block.

• Pool Reserve Changes

Swap logs show reserve changes before and after each trade. If reserves swing sharply and then revert quickly, temporary price pressure may be present. This helps separate ordinary volatility from order manipulation, especially when paired with matching wallet activity.

How to Audit a Swap Result

Auditing a swap means comparing what you requested, what the protocol promised, and what actually reached your wallet. Follow the sequence so you do not mistake normal costs for an attack.

1. Record Hash and Time

Save the transaction hash, time, and pool name. These details anchor your review in the explorer and help you find the exact block later. Without them, comparing nearby trades and calculating the real gap becomes guesswork.

2. Read the Swap Parameters

Check input token, output token, minimum received, slippage limit, and deadline. These parameters show how much room you gave the market. A loose limit can let a poor fill count as a valid transaction.

3. Compare Quote and Realized Result

The quote is an estimate before execution, while the realized result is the final balance after fees. Small gaps can be normal due to price movement and fees. Large repeated gaps deserve scrutiny, especially with paired trades nearby.

4. Inspect Nearby Transactions

Review trades before and after yours in the same pool. Look for addresses that buy and quickly sell the target token. Match size, direction, and timing so your conclusion rests on evidence rather than a single bad fill.

5. Keep Evidence and Patterns

Log findings in a simple sheet: date, pool, order size, slippage, result gap, and related addresses. If the pattern repeats, you can change your swap habits. Evidence also helps when reporting to a wallet provider or community.

Checklist for a Worse-Than-Expected Swap

Use this checklist before assuming the worst. A worse-than-expected swap may simply reflect fees, volatility, or normal price impact, so rule those out first.

• Quote and Fill Gap Is Wide

If the final result is far below the quote while the transaction succeeded, check whether it stayed inside the slippage limit. A fill near the limit means protection worked, but the limit may be too loose for your order size.

• Price Impact Jumps After Waiting

Price impact can change between preview and block inclusion. Fast markets or thin pools make the shift larger. Refresh the quote before signing and avoid raising slippage just because the first attempt failed.

• Paired Trades Appear

A quick buy and sell of the target token is a stronger signal. Check whether the addresses are the same or connected. Repetition across several of your swaps suggests you may be a routine target.

• Gas Rises Without Clear Cause

Gas can rise because the network is busy, but also because traders compete for order. If gas spikes exactly when your swap processes and nearby trades form a pattern, watch for frontrunning. Do not automatically answer with higher gas.

• Thin Pool and Oversized Order

A large order in a thin pool moves price sharply and invites MEV. Splitting the swap into smaller trades can reduce impact. Check pool depth before choosing size, and compare total fees with the slippage saved.

• Repeated Failed Transactions

A failed swap because slippage was exceeded can mean the market moved faster than your limit. An attacker can also trigger that move. After two or three failures, stop and audit the cause before trying again.

Slippage Limits That Actually Help

A slippage limit is a trade-off between reliable execution and protection from bad pricing. Too tight and swaps fail often; too loose and sandwich attackers get more room.

• Set Slippage from Tolerance

Start from the maximum loss you accept per trade, not from a wish for every swap to succeed. For liquid assets, a tight internal limit may be sensible; for volatile assets, raise it gradually while cutting order size. There is no universal number for every pool.

• Split Large Orders

Breaking an order into smaller trades can reduce price impact and make you a less attractive MEV target. Gas costs and execution time may rise. Compare total cost with the slippage saved before deciding.

• Choose Deeper Pools

Pools with larger reserves absorb orders with less price movement. If a token only trades in a thin pool, reduce size or use an aggregator that splits liquidity across venues. Check depth before swapping, not after a bad fill.

• Watch Confirmation Time

The gap between preview and confirmation gives price time to move. Avoid waiting too long with loose slippage, because the market can change before you sign. Refresh the quote right before signing and cancel if conditions have shifted.

• Avoid Racing a Crowded Queue

When the network is busy, order competition and gas costs rise. Forcing a trade through with high gas is not always profitable. Waiting for calmer conditions or using a route that does not expose details publicly can be safer.

Private Transaction Routes and Their Limits

Private transaction routes send orders directly to builders or relayers instead of exposing details in a public mempool. They reduce frontrunning exposure, but they do not remove every risk.

• How Private Routes Work

An order travels through a special path and is not broadcast openly before inclusion. The provider may bundle transactions in a way that limits bot interception. Effectiveness depends on the service design and the network involved.

• When Private Routes Matter

They matter more for large orders, less liquid tokens, or crowded networks. For a small swap in a deep pool, the benefit may not justify extra cost or complexity. Weigh the trade-off before enabling the route.

• Trust and Failure Risks

You must trust the provider not to misuse order details or fail to execute. There is also a risk that the transaction does not land on time. Read documentation, limit order size, and avoid excessive token approvals.

• Pair with Slippage Limits

A private route does not replace healthy slippage. Keep a minimum received limit and check the quote before signing. If the route fails, do not panic and raise slippage to an extreme level just to force execution, because the loss may grow.

• Market Risk Remains

Asset prices can still move on news, liquidity, or demand. A private route only reduces one type of interaction, namely order abuse. Market and smart contract risks still need separate review, including pool safety and token approvals.

Frequently Underrated Risks

Some risks come from user habits rather than attacker sophistication. Recognizing these patterns helps you cut losses without blaming every price gap on a sandwich.

• Loose Slippage

Loose slippage gives the protocol permission to fill far from the quote. For example, a 5 percent limit on a liquid asset can absorb a large loss during MEV pressure. Tighten the limit and split orders to shrink the attacker's room.

• Large Orders in Thin Pools

Large orders move price more and attract bots. If you buy a small token with limited liquidity, price impact can exceed trading fees. Use smaller size or find a route that splits the order.

• Gas Wars

Raising gas to jump the queue can create high costs without a guaranteed better fill. In a busy market, bots with faster infrastructure may still win the race. Cap gas spend, consider waiting, and avoid reflexively matching every competing bid.

• Repeating the Same Pattern

If you keep using loose slippage and large orders in the same pool, losses can repeat. For example, fills may always land near the minimum. Change order size and route before repeating the trade.

• Treating Every Gap as an Attack

A result gap can come from fees, price movement, or ordinary market impact. Accusing a sandwich without evidence leads to the wrong fix and may distract from real costs. Compare nearby transactions and record patterns before concluding.

• Regulatory Uncertainty

Rules on MEV and order manipulation are not uniform across jurisdictions. Conduct that counts as exploitation in one place may be less clearly regulated elsewhere. Monitor platform terms and local regulator guidance before large trades.

Conclusion

A sandwich attack is an ordering problem, not fate. You can reduce risk by understanding the frontrun and backrun sequence, checking explorer patterns, and comparing quote with final result. Healthy slippage limits, smaller orders, deeper pools, and carefully used private routes narrow the attacker's edge. After each swap, audit the evidence before deciding, then improve the next trade.

FAQ

What is the difference between a sandwich attack and DEX frontrunning?

DEX frontrunning means getting ahead of a visible pending trade, while a sandwich attack uses both a frontrun and a backrun to wrap your swap. Frontrunning is one component; the sandwich is the full pattern that extracts the price gap.

Does every worse-than-expected swap mean I was sandwiched?

No. A lower result can come from fees, normal price impact, price changes while waiting, or thin liquidity. Call it a sandwich only when nearby buy and sell trades plus an unusual result gap support that conclusion.

What slippage limit is safe?

There is no universal number. As a starting point, consider an internal limit around 0.5 percent to 1 percent for highly liquid assets, then raise it only if volatility and order size justify it. Always check minimum received before signing.

Do private transaction routes guarantee no sandwich?

No. Private routes reduce public mempool exposure, but provider failure, delays, or information leakage can still occur. Keep slippage tight and limit order size even when using a private route.

How do I check a swap on a block explorer?

Open the transaction hash, read input and output tokens, minimum received, and final balance. Then inspect trades before and after yours in the same pool. A quick buy and sell around your swap is a clue that needs price context.

Is a sandwich attack illegal?

Legal status depends on the jurisdiction and the facts. Many MEV practices sit in a gray area, while clear manipulation or fraud can violate rules. Verify local regulator and platform terms before drawing a legal conclusion.

Review Swaps with Clearer Signals

This financial insight can be a useful starting point before exploring investing at your own pace. When you feel ready, Mobee, operated by PT CTXG Indonesia Berkarya and licensed and supervised by OJK, offers beginner-accessible digital-asset choices with eligible options from IDR 10,000 depending on the product and deposit method.

Disclaimer

This article is for education only, not financial advice. Digital assets carry risk. Do your own research (DYOR) before making investment decisions.

Direct market access from the app

Start exploring digital assets with Mobee

Track the market, learn about digital assets, and start trading more conveniently with the Mobee App.

Open Mobee App

Mobee is licensed and supervised by the OJK. Not a solicitation to buy or sell any asset.

Mobee

Treasury Tower Office Building, 18th Floor District 8, Sudirman Central Business District (SCBD) 12190, DKI Jakarta

Follow our social media

Join our community

Registered & supervised by

ICEx Komdigi Intertek, KAN Asosiasi Pedagang Aset Kripto Indonesia

Contact Us

Directorate General of Consumer Protection and Trade Order
Ministry of Trade of the Republic of Indonesia
0853 1111 1010 (WhatsApp)

Copyright © 2026 PT. CTXG Indonesia Berkarya. All rights reserved.

Crypto asset trading is facilitated by PT CTXG Indonesia Berkarya, a licensed Digital Financial Asset Trader by the Financial Services Authority (OJK) and a registered member of PT Fortuna Integritas Mandiri (ICEx).

This website is provided for informational purposes only. None of the material on this site is intended to be, nor does it constitute, a solicitation, recommendation, or offer to buy or sell any security, financial product, or instrument. Trading cryptocurrency is a high-risk activity. Past performance does not reflect future performance. Historical performance, expected return, and probability projections are provided for informational and illustrative purposes. All cryptocurrency trading decisions are independent decisions by users.