A MEV bot is automated software that detects value-extraction opportunities in how blockchain transactions are ordered, included, or excluded, then submits transactions or bundles to capture that value. The operator, usually called a searcher, combines a strategy (arbitrage, liquidation, sandwich, backrun), a simulation layer, and a submission path to block builders or validators. This article explains the mechanism end to end, gives runnable code for observing pending transactions and simulating a candidate trade, and describes how to measure latency, inclusion rate, and net profit without inventing numbers. It also covers the infrastructure choices, failure modes, and ethical and legal limits a searcher must understand before deploying capital.
Definition and Scope of a MEV Bot
A MEV bot is a program that watches blockchain state and pending transactions, identifies a profitable ordering of transactions, and submits that ordering to the network or to a block builder. MEV stands for maximal extractable value: the profit available to whoever controls transaction ordering, inclusion, or exclusion within a block. A bot does not decide final block order on its own; it competes for position through fees, priority tips, or bundles that builders choose to include.
The person or team operating the bot is a searcher. Searchers write strategies, simulate outcomes against current state, and route signed transactions to builders or public mempools. This article covers the mechanism, a reproducible observation and simulation workflow, and the infrastructure and measurement questions that determine whether a strategy survives contact with real competition. It does not recommend a specific endpoint; for concrete provider and network choices, use the OnFinality RPC Assistant.
- Searcher: designs and runs the strategy.
- Bot: the automated software that monitors, simulates, and submits.
- Builder or validator: selects and orders transactions into a block.
- Mempool: the pending-transaction queue visible to observers on some chains.
Assumptions and Prerequisites
The procedures below assume an EVM-compatible chain with a JSON-RPC interface, a funded account for testing on a testnet or local fork, and basic familiarity with transaction signing. You need Node.js 18 or later for the JavaScript examples, Python 3.10 or later for the Python example, and curl for the raw RPC checks. All secrets must come from environment variables; never hardcode a private key.
You also need a reliable RPC endpoint that exposes pending transactions and supports eth_call against historical or pending state. Public endpoints often rate-limit or hide the mempool, so plan to use a dedicated or paid endpoint for anything beyond a smoke test. The OnFinality API service and dedicated node pages describe the operational options; the pricing page explains how request volume maps to cost.
export RPC_URL="https://your-endpoint.example"
export PRIVATE_KEY="0x..."
node --version
python3 --versionHow Ordering Creates Extractable Value
Blockchains execute transactions in an order chosen by the block producer. If two transactions touch the same liquidity pool, the order changes the price each one receives. That ordering sensitivity is the root of MEV. A bot's job is to find an ordering where its own transaction profits after fees, gas, and the risk that another searcher wins the race.
The common strategies differ in what they observe and what they submit. Arbitrage compares prices across venues and submits a round trip. Liquidation watches lending positions and submits a repay-and-seize transaction when a health factor crosses a threshold. Sandwich and frontrun strategies place transactions around a victim's trade; these are the strategies most associated with user harm and are restricted or discouraged on many venues. Backrunning places a transaction immediately after a large trade to capture the price impact it creates.
- Arbitrage: price difference across DEXs or CEXs.
- Liquidation: undercollateralized loan in a lending protocol.
- Backrun: price impact created by another user's large swap.
- Sandwich and frontrun: position around a victim transaction; high harm, high scrutiny.
The Searcher Loop: Observe, Simulate, Submit, Verify
Every bot, regardless of strategy, runs the same four-stage loop. Observation reads chain state and pending transactions. Simulation executes the candidate transaction against a forked or pending state to estimate output and revert risk. Submission signs and sends the transaction or bundle to a builder or public mempool. Verification confirms inclusion and computes realized profit after all costs.
The loop is a race. Observation latency, simulation latency, and submission latency all reduce the probability of inclusion. A bot that is correct but slow loses to a bot that is slightly less profitable but faster. This is why infrastructure choices matter as much as strategy logic.
Observing Pending Transactions with curl and WebSocket
Start by confirming your endpoint exposes pending transactions. The eth_newPendingTransactionFilter method creates a filter; eth_getFilterChanges polls it. Many production searchers use WebSocket subscriptions instead, because push delivery avoids polling gaps. The curl check below verifies the method is available; a null or error response means the endpoint does not expose the mempool and you need a different one.
curl -s -X POST "$RPC_URL" \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_newPendingTransactionFilter","params":[]}'Simulating a Candidate Trade in JavaScript
Simulation answers one question: if this transaction executes now, what is the output and does it revert? The example below uses ethers to call a Uniswap-style router's getAmountsOut against current reserves, then compares the result to a minimum acceptable output. Replace the router address and token addresses with the ones for your target chain. The script prints the quoted output and the implied edge; it does not submit anything.
Run this against a forked node or a testnet first. On mainnet, eth_call against pending state gives a closer estimate than latest state, but it is still an estimate because state can change between simulation and inclusion.
import { JsonRpcProvider, Contract, parseUnits, formatUnits } from 'ethers';
const provider = new JsonRpcProvider(process.env.RPC_URL);
const routerAbi = [
'function getAmountsOut(uint amountIn, address[] path) view returns (uint[] amounts)'
];
const router = new Contract('0xROUTER_ADDRESS', routerAbi, provider);
const amountIn = parseUnits('1', 18);
const path = ['0xTOKEN_IN', '0xTOKEN_OUT'];
const amounts = await router.getAmountsOut(amountIn, path);
console.log('quoted out:', formatUnits(amounts[1], 18));Bundling and Submission Paths
On chains with a proposer-builder separation, searchers submit bundles to builders rather than directly to the public mempool. A bundle is an ordered list of signed transactions that must execute atomically; if any transaction reverts, the whole bundle is dropped. Builders compare bundles by total tip and include the most profitable set. On chains without this separation, searchers compete through gas price and priority fees in the public mempool.
The submission path determines your competition. Public mempool submission exposes your strategy to copycats before inclusion. Private bundle submission hides the transaction until it is included but requires a relationship with a builder or a relay. Choose the path that matches your strategy's sensitivity to being copied.
- Public mempool: simple, but visible and copyable.
- Private bundle to builder: hidden until inclusion, requires builder access.
- Relay or bundle service: abstracts builder relationships, adds a fee.
- Direct to validator: only viable if you have a validator relationship.
Measuring Latency, Inclusion Rate, and Net Profit
You cannot improve what you do not measure. Instrument every stage of the loop with timestamps and log the outcome of each submission. The table below is the minimum set of fields to record per opportunity; fill it with your own measurements, not estimates. Run at least a few hundred opportunities before drawing conclusions, because inclusion is noisy and a small sample will mislead you.
- observed_at: timestamp when the opportunity was detected.
- simulated_at: timestamp when simulation completed.
- submitted_at: timestamp when the transaction or bundle was sent.
- included_at: timestamp when the transaction appeared in a block, or null.
- gross_profit, gas_cost, tip, builder_fee, net_profit: all in the same unit.
- outcome: included, reverted, outbid, dropped, or not_selected.
Results Table Procedure
Aggregate the log into a table with one row per strategy and one column per metric. Compute inclusion rate as included submissions divided by total submissions. Compute median latency from observed_at to included_at for included rows only. Compute net profit as the sum of net_profit across included rows minus the cost of reverted and dropped submissions. Present the table with the sample size and the observation window so the reader can judge whether the numbers are meaningful.
| Strategy | Submissions | Included | Inclusion rate | Median latency (ms) | Gross profit | Total cost | Net profit |
|---|---|---|---|---|---|---|---|
| Arbitrage | your count | your count | your rate | your median | your sum | your sum | your sum |
| Liquidation | your count | your count | your rate | your median | your sum | your sum | your sum |
| Backrun | your count | your count | your rate | your median | your sum | your sum | your sum |
Troubleshooting Common Failures
Most failed submissions fall into a small number of categories. Reverts usually mean state changed between simulation and inclusion, or the simulation used stale reserves. Outbid outcomes mean another searcher paid more for the same opportunity; the fix is either a higher tip or a strategy that is harder to copy. Dropped transactions usually mean the nonce was already used or the gas price fell below the builder's minimum.
If your bot never sees pending transactions, the endpoint is probably not exposing the mempool. If your simulation passes but inclusion reverts, check whether you are simulating against latest state while submitting against pending state. If your inclusion rate is high but net profit is negative, your cost model is missing a fee, a tip, or the cost of failed attempts.
- No pending transactions: endpoint hides mempool; switch endpoints.
- Simulation passes, inclusion reverts: state drift or stale reserves.
- Consistent outbidding: tip too low or strategy too visible.
- Dropped transactions: nonce reuse or gas below minimum.
- Negative net profit: missing cost component in the model.
Limitations, Ethics, and Legal Boundaries
MEV is not free money. Competition is intense, capital requirements are real, and the strategies with the highest expected value are often the ones with the highest harm and the most scrutiny. Sandwich and frontrun strategies extract value directly from other users and are restricted or discouraged on many venues. Some jurisdictions treat manipulative trading practices as unlawful regardless of whether the execution is automated; the legality of a bot depends on how it is used, not on the fact that it is software.
Operationally, MEV bots are fragile. They depend on low-latency infrastructure, reliable endpoints, and continuous monitoring. A bot that is down during a liquidation cascade loses the opportunities it was built for. Budget for redundancy and for the cost of failed submissions, which are a normal part of the loop.
Next Steps for Building and Operating a Searcher
Start with a single strategy on a testnet or local fork, instrument the full loop, and measure inclusion rate and net profit before adding capital. Use a dedicated endpoint for anything beyond a smoke test; the OnFinality API service and dedicated node options are documented, and the pricing page explains how request volume maps to cost. For concrete endpoint and network recommendations, use the RPC Assistant rather than guessing.
Once the loop is stable, add redundancy across endpoints and submission paths, and review the legal and ethical constraints for your jurisdiction and target venues. The related guides below cover the infrastructure and measurement topics that support a production searcher.
- Read the RPC endpoints guide for endpoint selection criteria.
- Review the blockchain node hosting guide for redundancy planning.
- Check the multi-chain RPC endpoints guide if you operate across chains.
- Use the RPC Assistant for concrete provider and network choices.