7Block Labs
Blockchain Technology

ByAUJay

MEV Protection: How to Shield Your Users from Sandwich Attacks

Sandwich attacks can be a real pain for users in the crypto space. These sneaky tactics allow bad actors to exploit transactions in a way that can cost users money. So, how do we protect our users from these attacks? Let's dive into some strategies to help keep their funds safe.

What’s a Sandwich Attack Anyway?

A sandwich attack occurs when a malicious actor places two transactions around a user’s transaction. Here’s how it typically plays out:

  1. User places a transaction: Let’s say they want to buy a popular token.
  2. Attacker sees this transaction: They notice it on the mempool (the queue of pending transactions).
  3. Attacker front-runs the user: They quickly buy the token first, driving up the price.
  4. User’s transaction gets executed: Now, the user buys the token at a higher price.
  5. Attacker sells the token: Finally, the attacker sells their token at the inflated price, pocketing the difference.

Ouch, right?

How to Protect Your Users

Here are some practical steps you can take to shield your users from these kinds of attacks:

1. Use MEV Protection Tools

There are several tools and services that have popped up to combat MEV and sandwich attacks. Consider integrating one of these into your platform:

  • Flashbots: They provide a more transparent way for miners to handle MEV.
  • EIP-1559: This Ethereum improvement proposal helps to create a system that mitigates extreme fee variability.

2. Implement Transaction Batching

By batching transactions, you can help obscure individual user trades. This makes it tougher for attackers to pinpoint when to strike.

3. Educate Your Users

Help your users understand the risks involved. Share resources and tips on how to spot potential red flags, like sudden price spikes or high gas fees.

4. Encourage Limit Orders

Promote the use of limit orders instead of market orders. This way, users can set the price they’re willing to pay, which can help them avoid getting caught up in the frenzy.

5. Collaborate with DeFi Protocols

Partnering with decentralized finance (DeFi) protocols that prioritize user safety can go a long way. Together, you can create a safer environment for everyone.

Conclusion

Sandwich attacks might be a tricky phenomenon in the crypto world, but with the right approach, we can definitely protect our users. By using tools, educating users, and implementing safer transaction methods, we can make a positive impact and keep their funds secure. Remember, keeping your users informed and safe should always be the top priority!

your specific headache right now

  • So, you rolled out a pricing update, but users are still seeing that annoying message: “execution price worse than quoted” during peak volatility. After digging into the post-trade analysis, you noticed some sequential swaps in the same pool, some weird tick jumps, and a spike of reverted transactions just before inclusion. It’s a classic case of sandwich flow, right out of the textbook.
  • Did you know that over 90% of Ethereum blocks are generated through MEV-Boost? It’s wild! Historically, just three builders have been responsible for about 80% of the blocks during the periods we’ve looked at. This means attackers don’t need to keep an eye on the entire mempool; they just have to predict what the builders will do next. That kind of concentration really ramps up how predictable ordering can be, which makes the usual advice of “just raise slippage” kind of pointless. (blog.rated.network)
  • And let’s not kid ourselves--“private routing” isn’t the magic solution here. A study from 2025 revealed that there were thousands of sandwich events happening even on private paths! Plus, there was noticeable user churn after the first-time attacks. This shows that just switching up an RPC isn’t enough to wipe out the risks. (arxiv.org)

The Risk of Waiting Too Long

  • Just think about it: if you mess up by even 10 basis points on a $50M monthly swap flow, that's a silent leak of $50,000--before we even get into the costs of failed swaps and the churn of support. According to some OFA research, using auction-enhanced routing can net you an improvement of about 4-5 basis points. If you don’t utilize this, that spread is just waiting for searchers and builders to snatch it up. (arxiv.org)
  • The longer you stick with public mempool routing, the more likely you are to see your users abandon ship. There's solid empirical data showing that when users get hit by sandwich attacks, they tend to migrate or churn away. Plus, the media is constantly pointing out that Ethereum sandwich losses are racking up in the millions each month--your users and competitors are definitely noticing this. (arxiv.org)
  • And don’t count on quick protocol upgrades to save you. The enshrined PBS (ePBS) is on its way to mainnet, but it’s not something you can just flip on today. You’ve got to plan for the current MEV-Boost ecosystem for the upcoming product cycles. Teams that claim to be “ePBS-ready” will still need OFAs, private routing strategies, and hook-level fixes to really capture that price improvement when ePBS finally arrives. (blog.ethereum.org)

7Block Labs’ Layered MEV Defense for DeFi

At 7Block Labs, we’ve put together a solid defense-in-depth strategy that really hits home. Our approach blends together protected order flow, intent-based execution, and AMM-level controls. The goal? Delivering real, measurable ROI instead of just putting on a show with “security theater.”

Layer 0: Baseline Telemetry and ROI Model

  • Instrument “Effective Price Improvement” (EPI): Let’s compare on-chain execution with pre-trade quotes, breaking it down by venue attribution--think AMM versus intent auction. We also want to keep rebates separate. It’s a good idea to use OFA benchmarks (bp uplift) to set SLOs for each pair and chain. Check out the details in this paper: (arxiv.org).
  • Track Sandwich Fingerprints: We should keep an eye on sequential pool interactions, deltaTick spikes, priority fee patterns, and backrun traces. To stay ahead of the game, let’s maintain a watchlist for builders and relays using Rated/EF data along with Flashbots SSE feeds. Dive into more about this here: (blog.rated.network).

Layer 1: Protected Order Flow by Default (No Code Freeze Needed)

  • Flashbots Protect + MEV-Share: This combo routes your swaps through a MEV-Share Node while keeping things pretty private. By default, only pool/pair addresses and transaction hashes are shared. Plus, 90% of the backrun value gets refunded, which is pretty cool. You can even customize privacy for those high-value orders. Check it out here.
  • MEV Blocker RPC Profiles: When dealing with consumer traffic, you'll want to stick with the /fast option. If you’ve got sensitive transactions like launches or whale redemptions, switch it to /fullprivacy. And if you're after both rebates and revert protection, go with /noreverts. Builders included in this are Flashbots, Titan, Builder0x69, bloXroute, and Beaver Build. Just a heads up on the 0.1% reorg edge case--private routing isn’t foolproof. More info can be found here.
  • Practical Integration Detail: Just so you know, starting November 17, 2025, there will be some changes to Protect RPC. This means you'll need to sign your eth_sendPrivateTransaction requests using X-Flashbots-Signature. It’s a good idea to standardize on relay.flashbots.net to keep everything running smoothly. You can also tune rate limits and auctionTimeout settings. For a deeper dive, visit this link.

Example (JS/ethers): Force Private Settlement for a High-Value Swap

In this example, we’ll walk you through how to enforce a private settlement for a high-value swap using JavaScript and the Ethers library. This method ensures that your transaction remains discreet and secure.

Prerequisites

Before we dive in, make sure you have:

  • Node.js installed on your machine.
  • A basic understanding of JavaScript and Ethereum.
  • The Ethers.js library, which you can add to your project by running:
npm install ethers

Setting Up

First, let’s set up our environment. Here’s a quick rundown of what you need to do:

  1. Import the Ethers library at the top of your JavaScript file:

    const { ethers } = require("ethers");
  2. Connect to an Ethereum provider (like Infura or Alchemy):

    const provider = new ethers.providers.InfuraProvider("mainnet", "YOUR_INFURA_API_KEY");
  3. Create a wallet instance with your private key:

    const wallet = new ethers.Wallet("YOUR_PRIVATE_KEY", provider);

Private Settlement Logic

Now that we’re set up, it’s time to create the logic for our private settlement. We want to ensure that our swap is executed securely. Here’s how to do it:

  1. Define your swap parameters:

    const swapAmount = ethers.utils.parseEther("10"); // Amount to swap
    const recipientAddress = "RECIPIENT_ADDRESS";
    const contractAddress = "SWAP_CONTRACT_ADDRESS";
  2. Create a transaction object:

    const tx = {
        to: contractAddress,
        value: swapAmount,
        gasLimit: ethers.utils.hexlify(100000),  // Set gas limit
        nonce: await wallet.getTransactionCount(),
    };
  3. Sign and send your transaction:

    const signedTx = await wallet.signTransaction(tx);
    const txResponse = await provider.sendTransaction(signedTx);
  4. Check the transaction status:

    const receipt = await txResponse.wait();
    console.log(`Transaction hash: ${receipt.transactionHash}`);

Wrapping Up

And there you have it! With these steps, you can force a private settlement for a high-value swap using JavaScript and Ethers.js. Just make sure to replace placeholders with your actual values.

Feel free to reach out if you’ve got questions or need further assistance! Happy swapping!

import { Wallet, providers } from 'ethers';
import { FlashbotsBundleProvider, FlashbotsTransactionResolution } from '@flashbots/ethers-provider-bundle';

const auth = Wallet.createRandom();
const provider = new providers.JsonRpcProvider(process.env.L1_RPC);
const fb = await FlashbotsBundleProvider.create(provider, auth);

const tx = {
  to: process.env.SWAP_ROUTER,
  data: process.env.CALldata,      // pre-simulated swap call
  maxFeePerGas: '0x' + (30n * 1_000_000_000n).toString(16),
  maxPriorityFeePerGas: '0x' + (2n  * 1_000_000_000n).toString(16),
  type: 2
};

const resp = await fb.sendPrivateTransaction({ transaction: tx, signer: Wallet.fromMnemonic(process.env.MNEMONIC) }, { maxBlockNumber: (await provider.getBlockNumber()) + 5 });

const res = await resp.wait();
if (res === FlashbotsTransactionResolution.TransactionIncluded) console.log('Included via Protect');

This respects the signed private-transaction requirement and keeps things off the mempool radar, all while making sure we stick to non-zero tips as per Protect guidance. Check out more details here.

Layer 2: Making Execution Intent-Based (Getting MEV Back to Users)

  • UniswapX: It’s all about gas-free, auction-based fills with some cool per-chain auction mechanics in play (like RFQ for exclusive Dutch auctions on Ethereum, and open Dutch ones on Arbitrum). The neat thing here is that fillers compete against each other, which means you get MEV as price improvements. Plus, if swaps go south? No worries; it won’t cost you a dime. So, if you’re dealing with big or unpredictable pairs, integrating UniswapX can really help cut down on slippage and shift the MEV advantage from the bad guys back to you. Check out the details here.
  • CoW Protocol: This one uses batch auctions with uniform clearing prices, which totally eliminates sequencing issues within a batch and puts a stop to those pesky sandwich attacks. For even more privacy and potential rebates, pair it with the MEV Blocker OFA. You can dive into more about it here.
  • Uniswap Wallet “Swap Protection”: If the wallet UX is under your control, make sure to keep swap protection turned on by default (it routes to Protect). This simple step can really trim down public mempool exposure for retail flows. Want to know more? Check it out here.

Layer 3: AMM-level Mitigations (Uniswap v4 Hooks)

  • Anti-sandwich fee hooks: These hooks have got your back by increasing fees on the fly when deltaTick indicates there's a risk of sandwich attacks. Several hooks in v4 are implementing these neat quadratic fee curves within the beforeSwap and afterSwap processes, making it tough for attackers to pull off sandwiches while keeping regular swaps low-cost. Just a heads-up though--make sure to keep an eye on audits! OpenZeppelin’s review of the v4 hooks revealed several high and critical issues back in 2025. (ethglobal.com)
  • Call/batch auction hooks: These hooks are pretty clever! They utilize hyperbolic call auctions or something called “uniform price” settlement in a tight timeframe to level the playing field, effectively countering any ordering advantages without needing oracles. (ethglobal.com)
  • Governance runway: The Uniswap Foundation’s Hook Design Lab is on a mission! They’re putting funds into creating production-grade policy orchestration, covering essential aspects like KYC, MEV protection, and dynamic fees to standardize how hooks come together. So, keep that in mind when planning any upgrades against this new interface. (uniswapfoundation.org)

Example (v4 Hook Sketch): Increase Fee on Abnormal Tick Jump

function beforeSwap(address, PoolKey calldata key, IPoolManager.SwapParams calldata params, bytes calldata) 
  external returns (bytes4, BeforeSwapDelta, uint24 hookFee) 
{
    int24 currentTick = getTickFromSqrtPrice(poolState[key].sqrtPriceX96);
    int24 dt = currentTick - poolState[key].lastTick;

    // quadratic fee growth on abnormal jumps
    uint24 base = 5; // 5 bps
    uint24 maxf = 60; // 60 bps cap
    uint24 dyn = uint24(min(uint256(base) + (uint256(abs(dt))**2)/1e4, uint256(maxf)));

    poolState[key].lastTick = currentTick;
    return (this.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, dyn);
}

This pattern is designed to penalize those outlier price moves that are probably linked to sandwich attacks, all while keeping Gas optimization in check (no external calls involved). Just a heads up, make sure to conduct audits and gas profiling before going live.

Layer 4: Transaction-level guardrails

  • Tight slippage + short deadlines: Make sure your slippage bands are specific to each pair and dial them down during those wild market swings. Stick to deadlines of about 60 to 120 seconds. You can also use the sqrtPriceLimitX96 bounds on v3/v4 paths to avoid those pesky pathological fills.
  • Revert protection: To give users a smoother experience, set defaults to the Protect/MEV Blocker endpoints with revert protection (like /noreverts or /fullprivacy) for those sensitive transactions. Check it out here: mevblocker.io.
  • Builder diversity: Don't get too cozy with just one builder; use the Protect settings to add more builders into the mix. Keep an eye on relay health and builder market share every week to stay informed. More details can be found here: collective.flashbots.net.

Layer 5: Monitoring and Incident Response

  • Stream Hints: Make sure to subscribe to the MEV-Share SSE so you can keep an eye on any cluster activity related to your pairs. If things start looking a bit off, go ahead and auto-escalate to /fullprivacy, and temporarily turn off any nonessential hints until the busy period passes. You can find more details here.
  • Sandwich Meter SLOs: Aim to keep it under 0.10% for swaps that get flagged as sandwiched. You can track this using backrun clustering and tick-spike heuristics. If you notice that you're breaching the SLO, switch over to intent-only routing for a bit and up those hook fees.
  • Reporting: It's a smart move to show “MEV rebates credited” and “price improvement vs baseline” in your app. This not only highlights the value you're providing but also helps keep end-user slippage in check.

what “good” looks like in metrics, with sources

  • Price Improvement: Order-flow auctions like CoW and UniswapX show they can really boost prices, with studies showing a solid 4-5 basis points uplift in their sample sets. So, your goal? Aim for a 3-6 basis points improvement over your pre-integration baseline on eligible pairs. You can check out the details here.
  • Attack Surface Reduction: With tools like Protect/MEV-Share and MEV Blocker, we can keep sensitive info (think slippage) under wraps, only letting out a few partial hints. If you're dealing with high-value orders, make sure to run /fullprivacy (no rebates involved). Your KPI here is to cut down public-mempool routing to single digits for swaps over $10k. More info can be found here.
  • Builder-Aware Resilience: Since around 90% of blocks come from MEV-Boost and builder concentration is still a thing, the best route is to bring MEV in-house with OFAs and hooks. Plus, diversify your builders and stick to private routing. Your KPI? Aim for zero user-visible “sandwich loss” incidents during known volatility moments (like CPI prints or token listings). Dive deeper into this here.
  • Reality Check: Keep in mind that private routing isn’t foolproof. MEV Blocker has even noted that around 0.1% of transactions could leak during reorgs. Plus, recent studies have shown sandwiches can pop up on private channels too, which means we need to stay layered with defenses (intents + hooks + private). Your KPI here is to make sure fallback policies kick in automatically during those reorg spikes. Check more about this here.

Emerging Practices to Track (Next 2-3 Quarters)

  • ePBS (EIP‑7732) and Inclusion Lists (EIP‑7547): Keep an eye on EF timelines for Glamsterdam, and design things to work smoothly with “OFA + ePBS.” While inclusion lists do boost censorship resistance, they won’t completely wipe out sandwich incentives on their own. Check out more details here.
  • Uniswap v4 Ecosystem: Get ready for standardized “policy orchestration” frameworks, plus a more extensive look into anti-MEV hooks. Make sure to set aside time for migration tests and hook audits before you flip the switch on dynamic fees in production. More info can be found here.

How 7Block Labs Gets Things Done (Pragmatic, Procurement-Ready)

  • Design and Integration

    • We kick things off by taking a close look at your current routing and swap paths. From there, we roll out changes in stages: starting with Protect/MEV-Share, then adding MEV Blocker endpoints for specific groups, and finally integrating UniswapX/CoW on a pair/chain basis.
    • For Automated Market Makers (AMMs) or any app-specific pools, we set up and audit v4 anti-sandwich hooks that come with controlled gas overhead.
    • We provide a comprehensive builder policy that includes a list of allowed relays/builders, auction timeout guidelines, and hint templates tailored to different order-size buckets. (docs.flashbots.net)
  • Tooling and Automation

    • We offer pre-trade simulations alongside post-trade reconciliation, complete with “sandwich meter” dashboards to keep you in the loop.
    • Privacy levels can step up automatically, thanks to MEV-Share SSE signals and pool-level anomaly detectors. (docs.flashbots.net)
  • Governance and Compliance

    • We provide detailed runbooks for incident responses, whether it’s a reorg spike or a builder outage.
    • Our process includes quarterly reviews to keep up with Ethereum Foundation timelines regarding ePBS and inclusion lists. (blog.ethereum.org)
  • Wallet/Frontend: Let’s make it so that Protect RPC is the default setting. Also, we should add a “Stealth Mode” toggle for those occasions when someone needs to make high-value swaps. Just a heads-up: the signed-private-tx requirement kicks in after November 2025. (collective.flashbots.net)
  • Aggregator: For orders that go above a volatility-adjusted threshold, we’ll route those to UniswapX. If they don’t meet that threshold, we’ll send them to the AMM using Protect RPC. On Arbitrum, let's put more focus on open Dutch auctions since they decay pretty quickly. (docs.uniswap.org)
  • DEX/Pool operator: We need to include a deltaTick-sensitive fee hook and set some sqrtPrice limits. Additionally, let’s run a canary pool with call-auction settlement during peak volatility events, like when listings drop or during oracle recalculation windows. (ethglobal.com)

Financial Impact (ROI You Can Showcase)

  • Example Math: Let's break it down. If you're dealing with a $100M monthly volume, a 4 basis point improvement translates to an extra $40,000 each month back into users' pockets. Plus, if you manage to capture 30% of backrun rebates, you’ve got another revenue stream that depends on your flow mix. The cool thing about MEV-Share is that it defaults to refunding users while also rewarding validators and searchers. You can really fine-tune those distributions based on your business model. Check it out here: (arxiv.org).
  • Operational Savings: Think about this--private routing with revert protection means no more failed transaction gas for your protected flows. And with UniswapX gas-free trades, the costs get shifted to fillers. Your finance team will definitely notice these changes in metrics like LTV:CAC and a reduction in support tickets. More details can be found here: (docs.uniswap.org).

How we work together

  • Architecture and integration: Our awesome DeFi development services team is on it! We’re managing Protect/MEV-Share, MEV Blocker, UniswapX, and CoW wiring, rolling things out in stages to keep everything smooth.
  • AMM and hooks: Over in our smart contract development group, we’re busy implementing and auditing Uniswap v4 hooks that help resist sandwiches. Plus, we’ve got test harnesses and gas profiling in the mix to make sure it all runs like a well-oiled machine.
  • Security and audits: When it comes to keeping things secure, we do independent reviews through our security audits. We focus on hook invariants and potential failure modes, so you can rest easy knowing your project is in good hands.
  • Protocol and integration: For DEXs and various venues, our DEX development and blockchain integration practices are all about ensuring smooth routing and data pipelines, no matter which chains you’re working with.
  • Full-stack support: If you’re diving into intent systems or cross-chain routing, we’ve got your back! We’ll sync up with your roadmap through our custom blockchain development services, web3 development, and cross-chain solutions.

Appendix: Why the Stack Works (Engineering Rationale)

  • Market Structure: Right now, with MEV-Boost taking the lead and a few builders calling the shots, exclusive order flow (EOFO) and order flow auctions (OFAs) are pretty much the only ways to turn potentially harmful MEV into better prices for users. So, you gotta plan for off-protocol PBS for at least the next round of products, and make sure it's "ePBS-compatible" later on. Check out more about it here.
  • Privacy Model: The MEV-Share setup does a great job at keeping data leaks to a minimum (think hash + pool hints right off the bat). Plus, with the MEV Blocker, you get OFA that lets you tweak privacy settings and clearly define endpoint semantics. This approach directly benefits major builders, speeding up inclusion times while steering clear of the public mempool. Dive deeper into it here.
  • Execution Model: Intent auctions, like UniswapX and CoW, are all about rewarding those who provide the best execution. Using batch or Dutch mechanics helps shrink the window for adversaries, and uniform clearing prices take a chunk out of sequencing profits. For more details, take a look at the docs here.
  • AMM-Level Friction: The new v4 hooks really shake up the economics for attackers. If someone tries to sandwich and their delta (dt) goes past a certain point, dynamic fees can totally wipe out their advantage. And those call auctions? They take away any ordering leverage completely. This is solid, auditable Solidity--no pipe dreams here! Learn more about it here.

Caveats (so you don’t get surprised)

  • Private != perfect: Just a heads-up--reorgs and edge-case leaks are still a thing. Research has shown that some private-path sandwiches can happen. So, make sure to set up monitors and consider automatically ramping up privacy levels during high-stress situations. Check it out here: mevblocker.io.
  • Hooks need audits: Recent audits of v4 hooks turned up some high and critical issues, so don't even think about shipping any MEV hooks that haven’t been audited. You can find more info on this at openzeppelin.com.
  • Config drift is real: Keep an eye on your Protect/MEV-Share settings and make sure they're up-to-date with the latest signing and endpoint requirements. Neglecting stale configurations can silently disable your protections, and that's not something you want. For further details, check out collective.flashbots.net.

If you're interested in having 7Block Labs set up this stack from start to finish--complete with clear KPIs, dashboards, and a pilot that’s live in production--just kick things off here: Book a 30-Day DeFi MEV Pilot.

Like what you're reading? Let's build together.

Get a free 30-minute consultation with our engineering team.

7BlockLabs

Full-stack blockchain product studio: DeFi, dApps, audits, integrations.

7Block Labs is a trading name of JAYANTH TECHNOLOGIES LIMITED.

Registered in England and Wales (Company No. 16589283).

Registered Office address: Office 13536, 182-184 High Street North, East Ham, London, E6 2JA.

© 2026 7BlockLabs. All rights reserved.