Auditing DEX Settlements: A Forensic Analysis Methodology
How to audit DEX settlements forensically — detect MEV extraction in transaction history, verify execution quality, and build audit reports from on-chain data.
When a user swaps tokens on a DEX, the transaction they sign is not the transaction that gets executed. Between submission and inclusion, searchers and builders can reorder, insert, or remove transactions to extract value. The final on-chain receipt tells you what happened, but not whether it was fair. Auditing DEX settlements means reconstructing the full execution path, comparing expected versus actual outcomes, and quantifying extraction.
This article presents a forensic methodology for auditing DEX settlements using public tools. We cover how to trace a swap through on-chain events, how to detect MEV extraction, how to build a forensic report, and which tools to use at each stage. Everything here uses publicly available data and open-source tooling.
The Two Artifacts: Receipts and Traces
Every Ethereum transaction produces two artifacts that matter for forensics.
The transaction receipt is returned by eth_getTransactionReceipt. It contains the execution outcome: status (success or revert), gasUsed, cumulativeGasGas, and the logs array. Logs are the emitted events — Transfer, Swap, Sync, Deposit, Withdrawal. The receipt tells you what the contract said happened.
The execution trace is returned by debug_traceTransaction (Geth) or trace_transaction (Erigon). It contains the full call graph: every internal call, every value transfer, every revert, every subcall. The trace tells you what actually happened inside the EVM.
The receipt is available from any node. The trace requires a node with tracing enabled, which most public endpoints disable because tracing is computationally expensive. Etherscan provides decoded logs and internal transactions on its UI. For programmatic access to traces, you need an archive node with debug/trace namespaces enabled, or a third-party service like Alchemy or Infura with trace add-ons.
A key forensic principle: the receipt and the trace tell different stories. The receipt shows the final state transitions. The trace shows the intermediate steps. When auditing a DEX settlement, you need both. The receipt tells you the user received X tokens. The trace tells you whether a sandwich attacker front-ran the swap and captured value that should have gone to the user.
Step 1: Identify the Transaction
The audit starts with a transaction hash. The user provides it, or you find it by querying your internal systems for a specific user's swap.
From the transaction hash, pull two RPC responses:
eth_getTransactionByHash— Returns the envelope:from,to,value,gas,gasPrice(or EIP-1559 fields),nonce,inputcalldata,blockNumber,blockHash.eth_getTransactionReceipt— Returns the execution outcome:status,gasUsed,logs.
Record both. The envelope tells you what was requested. The receipt tells you what the chain accepted. The gap between them is where extraction happens.
On Etherscan, the transaction page shows the envelope fields. The "Logs" tab shows decoded events. The "Internal Txns" tab shows the trace. For programmatic analysis, use an RPC client or a tool like evm-log-explorer (an open-source CLI that decodes Ethereum transaction logs into readable token flows).
Step 2: Decode the Logs
The logs array is the primary evidence in a DEX settlement audit. Each log entry has three fields: address (the contract that emitted it), topics (the indexed parameters, with topic 0 being the event signature hash), and data (the non-indexed parameters).
To decode logs, you need the ABI of the emitting contract. For standard protocols, the ABIs are public:
- ERC-20 —
Transfer(address,address,uint256), signature hash0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef - Uniswap V2 Pool —
Swap(address,uint256,uint256,uint256,uint256,address),Sync(uint112,uint112) - Uniswap V3 Pool —
Swap(address,address,int256,int256,uint160,uint128,int24) - WETH —
Deposit(address,uint256),Withdrawal(address,uint256)
Decode each log against the appropriate ABI. The result is a sequence of events that tells the story of the transaction: who transferred what to whom, what swapped for what, and what the pool state looks like after.
Reading the Token Flow
For a simple Uniswap V2 swap, the log sequence is typically:
Transfer— User sends input tokens to the pool.Swap— Pool emits the swap event with amounts.Transfer— Pool sends output tokens to the user.Sync— Pool updates its reserves.
For a multi-hop swap through a router, the sequence is longer: multiple Transfer and Swap events chained through intermediate pools.
For a sandwiched swap, the sequence looks different. You will see:
Swap— Attacker buys the token (front-run).Transfer— User sends input tokens.Swap— User's swap executes at a worse price (because the attacker moved the pool).Transfer— User receives fewer output tokens.Swap— Attacker sells the token (back-run), capturing the price difference.
The key signal is the ordering: if a buy-swap precedes the user's swap and a sell-swap follows it, and both involve the same pool and the same token, that is a sandwich.
Step 3: Reconstruct the Execution Trace
Logs tell you the event sequence but not the internal call structure. For that, you need the trace.
A callTracer trace from Geth's debug_traceTransaction produces a nested call tree. Each frame has: type (CALL, STATICCALL, DELEGATECALL, CREATE), from, to, value, input, output, gas, gasUsed, and calls (an array of subframes). An error field on any frame marks where a revert originated.
Read the trace outside-in. The top frame is the entry point (usually the router contract). Each nested frame is a call the parent made. For a DEX swap, the call tree typically looks like:
CALL router.swapExactTokensForTokens
CALL token.transferFrom(user, pool, amountIn)
CALL pool.swap
CALL token.transfer(user, amountOut)
STATICCALL token.balanceOf(pool)
STATICCALL token.balanceOf(router)
For a sandwich attack, the trace shows three separate transactions, not one. The attacker's front-run and back-run are separate transactions in the same block, ordered around the victim's transaction. You need to look at all three transactions in the block to see the full picture.
Step 4: Detect MEV Extraction
MEV (Maximal Extractable Value) extraction takes several forms. The three most common in DEX settlements are sandwich attacks, arbitrage, and liquidation. For a settlement audit, sandwich attacks are the primary concern because they directly harm the user.
Sandwich Detection
A sandwich attack has three on-chain transactions:
- Front-run — The attacker buys the same token the user is buying, moving the pool price up.
- Victim — The user's swap executes at the inflated price, receiving fewer tokens.
- Back-run — The attacker sells the token back, capturing the price difference as profit.
To detect this, examine the block containing the user's transaction. Look for other transactions in the same block that interact with the same pool and the same token pair, ordered immediately before and after the victim.
The forensic signals:
- A transaction immediately before the victim that swaps in the same direction (buying the same token).
- A transaction immediately after the victim that swaps in the opposite direction (selling the same token).
- Both transactions share the same pool address.
- The front-run and back-run transactions are typically from the same address or addresses controlled by the same searcher.
Using mev-inspect-rs
Flashbots' mev-inspect-rs is an open-source Rust tool that detects historic MEV opportunities, one of several MEV detection tools and methods available to developers. It inspects blocks and identifies swaps, arbitrages, sandwich attacks, and liquidations across Uniswap, Curve, Balancer, Sushiswap, Aave, Compound, and other protocols.
To use it:
# Inspect a single block
mev-inspect blocks 19000000 19000001
# Inspect a single transaction
mev-inspect tx 0x...
The tool parses transaction data, identifies MEV patterns, and outputs structured data. For sandwich attacks, it identifies the victim transaction, the front-run, the back-run, and the extracted profit.
mev-inspect-rs stores results in Postgres for querying. You can query for all MEV events in a block range, filter by type (sandwich, arbitrage, liquidation), and join with your user transaction data to identify which of your users' swaps were sandwiched.
Using EigenPhi
EigenPhi is a public MEV intelligence platform that tracks, classifies, and quantifies MEV activity across Ethereum and other EVM chains. It analyzes three types of MEV: arbitrage, sandwich, and liquidation.
EigenPhi's approach is based on a universal abstraction: it defines a transaction as a collection of asset transfers, then evaluates the outcomes using rules to determine if MEV occurred. It breaks down transactions into Transfers and Trades, merges them into a Transfer Table, and then generates a Combined Transfer Table to identify profit extraction.
The MEVScan API provides programmatic access. The eigenphi/mevscan-marketplace GitHub repository includes demo apps:
- MEV Live Stream — A Python app that connects to the MEVScan SSE push service and displays real-time MEV events.
- MEV Report — An AI-powered tool that takes a transaction hash and generates a structured report with conclusion, token flow chart, and EigenTx Mermaid diagram.
For a settlement audit, the MEV Report tool is particularly useful: paste a transaction hash, and it produces a structured analysis of the MEV activity in that transaction.
Computing the Price Impact
Once you identify a sandwich, quantify the extraction. The method:
-
Expected price — The pool price before the front-run, from the
Syncevent of the last swap before the victim's transaction. Compute the spot price asreserveOut / reserveIn(for Uniswap V2) or from thesqrtPriceX96(for Uniswap V3). -
Actual price — The price the user received, from the
Swapevent in the victim's transaction. Compute asamountOut / amountIn. -
Price impact — The difference between expected and actual price, as a percentage:
(expectedPrice - actualPrice) / expectedPrice * 100. -
Extracted value — The profit the attacker captured, from the back-run transaction's
Swapevent. Compute as the difference between the tokens the attacker received in the back-run and the tokens they spent in the front-run.
The evm-log-explorer tool computes both spot price (from Sync reserves) and execution price (from the Swap event) for Uniswap V2 trades, making it easy to see the slippage in any trade.
Step 5: Verify Execution Quality
Beyond MEV detection, a settlement audit verifies that the user got a fair price. This means comparing the executed price against a reference price.
Reference Price Sources
- Time-weighted average price (TWAP) — The average pool price over a defined window before the transaction. Compute from historical
Syncevents or use an on-chain TWAP oracle. - Off-chain price — The price on a centralized exchange (CEX) at the same timestamp. Use a price API (CoinGecko, Binance, Coinbase) to get the market price at the block timestamp.
- Best bid/offer across DEXs — The best available price across all DEX pools at the time of execution. Requires querying multiple pool states at the block.
Slippage Calculation
Slippage is the difference between the expected price and the executed price, expressed as a percentage:
slippage = (expectedPrice - executedPrice) / expectedPrice * 100
Normal slippage for a liquid pool is typically under 0.5% for moderate trade sizes, as explained in our guide on measuring DEX swap cost. Slippage above 1-2% on a liquid pool warrants investigation. Slippage that matches the extracted value from a sandwich attack confirms the extraction.
Gas Analysis
Compare the gasUsed against the expected gas for the swap type. Unusually high gas usage can indicate the transaction was bundled with additional calls (a common pattern in MEV extraction). Compare gasPrice or maxFeePerGas against the block's median gas price. A transaction that overpays for gas may be a priority transaction inserted by a searcher.
Step 6: Build the Forensic Report
A forensic report documents the findings in a structured, auditable format. The report should include:
Transaction Identification
- Transaction hash
- Block number and timestamp
- From address (the user)
- To address (the router or pool)
- Input calldata (decoded)
- Gas used and gas price
Execution Summary
- Input token and amount
- Output token and amount
- Executed price
- Reference price (TWAP or CEX)
- Slippage percentage
MEV Analysis
- Whether a sandwich was detected
- Front-run transaction hash and details
- Back-run transaction hash and details
- Attacker address
- Extracted value (in output token and USD)
- Price impact on the user's swap
Call Trace Summary
- The call tree, showing the path from the router through the pool(s)
- Any anomalous calls or reverts
Conclusion
- Whether the settlement was fair or extracted
- The quantified loss to the user
- Recommended action (dispute, compensate, no action)
Tools Summary
| Tool | Purpose | Source |
|---|---|---|
| Etherscan | View transactions, logs, internal txs | etherscan.io |
evm-log-explorer |
Decode logs, compute slippage | github.com/Frodrinos/evm-log-explorer |
mev-inspect-rs |
Detect MEV in block history | github.com/flashbots/mev-inspect-rs |
mev-inspect-py |
Python MEV inspector (legacy) | github.com/flashbots/mev-inspect-py |
| EigenPhi MEVScan | MEV intelligence platform | eigenphi.com |
| EigenPhi MEV Report | AI-powered transaction analysis | github.com/eigenphi/mevscan-marketplace |
Geth debug_traceTransaction |
Execution trace | Any node with debug namespace |
Erigon trace_transaction |
Structured trace | Any Erigon node with trace namespace |
Methodology Limitations
This methodology has limitations you should document in your report.
Trace availability — Not all nodes support tracing. If you cannot get a trace, you are limited to log-based analysis, which may miss internal value transfers (native ETH transfers do not emit logs).
Cross-block MEV — Some MEV strategies span multiple blocks. A searcher may front-run in block N and back-run in block N+1. Single-block analysis will miss this.
Multi-hop complexity — Multi-hop swaps through several pools produce complex log sequences. Manual decoding is error-prone. Use tools like evm-log-explorer or mev-inspect-rs for automated decoding.
Private order flow — Transactions submitted through private order flow (Flashbots Protect, MEV-Share, Merkle) may not appear in the public mempool. The on-chain result is the same, but you cannot reconstruct the pre-execution state.
L2 differences — On L2s (Base, Arbitrum, Optimism), the sequencing model differs. Transactions are ordered by the sequencer, not by gas price. MEV patterns look different. Some tools (mev-inspect-rs) are Ethereum-specific.
Summary
Auditing DEX settlements is a forensic process. Start with the transaction hash. Pull the receipt and the trace. Decode the logs to reconstruct the token flow. Examine the block for sandwich patterns. Use mev-inspect-rs or EigenPhi for automated MEV detection. Compute the price impact and compare against a reference price. Document everything in a structured report.
The tools are public. The data is on-chain. The methodology is repeatable. The hard part is not the tools — it is the discipline of checking every swap, not just the ones that look suspicious, which is why real-time MEV monitoring should be a continuous practice.
If you are building settlement auditing infrastructure, Orkid is one project working in this space. But the tools and methodology described here are publicly available and applicable to any DEX settlement audit.
Frequently Asked Questions
What is a DEX settlement audit?
A DEX settlement audit is a forensic review of the execution of decentralized exchange swaps to verify that each trade settled at a fair price and that no value was extracted through manipulation or intermediary markup. The audit reconstructs each swap from on-chain data, compares the executed price against a benchmark, and decomposes the cost into fee, price impact, and any surplus captured by routers or aggregators. It examines whether the settlement adhered to the trader's stated slippage tolerance and whether any MEV was extracted. The output is a per-trade cost breakdown and an aggregate execution quality assessment.
How do you trace a swap on-chain?
Tracing a swap on-chain involves following the sequence of internal transactions and event logs from the router contract through the pool contracts to the final token transfers. Each swap emits events such as Swap on the pool and Transfer on the token contracts, which record the amounts in and out, the recipient, and the sender. By replaying the transaction against the block's state or indexing the emitted events, you can reconstruct the exact token flows and intermediate prices at each hop. Multi-hop swaps require following the path through each intermediate pool in order.
What is forensic blockchain analysis?
Forensic blockchain analysis is the systematic examination of on-chain transaction data to reconstruct events, identify actors, and quantify value flows for investigative or audit purposes. It combines transaction graph analysis, event log parsing, and state reconstruction to build a complete picture of what happened during a transaction or series of transactions. In the context of DEX auditing, forensic analysis identifies where value moved, who extracted it, and whether the settlement was consistent with the protocol's intended behavior. The methodology draws on public chain data and does not require special access.
What tools are used for DEX auditing?
DEX auditing uses a combination of block explorers for manual transaction inspection, RPC nodes and archive nodes for state reconstruction, and indexing frameworks for systematic event extraction. Tenderly and similar simulation platforms allow replaying transactions against historical state to inspect internal calls. Custom scripts using web3 libraries parse event logs and compute per-swap metrics from pool contracts. For large-scale analysis, indexed subgraphs or direct database ingestion of decoded event data enable batch computation of execution quality across many trades.
What is settlement integrity?
Settlement integrity is the property that a trade executed at the price the trader should have received given the prevailing market conditions and the protocol's rules, with no unexplained value leakage. A settlement with high integrity shows that the difference between the expected and actual outcome is fully explained by legitimate costs such as fees and price impact. Integrity is compromised when intermediaries extract surplus beyond disclosed fees, when MEV bots manipulate the execution, or when router logic routes through suboptimal paths. Auditing verifies integrity by accounting for every component of the price difference.
Put it to work
The research above powers the product — try it or compare it: