MEV attack detection system: protecting DeFi from sandwich and front-running

Sandwich attacks and front-running quietly eat into DeFi protocol profitability while transactions look normal. We set up a turnkey MEV detection system: we identify leakage points, deploy online monitoring, and hand over procedures. The share of unprofitable trades drops severalfold, and decisions are made based on data, not guesswork.

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

MEV detection: where DeFi protocol protection breaks

MEV detection begins where a user submits a swap of a large amount and sees confirmation — but it executes at a price worse than the one at the moment of submission.

The transaction sits in the pending queue for some time, and while it is there, its parameters are open: a third party places their buy before it and sell immediately after, taking the difference.

This is a sandwich attack; its close relative, front-running, triggers even earlier, when another agent takes the same position in the block first.

The size of the loss rests on the slippage tolerance that the user set themselves. The attacker tunes the offset so that the trade is not canceled and passes exactly at the tolerance boundary — therefore neither errors nor warnings appear in the interface.

On large orders this is not a one-off failure but a systematic leak: the share of trades executed worse than the quote accumulates across the protocol and grows with volume.

Protection breaks where it is built on final account state.

The order of trade execution within a single block is the only place where the attack is at all distinguishable: the victim transaction is sandwiched between two third-party trades, often from the same address or related addresses, and pool reserves between them are shifted in one direction.

Until this slice is reconstructed step by step, detection records only the result — the user's already lost funds.

Next we break down how this is closed: from block-by-block analysis to rules that flag the bundle at the moment it appears, rather than based on the results of a week.

Effect of MEV detection: what changes in metrics

MEV detection is built into the transaction path itself, so protocol metrics are visible not in post-mortem analysis but at the moment a decision is made.

Three values are worth watching: how quickly the node reacts to a suspicious transaction, what share of attempts do not reach profit extraction, and which class of failures disappears from statistics entirely.

Reaction time to a suspicious transaction

The critical boundary is the interval between a transaction appearing in the mempool and its inclusion in a block.

While protection lived in offline analysis, reaction was measured in hours: pool balance discrepancy was noticed after the bundle had already executed, and there was no way to return funds.

Checking operation ordering before block assembly fits within the same interval in which the validator selects block contents — reaction compresses from hours to seconds.

Share of repelled attacks and the eliminated class of failures

The second metric is the share of sandwich and front-running attempts that finish without profit for the attacker.

Configured rules cut off most such bundles before execution: the swap goes through at the expected price, slippage stays within declared bounds, and the number of trades unfavorable to the user falls in protocol statistics.

Along with this, an entire class of failures goes away — cascading liquidation triggers and quote desync after a single manipulation stop recurring.

The scale of losses created by such failures is regularly estimated in open analytics (Flashbots, aggregated data on MEV losses): comparing industry figures with one's own statistics before and after implementation shows the effect concretely.

Protection modes: online monitoring, post-mortem analysis, hybrid

Mempool determines the order in which trades enter the block, and who gets the result depends on this order. Protection modes differ by intervention point: before block assembly, after it, or in two circuits at once.

The choice between them is determined by what is more critical — preventing an attack from occurring or accurately reconstructing the picture and presenting it to the counterparty.

Option When suitable Limitations
Online interception Active pools where execution order directly affects the user's trade outcome Operates by rules: non-standard routing through multiple pools bypasses the detector. A defensive trade may be one block late — trigger occurs, no effect
Post-mortem analysis Periodic execution quality control, audit of already assembled blocks Does not save a specific trade: records the fact and reconstructs the route
Hybrid scheme Pool with regular arbitrage flow, both control and analysis needed Two circuits require a coordinated address registry, otherwise discrepancies in reports
Manual log analysis Disputed episodes, claim preparation, complex multi-step schemes Speed limited by people and does not scale to flow

Limitations of the online scheme

The detector compares transaction characteristics with a normal execution profile, so an attack spread across multiple protocols passes below threshold. Lowering the threshold produces false positives and extra defensive transactions, while raising it produces misses.

Latency is also critical: action must occur before block assembly, otherwise the defensive transaction only adds costs.

When post-mortem analysis is enough

If transaction flow is moderate and the pool is not a target of arbitrage bots, log analysis fully covers the task. It provides the trade route, participating addresses, and call sequence — enough to rebuild pool parameters and close the scheme for the future. Monitoring after the fact is connected when proof is needed, not interception.

Implementation stages: from transaction flow audit to handover

Implementation goes from monitoring to automation: first we capture the real picture of transaction flow, then formalize it into rules, and only then enable reaction. This order eliminates false positives at launch — the detector does not touch legitimate market maker activity.

Audit and rule scheme

  1. Audit of transaction flow and entry points. We collect mempool and confirmed block data, mark exactly where user transactions become visible to third parties: public mempool, private relays, own nodes. We record execution routes passing through your protocol.
  2. Designing the rule scheme. We describe detection as a set of checks: gas increase in the same block before a user transaction, price discrepancy between signature and execution, paired operations around a single transaction. We agree on sensitivity thresholds to separate attack from ordinary volatility.
  3. Setting up alerts and auto-reaction. We determine what happens on trigger: log entry, on-call notification, pause for swap execution, or transaction rejection under a specified condition.

Configuration, verification, acceptance

  • Verification on historical data. We run rules over past blocks with already known attacks and calculate shares of caught and false positives. We calibrate thresholds by numbers, not by feel.
  • Acceptance tests. We reproduce sandwich and front-running scenarios on a test circuit with real gas parameters and measure time from detection to blocking.
  • Acceptance and handover. We hand over configuration, rule scheme, and regulations to the on-call shift: how to read alerts, what to escalate, how to change threshold without downtime.

What we hand over: configurations, rules, regulations

The handover package is not a folder with settings but a set of artifacts by which the on-call shift and your team work without us. We describe each rule so it can be verified, reproduced, and changed without reading code.

Configurations and schemes

  • Configurations of MEV pattern detection rules: thresholds by volume and number of attempts in a block, exception pool lists, “signal-only” mode or automatic blocking — with notes on what changes when threshold is tightened.
  • Route scheme: how transaction flow passes through the observer node, at what point a transaction copy is taken, what bypass paths exist, and what happens if one of them is unavailable.
  • Escalation map: who receives the signal and within what timeframe, which attack class requires immediate intervention, and which goes to scheduled analysis.
  • Verification report: reproduced sandwich attack and transaction front-running scenarios, expected and actual reaction, list of open discrepancies.

Regulations and access rights

  • Access rules for the on-call shift: roles, scope of rights, and separate circuits for changing thresholds and for manual address blocking.
  • Incident instruction: recording procedure, isolation of suspicious route, rollback of rule to previous configuration, alert template.
  • Change log: each edit with timestamp, author, and reason — so that six months later it is clear where the current threshold came from.

Case: how losses from sandwich attacks were reduced

A market maker with dense order flow operated in Uniswap pools across several networks at once: dozens of trading pairs, frequent quote rebuilds, part of flow went through aggregators.

Such a traffic profile makes the participant a priority target for sandwich bots — and protection was built for manual on-call duty, not for speed.

What it was before

Engineers reviewed mempool observer alerts after block confirmation: by reaction time, the attacking bundle was already in the block, and the trade executed at the extreme slippage tolerance value.

Share of trades at worst price within the block held at 8–9%, average reaction time — about half an hour. During this window, the bot managed to repeat the bundle on the same pair, and repeat attempts almost always succeeded: nothing in routing stopped them.

What changed after

Monitoring of unconfirmed flow was linked to block structure analysis rules: a pair of transactions in one pool around the client trade, mirrored reserve changes, slippage tolerance asymmetry.

Each such bundle is assigned a risk score, and by threshold the route switches to private order submission, while slippage tolerance narrows automatically. The engineer gets involved only in analysis of disputed cases, not every attack.

Reaction time dropped to 2–4 seconds — the detector triggers before transaction inclusion in the block. Share of trades executed at worst price fell to 1–2%: the remainder — large orders where route rebuilding is more expensive than slippage itself.

Over the quarter, over a thousand attempts were repelled, and the share of repeat approaches from the attacking side decreased several times over — bots leave pairs where the bundle consistently fails.

How online control differs from post-mortem analysis

MEV detection solves two different tasks — having time to prevent profit extraction and accurately reconstructing what happened. Hence two modes: online control and post-mortem analysis.

Online control looks at the queue of unconfirmed transactions and block contents at the moment of block assembly, so the decision is made on incomplete data and under a tight time limit.

Post-mortem analysis works with recorded history: the indexer goes through the chain, matches trades, transfers, and contract calls, and reconstructs the sequence without time constraint.

Criterion Online control Post-mortem analysis
Reaction before transaction inclusion in block based on confirmed data, with lag
Depth current block and pending transaction queue entire history: address links, trade chains, recurring patterns
Infrastructure continuous data stream and load headroom indexer and history storage, peaks non-critical
Result sandwich bundle does not execute evidentiary picture and rule tuning

In practice modes are not opposed. If the task is to prevent profit extraction in the moment, online control with fast rules based on coarse signs is enabled.

If it is necessary to investigate an incident, estimate volume, and reduce false positives — rely on post-mortem analysis, which refines thresholds and patterns for the online layer.

Technical concerns: false positives and load

False positives are a common reason MEV detector is taken out of operation: alert flow grows, trust in them falls, the on-call person stops reacting. Below are engineering answers to questions that come up before launch.

How are false positives filtered out?

A signal passes several independent checks. First cheap filters by block structure: transaction order, gas increase, pool reserve change. Then comparison with the pending transaction queue — was there a competing order before block inclusion.

We confirm when two signs match and profit is reproduced on simulation; the threshold is configured per specific pool.

What load will be placed on current infrastructure?

The indexer reads only confirmed blocks, the pending queue — via subscription, without constant polling. Simulation runs only for candidates that passed cheap filters: this is a fraction of a percent of total flow.

Storage grows linearly, old records are rolled up into aggregates, a separate node is not required for this.

What to do with non-standard attack schemes?

Some schemes do not fit the template: manipulation in several pools at once, liquidity added for one block, submission through closed channels. Such cases are caught not by rules but by behavioral address profile — deviation from its normal activity. We describe a new template as a rule after incident analysis, then it works automatically.

Is this compatible with already deployed protection?

Detection is passive: read-only data, without intervention in transaction flow or edits to contracts. There are no conflicts with existing protection tools at routing level — signals go to existing alert channels. Disabling comes down to stopping components: contract state did not change.

Let's discuss the task: what is needed from your side

To make the assessment substantive rather than evaluative, it is enough to prepare a few things for discussion. This saves the first pass: engineers immediately calibrate the detector to your real transaction flow instead of piecing together a picture from general words.

  • List of pools and pairs — contract addresses, network, pool type. It is used to build a profile of normal activity and anomaly thresholds.
  • Access to trade history — log export for a period or a read-only key to the indexer. Calibration is done on your data, not synthetic data.
  • Current protection scheme — private mempool, slippage limits, order splitting, relays. It is immediately clear what is already cut off and what passes through.
  • Reaction time requirements — how much time is allotted from signal to blocking: seconds on hot path, minutes for incident analysis.
  • Acceptance criteria — share of caught sandwich patterns, acceptable false positive rate, log retention depth.
  • Responsible persons on your side — incident on-call person and integration owner: who confirms the result and accepts the work.

Describe the task within these boundaries — we will return with an estimate and work plan.

It will include detector architecture, integration points into your services, acceptance procedure, and timeline for the first pass over your data: usually it takes one to two weeks, after which a measurable share of intercepted attacks and false positive rate on historical flow becomes visible.