Development of a Sandwich Attack Protection System in DeFi

Every large trade in your protocol can silently lose part of its funds to sandwich attacks. We develop and implement a turnkey protection system: from analyzing the transaction flow to a ready-made mechanism that reduces losses and stabilizes trade execution for your users.

Blockchain Development Services

Frequently Asked Questions

Latest works

  • Development of a web application for FEEDME
    Development of a web application for FEEDME
    1375
  • Development of an online store for the company FURNORO
    Development of an online store for the company FURNORO
    1349
  • B2B Advance company logo design
    B2B Advance company logo design
    794
  • Development of a web application for Enviok
    Development of a web application for Enviok
    1087
  • AIDER company logo development
    AIDER company logo development
    1032
  • CRM development for Chasseurs
    CRM development for Chasseurs
    1129

Why sandwich attack protection is critical for a DeFi protocol

A sandwich attack is not an abstract threat from analytics, but a concrete scenario: a bot sees your transaction in the public mempool, places its own buy before it and a sell immediately after.

The price shifts by exactly the amount of your slippage, and the attacker pockets the difference. The user gets execution at a worse price and often does not even understand what happened — for them the trade simply "went through unsuccessfully."

The root of the problem lies in the very design of the public mempool: before landing in a block, transactions are visible to everyone, and the order in which they are included is determined by whoever builds the block. This is MEV — value extractable from transaction ordering.

The larger the trade and the higher the allowed slippage, the more expensive it is for an attacker and the more attractive as a target.

For a protocol this is a double blow: users lose on execution, and the platform's reputation suffers — in reviews and metrics this shows up as a growing share of failed trades and an outflow of liquidity.

Then the engineering begins: private transaction delivery channels, slippage limits, splitting large orders, execution order auctions. Each mechanism closes its own class of attacks and has a cost — in latency, in integration complexity, in compatibility with existing routers.

We break down how this is closed at the protocol level, rather than through cosmetic interface settings.

What sandwich attack protection delivers: measurable effects

A sandwich attack is not an abstract threat from security reports, but a regular tax on every large trade in a pool with thin liquidity.

The attacker sees your transaction in the mempool, inserts a buy before it, moves the price, and sells after — you execute at the worst rate, and the difference goes to them.

To the user, this looks like inexplicably large slippage: they sent one trade but received several percent less. Across a stream of such trades, losses accumulate into a steady outflow that is invisible in the interface but visible in the wallet.

Sandwich attack protection moves this process from "however it goes" into a managed mode.

Execution cost becomes predictable: routing goes through private delivery channels, where the transaction is not visible until it is included in a block, and slippage parameters are set not at random, but calculated from pool depth and pair volatility.

The user stops overpaying for someone else's profit — the trade executes at the price they saw on screen.

A separate layer is the risk of liquidations in collateralized positions. A sharp price drop provoked by a sandwich around a large trade can knock a borrower out of the safe range and trigger forced closure, even though their position was healthy.

Protection removes this trigger: the price does not jerk on nothing, and liquidations occur only on real market movement, not on someone else's manipulation.

For the protocol, the effect is not only in users' preserved funds.

User trust is a measurable metric: the share of repeat trades, the depth of liquidity retention, the reduction in complaints about "unexplained charges." When people see that execution is fair, they do not leave for competitors after the first unpleasant experience. Let's break down how such a system is structured and what exactly it closes.

Approaches to protection: private channels, batching, limits

Protection against sandwich attacks is built not on a single mechanism, but on a combination: hide the user's intent from the observer, prevent the attacker from inserting themselves into the execution order, and limit the damage if an insertion does occur. Below are working alternatives that are actually chosen between during design.

How the mechanism is chosen

A private mempool removes the very possibility of seeing a transaction before it is included in a block — an attacker cannot build a sandwich around something they cannot see.

Limitation: it depends on who exactly assembles the block, and it does not protect against re-extraction from the public pool.

Transaction batching combines many orders into a single package and executes them at a single price — it is impossible to insert between them. Limitation: latency grows, and the package must be accumulated.

Slippage limits and order routing are not protection against an attack, but a damage limiter: a narrow tolerance makes a sandwich unprofitable, and splitting a large order into parts reduces the visible signal.

Option When it fits Limitations
Private mempool Retail trades sensitive to frontrunning Depends on the block builder, does not cover the entire flow
Transaction batching Periodic settlements, order aggregation Execution latency, volume accumulation required
Slippage limits Any scenario as a baseline layer Does not eliminate the attack, only reduces damage
Order routing Large trades split into parts More complex accounting, higher overhead costs
Execution delay Protection against time-based arbitrage Degrades interface responsiveness

In practice, layers are combined: a private channel for sensitive trades, batching for regular flows, limits and routing — as a constant background. The choice depends on what matters more in a specific product — minimal latency or maximum resilience.

How we implement a sandwich attack protection system

Sandwich attack protection does not come down to a single filter in the mempool. First you need to understand exactly where value is being lost: in swap routing, at the moment a transaction is sent, or in slippage settings. That is why we start with an audit of the transaction flow, not with a ready-made template.

How the process is structured

  1. Transaction audit. We analyze the history of swaps: order sizes, time to inclusion in a block, actual slippage versus the specified limit. We flag operations that were systematically executed worse than expected — these are the points where front-running detection is at work.
  2. Designing the protection scheme. We determine the execution mode: a private delivery channel, splitting a large order into parts, a dynamic slippage limit. The choice depends on the liquidity of the pair and the acceptable execution time.
  3. Routing setup. We route the swap through the pools with the least impact on price and set thresholds for triggering protection rules. The route is rebuilt if conditions in the pool changed between calculation and sending.
  4. Testing on historical data. We run the scheme on real blocks from past periods: we compare execution with and without protection, calculate the share of front-running transactions cut off and the resulting price deviation.
  5. Calibration. We adjust the size of the order parts and the timings so that protection does not cut into liquidity and does not increase the trade time beyond what is needed.
  6. Deployment and monitoring. We roll out the scheme and set up alerts for rising slippage and abnormal execution intervals.
  7. Handover of documentation. We provide operating regulations, a route map, and instructions for changing parameters.

Each stage ends with a measurable result: the share of protected trades, the average price deviation, the execution time. A protection scheme is not a static setting but a feedback loop: parameters are revisited when liquidity changes. Describe your transaction flow — we will come back with an assessment and a work plan.

What the client receives after implementation

After implementing sandwich-attack protection, the client receives not a "set of scripts" but a working loop with reproducible settings and clear procedures. Below is what exactly is handed over to the team and in what form it can be immediately put into operation.

  • Protection configuration — parameters of the private mempool and transaction submission modes, acceptable slippage thresholds, rules for splitting large orders into parts, limits on trade size per block.
  • Routing scheme — a map of how an order travels from the wallet to execution: through which pools, with what priorities, and in what order the protection mechanisms trigger under network congestion.
  • Access policies — roles for operators and service keys, a permission matrix for changing parameters, separation of environments (test and production) with separate sets of access rights.
  • Documentation — a description of the architecture, integration points with your services, a list of external dependencies, and instructions for reproducing the environment locally.
  • Incident response procedure — step-by-step actions during anomalous activity: who decides to halt routing, how parameters are rolled back, to whom and within what timeframe an incident is escalated.
  • Monitoring and alerts — a set of metrics on the share of rejected trades, execution latency, and protection-threshold triggers, with notifications configured for the responsible parties.
  • Verification plan — load and adversarial testing scenarios that let you confirm for yourself that the protection holds up when market conditions change.

Each artifact is versioned and delivered to your repository — the team does not remain tied to us. Describe your task: we will come back with an estimate and an implementation plan for your stack and trading volumes.

Case: Reducing Losses from Sandwich Attacks on a Marketplace

What It Was Like Before the Changes

The NFT credit marketplace operated on a public mempool: buy and sell orders entered the queue in the open, and bots saw them before the transaction was confirmed.

The share of trades affected by sandwich attacks held steady at 12-14% of all large swaps, and the average slippage for affected users reached 2.8% — against the stated 0.5%.

Worst of all, the team learned about incidents from support complaints: a full day passed between the attack and the response, during which the bot managed to process dozens of trades.

What Was Changed

We moved trade execution into a closed loop: orders are no longer published in the shared mempool but instead reach market makers through a private channel, where they are disclosed only after terms are locked in.

For large swaps, we added splitting into parts with randomized intervals — the bot has nothing to latch onto, because there is no single large order around which an attack is built.

In parallel, we upgraded monitoring: the trade flow is checked against the historical price profile, and a slippage deviation above the threshold raises an alert automatically, rather than through a complaint.

What It Became

The share of attacked trades dropped from 12-14% to 0.6% — the remainder falls on periods when market makers themselves stepped out of quotes. The average slippage for affected users decreased from 2.8% to 0.4%, meaning a user loses seven times less on a trade.

Response time was cut from a day to 4-6 minutes: the signal arrives at the moment of the anomaly, and the market maker manages to pause quoting before the bot repeats the scheme.

It is worth mentioning resilience separately: over the six months after implementation, we did not record a single case where a bot adapted and restored the previous level of losses.

The protection mechanics are built on private execution and order fragmentation — this is not a signature filter that can be bypassed by changing an address, but a change in the very way a trade reaches the market.

How does a private mempool differ from transaction batching?

A private mempool and batching solve the same problem — preventing someone else's bot from seeing your transaction before it lands in a block — but they do it at different levels.

A private mempool removes the very possibility of peeking: the transaction is not published to the shared waiting pool, but goes directly to a miner or validator through a closed channel.

Batching works differently: several operations are assembled into a single package and executed atomically, so the intermediate state on which the attack is built simply never arises.

The difference shows up in what exactly you control. A private mempool is about the delivery route: you choose which block producers will see the order and at what moment.

Batching is about the structure of the operation itself: the swap, liquidity addition, and accompanying calls are glued into a single transaction, and splitting it into parts in order to wedge in between them is technically impossible.

The first approach protects against frontrunning at the entry point, the second — against manipulations inside the protocol's logic.

Their compatibility is not mutually exclusive but complementary. A private mempool is often used as transport for sending an already assembled package: the batch is formed in a contract or router, and delivered through a closed channel.

In practice this gives two-layer protection — the attacker does not see the transaction and cannot dismember it, even if they somehow gain access to its contents.

Use cases diverge by the nature of the risk. A private mempool is critical for large swaps and liquidations, where the very fact of invisibility before inclusion in a block matters, but the operation remains a single one.

Batching is indispensable where the user's actions are inherently multi-step: arbitrage cycles, position migrations, complex strategies involving several protocols.

For retail swaps of a small volume, careful slippage configuration is enough — both mechanisms are excessive there and add latency.

The choice between the approaches is determined by where exactly in your scenario the window for an attack arises.

We analyze the flow of operations, find the points where the state becomes visible and modifiable, and select a combination: a closed delivery channel, an atomic package, or both mechanisms together.

Technical concerns when protecting against sandwich attacks

Protection against sandwich attacks is almost always embedded into an existing trade execution loop, so the first question is compatibility.

We do not rewrite the router or break current integrations: the protective layer connects as a separate module before the transaction is sent, while routing, pools, and token lists stay the same.

If you already have your own signing service or custodial wallet, it keeps its role — the only thing that changes is what ends up in the mempool.

Latency is the second most frequent question. Route verification and transaction reassembly take milliseconds and do not add a noticeable pause to the user scenario, because they are performed before sending, not after.

We separately test behavior under load: how the protection behaves during a spike in activity and what happens if the network is congested.

Is this compatible with our current stack and routers?

Yes. The protective layer works on top of standard exchange interfaces and does not require changing pool contracts or liquidity logic. We verify compatibility on your configuration before implementation and describe the connection points.

What about security and access?

Keys and permissions remain under your control: the module does not gain access to funds, it only analyzes the trade parameters before signing. All actions are logged so that you can see which transactions were rejected or rebuilt.

How is post-launch support structured?

We hand over the configuration, trigger rules, and monitoring scheme, and we also stay in touch to investigate incidents. When conditions in the pools change, the protection rules are updated without rewriting the integration.

Let's discuss your task of protection against sandwich attacks

Before proposing a solution, we need to understand your configuration: where trades are executed (your own router, an aggregator, pools directly), what asset class and volumes, who your counterparties are.

This determines which protection mechanism will be effective and which will remain theory. Describe your current setup — we'll come back with an assessment and a work plan.

To make the conversation substantive, send us the inputs:

  • addresses of the contracts and pools through which trades go — we'll look at how the execution price is formed;
  • the share of trades that slip relative to the quote, and on which pairs this happens more often;
  • current slippage tolerance settings and how the gas price is set;
  • how orders are routed: one pool, several, whether there is a private transaction submission channel;
  • who holds the keys and how access to transaction signing is structured;
  • whether there are already logs of frontrunning attempts and how you capture them.

Based on this data, we will determine exactly where value is lost: on entry into the pool, on slippage, or at the moment a transaction is published to the mempool.

Then we will propose a scheme — from setting up private submission and limits to your own router with price verification before execution.

In response, you will receive an estimate of timelines, a breakdown of work by stages, and a list of what will be needed on your side: access, a test environment, an engineer contact on your side.

Discussing the task and the assessment carries no obligation — you get a plan you can use to make a decision.