Can We Return the MEV Left Behind by a Swap to the User?
In 2022, a DeFi swap could finish in seconds. Its economic effects did not.
A user makes a large swap through an automated market maker (AMM), a trading pool whose reserves determine its price. The reserve ratio moves, opening a price gap against another decentralized exchange (DEX). A searcher, a participant looking for profitable trading opportunities, follows the swap and earns a profit by narrowing that gap. This kind of following trade is called a backrun.
The user bears price impact and gas costs, while someone else receives the arbitrage left behind. At the end of 2022, we began with this question:
Could the arbitrage run inside the user's transaction and return what remains after costs to the user?
MEV broadly describes value obtained through transaction inclusion, exclusion, ordering, and related choices. This post revisits a design for internalizing some cross-DEX arbitrage left after a user's swap. It explored changing who executes that trade and receives its proceeds; it does not present verified performance of a current product.
What Remains After Borrowing 4.2 A?
Suppose a user has swapped token A for B. The following table describes two pools observed immediately afterward. We will calculate only the subsequent arbitrage, not the execution price of the entire original order. Pool names are 1 and 2; token names are A and B.
| Pool | A reserve | B reserve | Marginal price of 1 A |
|---|---|---|---|
| Pool 1 | 100 | 100 | 1.0 B |
| Pool 2 | 100 | 120 | 1.2 B |
A is relatively expensive on pool 2. Borrowing A, selling it there for B, and using that B to buy A on pool 1 can return more A than we borrowed. Each trade also moves the pool's price, so the 20% price gap is not itself a return on the amount traded.
Assume a 0.3% swap fee on each pool and a 0.05% premium from a separate flash-loan provider. The protocol covers the additional gas caused by internalization and charges its assumed equivalent of 0.01 A against the arbitrage. The gas cost of the basic user swap is separate, and there is no additional protocol fee.
| Step | Result |
|---|---|
| Principal borrowed | 4.200000 A |
| Pool 2: exchange A for B | 4.822925 B |
| Pool 1: exchange B for A | 4.587851 A |
| Increase after repaying principal | 0.387851 A |
| Deduct loan premium | −0.002100 A |
| Settle extra execution cost | −0.010000 A |
| Surplus returned to the user | 0.375751 A |
Both DEX fees are already reflected in the swap outputs; do not deduct them from the increase again. We use one cost basis throughout: the increase after swapping and returning principal, less the loan premium and extra execution cost. The user's original output token was B, but this example refunds A. Paying the refund in B as well would require including the fee and price impact of that final conversion.
The output calculation is short. Let be the input-token reserve, the output-token reserve, and the input. With the fee-adjusted input fraction , the output is:
Using pool 2's output as pool 1's input produces the table above. This follows the fee treatment in the official Uniswap v2 calculation code. For readability, we use real-number arithmetic and round to six decimal places. These are not contract-execution results reproducing integer division in the tokens' smallest units.
After the cycle, the marginal price of 1 A is approximately 1.0986 B on pool 1 and 1.1053 B on pool 2. They need not be identical. With fees, a small remaining gap may not cover another trade's costs. The practical objective is therefore closer to maximizing surplus after costs than making every pool ratio equal.
One Transaction, from Loan to Refund
The core idea is for an aggregator connecting multiple DEXs to execute this cycle immediately after the user swap. A flash loan supplies liquidity that must be borrowed and repaid within one transaction. It funds an opportunity that already exists; it does not create profit where none exists.
Uniswap v2 flash swaps also illustrate arbitrage funded this way. Flash swaps and loans from a separate provider can have different repayment rules; the 0.05% premium above is an illustrative assumption.
There are three execution cases:
| When | What happens |
|---|---|
| Pre-execution calculation finds no surplus above costs | Select the basic user-swap route |
| Execution meets output, repayment, and surplus conditions | Complete the user swap, arbitrage, repayment, and refund together |
| A condition fails during internalized execution | Revert the entire path, including the user swap |
Atomicity means that the state changes either succeed together or revert together. The path may include multiple function calls, such as trading and arranging repayment inside a loan provider's callback, while remaining one transaction. Retrying only the basic swap after failure needs a separate design; it is not automatic. A reverted transaction can still consume gas.
User protection also has two distinct measures. minOut specifies the minimum token quantity the user must receive,
and comparison with a baseline checks token output. Improvement after gas additionally depends on who pays for it,
the incremental amount, and the conversion price. An output check alone does not guarantee all of these.
The Boundary of Atomicity
An external participant cannot insert another transaction between calls inside this transaction. But a builder, which assembles the block, can place trades before or after the whole transaction. Frontrunning a disclosed order, or sandwiching it with trades on both sides that affect its execution, remains a separate problem.
| Boundary | What needs attention |
|---|---|
| Arbitrage left after the user swap | Capture and return the part that exceeds costs |
| Ordering around the entire transaction | Order delivery, deadlines, and price limits; internal atomicity is insufficient |
| Manipulated or changed pool state | Liquidity and price-deviation criteria, with execution-time revalidation |
| Malicious adapters or nonstandard tokens | Restrict support, account for actual balance changes, defend callbacks and reentrancy |
| Final allocation of proceeds | Account for principal, premium, costs, refunds, and small residual balances |
This does not address every type of MEV, including liquidations or oracle manipulation, nor inclusion delays and censorship. It changes the executor and beneficiary of arbitrage following a particular swap.
Liquidity providers (LPs) also matter. The Loss-Versus-Rebalancing research examines the relationship between AMM arbitrage and LP performance. Returning arbitrage to the user does not erase its source. We cannot equate every unit of surplus in this example with LVR; who bears the costs, including LPs, must be measured separately.
Reading the 2022 Equations Again
Our internal spreadsheet contained four simple constant-product pools holding the same token pair. We tried to rebalance their ratios after a user swap while preserving the product of the two reserves in each pool.
Let denote pool 's A reserve and its B reserve. Its product and the target aggregate ratio are:
has units A/B, the opposite direction from the earlier price of one A in B. The corresponding target price in B/A is . The target reserves preserving each pool's product while setting its reserve ratio to are:
The square root comes from solving and together. A positive calls for a trade that sends A into the pool; a negative value calls for one that withdraws A.
This model assumes fee-free pools. The earlier 4.2 A example is a separate calculation that includes fees to illustrate the limitation. This target formula does not optimize concentrated liquidity, different fee tiers, or stable-swap curves. The aggregate ratio is an internal reference from selected pools, not an external fair price. It is sensitive to pool selection and reserve manipulation, and preserving each pool's product does not by itself ensure repayment or token conservation across the complete path.
For implementation: execution boundaries and checks
The following pseudocode illustrates execution order. Unlike the numerical example's A refund, it converts surplus to the order's output token, so the candidate calculation must include that conversion's costs. It is not deployable code implementing callbacks, repayment approvals, or failure recovery. Its final checks also run inside the same top-level transaction.
function swapWithInternalizedArbitrage(order):
snapshot = readEligiblePools(order.pair)
baseline = simulateBestUserRoute(order, snapshot)
candidate = optimizeCrossDexTrade(baseline.postSwapState)
if candidate.netSurplus <= MIN_PROFIT:
return executeBaselineSwap(order, baseline)
result = atomicExecute([
validateQuotes(snapshot, order.deadline),
executeUserSwap(order, baseline.route),
flashBorrow(candidate.borrowToken, candidate.amount),
executeCrossDexTrade(candidate.route),
repayFlashLoan(),
convertSurplusTo(order.tokenOut),
refundSurplus(order.owner),
])
require(result.totalUserOut >= order.minOut)
require(result.totalUserOut >= baseline.userOut)
require(result.flashLoanRepaid)
require(result.netSurplus > MIN_PROFIT)
require(result.unaccountedBalance <= DUST_LIMIT)
The reference time of baseline.userOut and quote validity must be defined, with state revalidated at execution.
An unconditional promise based on a simulated price may become impossible before block inclusion. netSurplus needs
a cost-conversion and cost-bearing policy; DUST_LIMIT needs a rule for the remaining small token balances.
For the earlier example's real-number model with fixed extra cost, the cycle output is:
The refundable surplus is . The maximizing loan is approximately 4.196063 A, rounded to 4.2 A in the table. Token-unit rounding, changing gas costs, or a refund conversion require optimizing again.
Other Designs Asking the Same Question
In August 2022, WOWMAX's public explanation described combining swaps and subsequent price rebalancing in one atomic transaction. In 2023, the UniswapX whitepaper described competition to execute orders, routing, and batching as ways to return surplus through price improvement.
CoW Protocol's batch auction addresses solving multiple orders together, while Flashbots Protect addresses private order delivery and MEV refunds. Their execution models differ, but they all treat value allocation and order protection as protocol design questions. We cannot call our idea the first of its kind.
This design was documented in Bankware Global Co., Ltd.'s Korean Registered Patent No. 10-2564770, “Token Swap System and Method Through a Decentralized Exchange for Preventing Transaction Distortion” (filed January 12, 2023; registered August 3, 2023). This records its source and history; it is neither evidence of technical completeness nor a license or non-assertion pledge. Public code and the conditions for using patent rights require separate decisions.
The work of closing a post-swap price gap remains. Leaving the resulting surplus to external searchers, or recovering it within execution and returning it to the user, is a separate choice. That choice was the question our small 2022 model opened up.