Logo
New RPC users get 35% off their first monthView the offer
OnFinality Learn
Network & Protocol Guides11 min read

What Is MEV? Maximal Extractable Value Explained for Builders

A technical guide to maximal extractable value: how transaction ordering creates profit, how searchers, builders and validators interact, and how to measure and mitigate MEV exposure.

TL;DR

MEV, or maximal extractable value, is the profit that can be captured by choosing which transactions enter a block, in what order, and which are excluded. It exists because block producers control ordering and because pending transactions are often visible before inclusion. This guide explains the mechanism, walks through the main extraction patterns, and gives reproducible procedures for measuring your own exposure and reducing it. It separates documented protocol behavior from recommendations and from measurements you must run against your own infrastructure.

Definition and scope of maximal extractable value

Maximal extractable value (MEV) is the maximum profit obtainable from block production beyond the standard block reward and transaction fees, by including, excluding, or reordering transactions within a block. The term began as "miner extractable value" under proof-of-work, when miners controlled block contents. After Ethereum's move to proof-of-stake, validators hold that role, so the community adopted "maximal" to describe the same economic surface without tying it to mining.

MEV is not a single attack. It is a category of value that arises whenever ordering matters: decentralized exchange arbitrage, liquidations, sandwiching, NFT mint sniping, and backrunning oracle updates all fall under it. Some of it is benign market-making that tightens prices across venues; some of it directly transfers value away from ordinary users. The distinction matters when you decide what to mitigate.

This article covers the mechanism, the actor roles, runnable diagnostics you can execute against an RPC endpoint, and the tradeoffs of common mitigations. It does not publish benchmark numbers for any provider; where measurement is needed, the procedure is given so you can produce your own results.

  • MEV is value from ordering, inclusion, and exclusion, not from holding or staking alone.
  • It exists on any chain where a block producer controls transaction order and pending transactions are observable.
  • Exposure depends on your transaction type, slippage settings, and how you submit transactions.

Assumptions and prerequisites

You should be comfortable with transactions, blocks, gas, and the difference between a public mempool and a private transaction relay. Familiarity with an automated market maker (AMM) helps, because most user-facing MEV examples involve swaps whose price impact depends on ordering.

You need an RPC endpoint for read-only diagnostics. Any reliable endpoint works; if you are choosing one, the RPC endpoint guide covers what to evaluate, and RPC pricing explains how request volume maps to cost. For production workloads that need consistent latency, a dedicated node removes noisy-neighbor effects that can distort timing-sensitive measurements.

The mental model: ordering as a scarce resource

Think of a block as a sequence with a fixed capacity. Every transaction in it has an effect on shared state, and the effect of one transaction depends on what ran before it. A swap moves a pool's price along its curve; a liquidation changes a borrower's health; an oracle update changes what prices contracts see. Because order changes outcomes, the right to choose order is valuable.

In a simple model, a searcher identifies a profitable sequence, submits it as a bundle, and bids part of the profit to the block builder for inclusion. The builder assembles the most valuable block and passes a bid to the validator, who proposes it. The validator's guaranteed share comes from the bid; the searcher keeps the remainder. Competition drives bids up, so in highly contested opportunities most of the value can flow to builders and validators rather than to the searcher.

This is why MEV is sometimes called an invisible tax on users: the value is real, but it is paid through worse execution rather than a line item. The size of that tax depends on how much your transaction reveals about itself before it lands.

Actor roles: searchers, builders, validators, and relays

Searchers run algorithms over pending and historical data to find profitable orderings, then submit bundles. Builders aggregate bundles and ordinary transactions into candidate blocks, optimizing for total value. Validators (or proposers) select a block and attest to it. Relays act as intermediaries that pass bundles between searchers and builders without exposing the contents prematurely.

The separation is not universal. On some networks the roles collapse into a single proposer, and on others the builder market is less developed. When you reason about MEV on a new chain, first ask who controls ordering and whether a private submission path exists. The networks directory lists supported chains and their execution environments, which is a useful starting point before assuming Ethereum-style infrastructure.

  • Searcher: finds and submits profitable transaction bundles.
  • Builder: assembles blocks from bundles and transactions.
  • Validator/proposer: selects and proposes the block.
  • Relay: moves bundles between parties with limited disclosure.

Common extraction patterns and their user impact

DEX arbitrage corrects price differences between pools and venues. It is generally the largest category by volume and is mostly neutral to harmful for users, since it pushes prices toward a single market rate. Liquidations keep lending protocols solvent and are a legitimate incentive for keepers, though they can be aggressive during volatility.

Sandwiching is the pattern users feel most directly. A searcher observes a pending swap that will move a pool's price, buys ahead of it, lets the victim's trade push the price further, then sells after. The victim receives a worse rate. The attack is profitable only when the victim's slippage tolerance leaves room, so slippage settings are the primary lever users control.

Frontrunning and backrunning are the general primitives: placing a transaction before or after a target. Generalized frontrunning copies a profitable transaction and replaces the sender. NFT sniping and mint frontrunning apply the same logic to scarce mints. Each pattern has a different mitigation profile, which is why blanket advice like "use a private RPC" is incomplete.

Diagnostic procedure: inspect pending and recent transactions

Before changing anything, establish what your transactions look like from the outside. The following Python script queries a JSON-RPC endpoint for the latest block and prints transaction hashes, gas prices, and input sizes. Run it against your own RPC_URL; do not hardcode a public endpoint. Treat the output as a baseline you can compare after changing submission behavior.

The script uses only standard library modules and the eth_getBlockByNumber method, which every EVM-compatible endpoint supports. If your provider rate-limits, reduce the block range or add backoff.

import json, urllib.request

RPC_URL = "RPC_URL"

def rpc(method, params):
    payload = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
    req = urllib.request.Request(RPC_URL, data=payload, headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=20) as resp:
        return json.loads(resp.read())["result"]

block = rpc("eth_getBlockByNumber", ["latest", True])
print("block", int(block["number"], 16), "txs", len(block["transactions"]))
for tx in block["transactions"][:20]:
    print(tx["hash"], int(tx["gasPrice"], 16) if tx.get("gasPrice") else "n/a", len(tx.get("input", "")))

Measuring your own exposure with a reproducible method

You cannot reduce what you cannot see. A practical exposure test is to submit a small swap through your normal path and compare the executed price against a reference price taken immediately before and after. Record the following fields for each trial in a table: timestamp, pool, quoted amount out, executed amount out, slippage tolerance, submission path (public mempool or private relay), and observed price impact.

Run at least ten trials per configuration and report the median and spread rather than a single result. A single swap can be lucky or unlucky; the distribution is what tells you whether a mitigation helps. Do not compare trials run at different times of day or different market volatility without noting it, because MEV activity is not stationary.

The results table below is a template, not measured data. Fill it with your own observations.

  • | Trial | Path | Quoted out | Executed out | Slippage bps | Price impact |
  • | 1 | public | (your value) | (your value) | (your value) | (your value) |
  • | 2 | private relay | (your value) | (your value) | (your value) | (your value) |
  • Report median executed-minus-quoted across trials, not a single best case.

Implementation: submitting a swap with tighter constraints

The most direct user-side mitigation is to reduce the profit available to a sandwich. Lower slippage tolerance, split large orders, and set a deadline. The JavaScript snippet below shows the shape of a swap call using ethers-style placeholders. It is illustrative; substitute your router ABI and token addresses. Never commit PRIVATE_KEY to source control.

The key parameters are amountOutMin and deadline. amountOutMin should be derived from a fresh quote, not from a stale one, and should be tight enough that a sandwich becomes unprofitable after fees. Splitting an order into smaller pieces reduces the price impact each piece creates, which in turn reduces the value a searcher can extract from any single transaction.

import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider("RPC_URL");
const wallet = new ethers.Wallet("PRIVATE_KEY", provider);
const router = new ethers.Contract("ROUTER_ADDRESS", ROUTER_ABI, wallet);

const amountIn = ethers.parseUnits("1.0", 18);
const quotedOut = await router.getAmountsOut(amountIn, [TOKEN_IN, TOKEN_OUT]);
const minOut = quotedOut[1] * 995n / 1000n; // 0.5% tolerance, adjust deliberately
const deadline = Math.floor(Date.now() / 1000) + 60;

const tx = await router.swapExactTokensForTokens(
  amountIn, minOut, [TOKEN_IN, TOKEN_OUT], await wallet.getAddress(), deadline
);
console.log("submitted", tx.hash);
const receipt = await tx.wait();
console.log("status", receipt.status);

Verification: confirming the mitigation worked

After changing slippage or submission path, re-run the exposure procedure and compare distributions. A successful mitigation shows a narrower gap between quoted and executed amounts and fewer transactions with large negative price impact. It does not necessarily show zero MEV; arbitrage and other benign activity will still appear in block data.

Use a block explorer or your own indexer to inspect whether your transaction was preceded by a same-pool swap from a different sender in the same block. If it was, and the price moved against you, that is evidence of a sandwich. Record the block number and the two transaction hashes so the observation is reproducible.

Limitations, tradeoffs, and next steps

Private submission reduces exposure to public-mempool sandwiching but does not eliminate MEV; builders can still reorder within their own blocks, and trust assumptions shift to the relay. Tighter slippage protects against sandwiches but increases failed transactions, which cost gas. Splitting orders reduces per-trade impact but increases total fees and operational complexity.

Measurement itself has limits. Public data shows what landed, not what was attempted, and bundle-level competition is only partially visible. Treat any single number as a snapshot. For production systems, monitor continuously and revisit assumptions when the chain's builder market changes.

If you are building infrastructure around these workflows, start with a reliable endpoint: review the API service for managed access, compare RPC pricing for cost modeling, and check supported networks before assuming a relay or builder API exists. For latency-sensitive searchers or keepers, a dedicated node is the usual next step after establishing a baseline.

Never Worry about Infrastructure Again

OnFinality takes away the heavy lifting of DevOps so you can build smarter and faster.

Get Started