Certifying optimal MEV strategies with Lean
Massimo Bartoletti
University of Cagliari
Cagliari, Italy
bart@unica.itRiccardo Marchesin
University of Trento
Trento, Italy
riccardo.marchesin@unitn.itRoberto Zunino
University of Trento
Trento, Italy
roberto.zunino@unitn.it
Abstract—Maximal Extractable Value (MEV) refers to a class
of attacks to decentralized applications where the adversary
profits by manipulating the ordering, inclusion, or exclusion
of transactions in a blockchain. Decentralized Finance (DeFi)
protocols are a primary target of these attacks, as their logic
depends critically on transaction sequencing. To date, MEV
attacks have already extracted billions of dollars in value, under-
scoring their systemic impact on blockchain security. Verifying
the absence of MEV attacks requires determining suitable upper
bounds, i.e. proving that no adversarial strategy can extract
more value (if any) than expected by protocol designers. This
problem is notoriously difficult: the space of adversarial strategies
is extremely vast, making empirical studies and pen-and-paper
reasoning insufficiently rigorous. In this paper, we present the
first mechanized formalization of MEV in the Lean theorem
prover. We introduce a methodology to construct machine-
checked proofs of MEV bounds, providing correctness guarantees
beyond what is possible with existing techniques. To demonstrate
the generality of our approach, we model and analyse the MEV
of two paradigmatic DeFi protocols. Notably, we develop the first
machine-checked proof of the optimality of sandwich attacks in
Automated Market Makers, a fundamental DeFi primitive.
Index Terms—smart contracts, MEV , decentralized finance,
interactive theorem proving, Lean 4
I. INTRODUCTION
Public permissionless blockchains such as Ethereum cur-
rently handle billions of dollars in crypto-assets, controlled by
smart contracts that implement increasingly complex financial
applications. In most cases, the underlying protocols of these
blockchains do not enforce transaction order fairness, instead
delegating the sequencing of user transactions to miners or
validators. This leaves decentralized applications vulnerable to
Maximal Extractable Value (MEV) attacks, where adversaries
manipulate transaction sequencing for profit. While MEV
extraction may have some beneficial effects — such as reduc-
ing transaction fees [1] — its overall impact is detrimental
on the affected blockchains, undermining decentralization,
transparency, and exacerbating network congestion [2], [3].
MEV can be approached from two different perspectives,
depending on whether one plays the role of attacker or
defender. For an attacker, the fact that the value extracted is
maximalis not really relevant. What truly matters is having
an efficient algorithm to bundle one’s own transactions with
those of other users in a way that guarantees profit. For that
purpose, the attacker can exploit known heuristics targeting
specific contracts [4], [5], [6], or devise adaptive techniques
that can potentially extract value from arbitrary contracts [7].In both cases, the adversary wins if the value extracted exceeds
the value paid to mount the attack.
Playing the role of defender is substantially harder: to
guarantee that the value extractable from a contract is bounded
by a given thresholdv, one must ensure that no adversarial
strategy — among aninfiniteset of possible strategies —
can extract more thanv. More abstractly, letEV(σ, v)be a
predicate stating that in system stateσthe extractable value is
bounded from above byv. Then, the adversary’s task reduces
tofalsification: finding a counterexample toEV(σ, v), by
exhibiting a strategy that extracts somev′> v. Instead, the
defender task amounts toverification: constructing a proof that
EV(σ, v)indeed holds.
From this perspective, establishing MEV requires the same
fundamental ingredients as program verification, namely:
1) a formal model of the system under analysis, i.e., smart
contracts executed on blockchains;
2) a precise formalization of the property of interest, i.e.,
EV(σ, v);
3) a proof technique to determine whether a system satisfies
or not the property.
While the literature proposes several formal models of
contracts at different levels of abstraction — ranging from the
low-level Ethereum Virtual Machine [8], [9], [10] to the high-
level contract language Solidity [11], [12], [13] — the existing
MEV formalizations and the associated proof techniques are
not fully adequate for the purpose. The problem is twofold:
•First, most existing definitions [14], [15], [16] lack the
precision needed to establish MEV , as they often omit
key aspects of adversarial capabilities such as eavesdrop-
ping the transaction mempool [17]. We emphasize that,
from a defender’s perspective, the accuracy of a MEV
formalization is crucial to ensure that no class of attacks
is overlooked.
•Second, as noted above, establishing precise MEV bounds
requires consideringallsequences of transactions that
an adversary can construct using their private knowledge
and the content of the transaction mempool. Although
in many cases this infinite set of adversarial strategies
can be partitioned into a finite number of equivalence
classes, the resulting combinatorial explosion of cases and
subcases quickly becomes unmanageable. This explosion
occurs even for relatively simple contracts, where just a
handful of system variables already gives rise to a vastarXiv:2510.14480v1  [cs.CR]  16 Oct 2025
and intricate strategy space, well beyond the reach of
reliable pen-and-paper proofs.
To address these challenges, it is necessary to devise a
MEV formalization that is (i) precise enough to capture
all possible adversarial strategies, (ii) flexible enough to ac-
commodate a wide range of use cases, and (iii) amenable
to rigorous, machine-verified proofs that go beyond manual
analysis. Proof assistants provide a natural framework to meet
these requirements, as they enable precise formalizations of
software systems and support the construction of machine-
verified proofs whose correctness is guaranteed beyond any
reasonable doubt. In the context of MEV , they offer the
potential to reason about adversarial strategies, automate parts
of the verification process, and ensure a level of rigour
that manual analysis cannot achieve. However, despite its
central role in the security of decentralized applications, no
mechanized formalization of MEV has been developed so
far. Existing studies rely on informal arguments, which are
insufficient to provide guarantees of correctness. This leaves a
critical gap between the theoretical understanding of MEV and
the practical need for security of decentralized applications.
Contributions:This paper addresses the previous re-
search questions by providing the following key contributions:
1) we provide the first fully mechanised formalization of
MEV in a proof assistant (§III). To this purpose, we
adopt Lean 4 [18], an open-source theorem prover and
programming language that has been successfully applied
to construct and verify large-scale proofs [19]. Its exten-
sive mathematical library makes Lean 4 particularly well
suited for reasoning about DeFi contracts, which often
involve complex mathematical manipulations.
2) we devise a new proof technique for establishing MEV .
Roughly, given a system stateσwhere MEV is to be
estimated, our proof technique requires the defender to
provide a “guess” function mapping each state to a can-
didate MEV amount. The defender must then prove that
(i) the guess for the initial state is an under-approximation
of MEV , and (ii) any adversarial move affects the guess
by an amount which is bounded by the gain of the move.
We establish that our proof technique issound— i.e.,
when such a guess function exists, it actually gives the
MEV — andcomplete— i.e., when the MEV exists, a
guess function exists.
3) we apply our proof technique to two paradigmatic case
studies. The first is a gambling game in which players
can win a prize by depositing suitable amounts of tokens.
Despite its apparent simplicity, this case study highlights
how different adversarial strategies can emerge depending
on the contents of the transaction mempool (§V). The
second contract is an Automated Market Maker (AMM),
one of the cornerstones of Decentralized Finance [20],
[21]. Although the MEV of AMMs has been studied
before [22], [23], [24], [25], our work provides the first
mechanized proof that so-calledsandwich attacksextract
the maximal possible value (§VI).contract AirDrop {
constructor()payable{ // receive tokens from the sender
require(msg.value> 0);
}
function drop(uint v)public{
addresspayablercv =payable(msg.sender);
rcv.transfer(v); // transfer tokens to the sender
}
}
Fig. 1. An Airdrop contract in Solidity.
Our Lean implementation, including all the proofs and
case studies are available online in a public repository [26]
consisting of∼7000 lines of code.
II. BACKGROUND ONMEV
At an abstract level, we can see a blockchain as a transition
system, where states represent both users’ wallets (i.e., their
token holdings) and the states of deployed contracts (including
their balances). State transitions are triggered bytransactions
sent by users: a transaction may affect the sender’s wallet, the
state of the called contracts, and the wallets receiving tokens
from those contracts (if any).
As a concrete example, consider anAirdropcontract that
allows any user to withdraw tokens from its balance. We
specify this contract in Solidity in Figure 1. Deploying the
contract requires the sender to transfer any positive amount
of tokens from its wallet to the contract. In this case, the
tokens correspond to the blockchain native cryptocurrency
(e.g., ETH on Ethereum), and they are quantified by the
expressionmsg.value. Besides the constructor, the contract
only features another function,drop, which allows any user
(identified bymsg.sender) to withdraw an arbitrary fraction
of the contract balance. The contract state only consists of its
balance, which is implicitly updated when receiving tokens (in
theconstructor) or sending them (in thetransfercommand).
MEV quantifies the maximal gain that an adversary can
obtain by exploiting their power to reorder, drop, or insert
transactions in the blockchain. To this end, the adversary can
play both pending user transactions in the public mempool,
and may also inject its own crafted transactions, potentially
leveraging knowledge of the mempool contents.
In our working example, assume a system stateσconsisting
of the sole Airdrop contract with a balance ofn >0tokens,
which for simplicity we assume to have unitary price. Any
adversary can simply fire adrop(n)transaction to empty the
contract balance: therefore, the MEV inσis exactlyn. Note
that the Airdrop’s MEV is not necessarily “bad MEV”, since
the extraction of value is aligned with the intended function-
ality of the contract. However, an adversary with transaction
sequencing powers can always front-rundroptransactions of
honest users, depriving them of any gain. In the rest of the
section, we will examine cases of “bad MEV” where the
adversary causes a loss to honest users.
In the previous case, the adversary does not need to exploit
the mempool, but just to front-run other users’ transactions
contract CoinPusher {
function push()public payable{
if(address(this).balance>= 100) {
addresspayablercv =payable(msg.sender);
rcv.transfer(address(this).balance);
}
}
}
Fig. 2. A CoinPusher contract in Solidity.
(this is calleddisplacement attackin [27]). More sophisticated
forms of MEV arise when the adversary exploits pending
transactions in the mempool, e.g. by constructing bundles that
combine users’ transactions with adversarial ones. We will
see in the rest of the section how these strategies make the
estimation of MEV increasingly more complex.
A. The CoinPusher contract
We now consider a case where extracting MEV requires the
adversary to leverage transactions pending in the mempool.
TheCoinPushercontract transfers its entire balance to any
user whose deposit causes the balance to exceed100tokens
( Figure 2). The contract has a single functionpush, which
receives from the sender any amountmsg.valueof tokens (this
transfer happens implicitly along with the call). If the incom-
ing tokens make the contract balance exceed 100 units, the
entire balance (including the incoming tokens) is immediately
sent to the caller through thetransfercommand.
Letσbe a system state where the contract holds0tokens
and a userAholds1token. We assume the adversaryAdvto
bewealthy, i.e. endowed with enough tokens to mount any
feasible attack (in practice,Advcan also obtain such tokens
as a very short-term loan, even if that might cost of some
additional fees). If the mempool inσis empty, thenAdvcannot
extract any value, henceMEV(σ) = 0. Now suppose that the
mempool contains a transaction sent byAthat callspushwhile
transferring 1 token — writtenA:push(value=1). In this case,
Advcan atomically execute the transaction bundle:
A:push(value = 1)Adv:push(value = 99)
which yields a gain of1toAdv. Since no strategy achieves
a higher gain, we conclude thatMEV(σ) = 1. Devising an
optimal strategy for an arbitrary contract when the mempool
contains many transactions is hard, also due to the combi-
natorial explosion of possible interleavings. In the CoinPusher
case, the adversary’s optimal strategy is to include the pending
mempool transactions while interleaving its ownpushcalls. In
the idealized case where there are no transaction fees, this can
yield a gain equal to the contract balance inσplus the total
value of those mempool transactions with value<100.
B. Automated Market Makers
We now consider an Automated Market Maker (AMM), an
archetypal decentralized finance (DeFi) primitive that enables
users to swap between two token types according to an
algorithmically defined exchange rate [20], [28], [29].contract AMM {
uint r0, r1; // reserves of token types t0, t1
constructor(uint n0, uint n1) {
t0.transferFrom(msg.sender, address(this), n0);
t1.transferFrom(msg.sender, address(this), n1);
r0 = n0; r1 = n1;
}
function swap0(uint n0, uint x1_min) {
t0.transferFrom(msg.sender, address(this), n0);
x1 = (n0 * r1) / (r0 + n0); // compute output tokens
requirex1>=x1_min && x1<r1;
t1.transfer(msg.sender, x1);
r0 = r0 + n0; r1 = r1 - x1;
}
function swap1(uint n1, uint x0_min) {
// symmetric to swap0
}
}
Fig. 3. A constant-product AMM contract in Solidity (simplified).
For illustration, we present in Figure 3 a simplified Solidity
code of the AMM contract (an actual implementation is
substantially more complex, e.g. because it has to deal with
rounding of integer operations). Theconstructorinitializes
the reserves of tokenst 0andt 1, which are transferred from
the sender’s wallet to the contract. The functionswap0allows
anyone to sendn0units oft 0and receive at leastx1_minunits
oft 1. The functionswap1is symmetric: it takest 1as input
and outputst 0. The exchange rate follows the mechanism
of Uniswap v2 [30], which maintains the product of reserves
(i.e.,r0·r1) constant across swaps. This guarantees that the
marginal exchange rate (i.e., the one applied for infinitesimal
swaps) coincides with the ratio between the reserves.
When external prices are not aligned with the marginal
exchange rate — i.e., whenr0·price(t 0)̸=r1·price(t 1)
— a strategy to extract value is to perform anarbitrage, i.e. fire
a swap that realigns the reserves with external prices. For ex-
ample, letσbe a state whereprice(t 0) = 4,price(t 1) = 9,
and the AMM reserves are of6units of each token, written:
σ=AMM[6:t 0,6:t 1]|Adv[n 0:t0, n1:t1]
If the adversary callsswap0(3,0), the state becomes:
AMM[9:t 0,4:t 1]|Adv[n 0−3:t 0, n1+ 2:t 1]
The resulting AMM is balanced, and the adversary has paid 3
units oft 0(with value3·4 = 12) to buy2units oft 1(with
value2·9 = 18). So, overallAdvhas gained18−12 = 6.
One of our contributions (§VI-A) is a machine-checked proof
that arbitrage is indeed the optimal MEV-extracting strategy
when the mempool is empty.
If the mempool is nonempty, more complex strategies arise,
which potentially give a higher MEV . A typical strategy is the
so-calledsandwich attack[22], which we illustrate in the same
stateσas before. Assume that a honest userAhas sent an
arbitrage transactionA:swap0(3,1)to the mempool. Here,A
has set the parameterx1_minto1, enforcing a lower bound on
the number oft 1units received from the swap. This safeguard
is meant to account for the uncertainty of the state in which a
transaction will be actually executed — an inherent problem in
account-based blockchains. In a sandwich attack, the adversary
has access to the mempool (containingA’s arbitrage), and uses
it to construct the following transaction bundle:
1)Adv:swap0(3,0), an arbitrage transaction performed by
the adversary;
2)A:swap0(3,1), the transaction picked from the mempool.
SinceA’s transaction is executed in a state where the
AMM is in equilibrium,Awill not receive the 2 units
they would have expected inσ: rather, they receive the
minimum oft 1units admitted by the constraintx1_min,
i.e. only 1 unit. This causesAto have a negative gain;
3)Adv:swap1(1,3). The adversary closes the sandwich
with another arbitrage transaction, after which the AMM
reaches again the equilibrium.
Overall, executing this transaction bundle inσleads to:
AMM[6:t 0,6:t 1]|Adv[n 0:t0, n1:t1]| ···
(1)− − →AMM[9:t 0,4:t 1]|Adv[n 0−3:t 0, n1+ 2:t 1]| ···
(2)− − →AMM[12:t 0,3:t 1]|Adv[n 0−3:t 0, n1+ 2:t 1]| ···
(3)− − →AMM[9:t 0,4:t 1]|Adv[n 0:t0, n1+ 1:t 1]| ···
This gives the adversary a gain of1·price(t 1) = 9,
which is greater than the gain obtainable without exploiting
the mempool, and it actually turns out to be the MEV inσ.
More in general, devising the optimal MEV-extracting strategy
depends on a multitude of factors: the AMM reserves, the
external token prices, the direction of the swap in the mempool
(i.e.,swap0vs.swap1), as well as the swap amount and lower
bound. The resulting combinatorial explosion of cases and
subcases makes manual reasoning about MEV extremely error-
prone. Our machine-checked proof in Lean (§VI-B) addresses
this complexity, by establishing the MEV when the adversary
can exploit a transaction from the mempool.
III. SYSTEM MODEL
In this section, we introduce our Lean formalization of smart
contracts executed on blockchains (§III-A). We illustrate it by
formalizing theAirdropcontract presented in §II (§III-B).
A. System state
Awalletis a container of tokens, possibly of different
types. We model wallets as functions from token types to real-
valued amounts. We explicitly separate the adversary from
honest users, reflecting the different assumptions we make
about their capabilities. In particular, we assume our adversary
to bewealthy, i.e., able to spend arbitrarily large amounts of
tokens when mounting an attack. Honest participants, instead,
own a limited amount of tokens, as in the real world. We
formalize these assumptions by defining two distinct wallet
types:Wallet, holding a non-negative amount of tokens for
honest participants and contracts, andWalletAdv, holding
arbitrary token amounts (possibly negative) for the adversary.We parametrize these types byToken, a type representing the
token types:
def Wallet (Token : Type) : Type := Token→R≥0
def WalletAdv (Token : Type) : Type := Token→R
We parameterise our model with a typeState, which
represents the state of an arbitrary contract running in an
honest environment. This parameter will be instantiated when
defining specific contracts, e.g. in §III-B, §V and §VI. Intu-
itively, suchStatecomprises the contract variables, its wallet,
the wallets of the honest participants, and the mempool.
We model the interactions between the adversary, the honest
participants, and the contract as a state transition system.
Its states are typesSysState, consisting of aStateand the
adversary’s wallet:
structure SysState {Token State : Type} where
∆: WalletAdv Token
s : State
The rules of the transition system are defined by the
structureSystem(Figure 4), which specifies the types:
•Token, representing the possible token types exchanged
within the system;
•State, mentioned above;
•Move, representing the possible adversarial moves, e.g.,
crafting and executing a transaction, or fetching from the
mempool a transaction sent from an honest participant
and executing it.
ASystemmust provide asemanticsfor adversarial moves
(note that honest participant’s moves are already taken into
account by the transactions in the mempool). Thesemantics
is apartialfunction, mapping aSysStateand aMoveto a
newSysState. The semantics is undefined (none) when it
is impossible to perform the given move. In practice, this
corresponds to the case where a transaction reverts.
In order to prove general properties onSystems — i.e.,
properties that do no depend on the specific instantiation of its
semantics — we require a few more fields and assumptions.
First,Systemmust provide a function (honTokens) mapping
eachStateto the cumulative amount of tokens owned by the
contract and honest participants (hereafter, referred to as the
“honest tokens”). Second, we postulate that thesemantics
preserves tokens: we model this through the assumption
preserveTokens, which forbids the minting and the burning of
tokens. Finally, aSystemmust associate each token type with
aprice: formally, this is modelled as a functiontokenValue
that maps any wallet to a real number, denoting the cumulative
price of all the tokens in the wallet. We require this value
function to be non-negative and additive.
Givensys : System, we can then prove a few basic prop-
erties. For instance, we establish that the value of the empty
wallet is zero, and that the value function preserves subtraction
and is monotonic on wallets.
structure System where
Token : Type
State : Type
Move : Type
semantics : @SysState Token State→Move→
Option (@SysState Token State)
honTokens : State→Wallet Token
preserveTokens :∀σm,
match semanticsσm with
| .none => True
| .someσ’ =>∀τ, honTokensσ.sτ+σ.∆τ
= honTokensσ’.sτ+σ’.∆τ
tokenValue : WalletAdv Token→R
tokenValue_nonneg :∀f, f≥0→tokenValue f≥0
tokenValue_additive :∀f g,
tokenValue (f + g) = tokenValue f + tokenValue g
Fig. 4.Systemmodel in Lean.
theorem tokenValue_zero : sys.tokenValue 0 = 0
theorem tokenValue_sub (f g : WalletAdv _) :
sys.tokenValue (f - g)
= sys.tokenValue f - sys.tokenValue g
theorem tokenValue_monotonic (f g : WalletAdv _) :
f≤g→sys.tokenValue f≤sys.tokenValue g
For readability, hereafter we abbreviateSysState, instanti-
ated withsys.Tokenandsys.State, assys.sysState:
abbrev System.sysState : Type :=
@SysState sys.Token sys.State
B. Example: formalization of the Airdrop contract
We exemplify our Lean formalization to model the Airdrop
contract introduced in Section II. We start by providing some
general definitions regarding the participants, the exchanged
tokens, and the the transactions. This skeleton will be reused
also for the other use cases.
We define a typeParticipantto describe who can interact
with the contract. The type comprises infinitely many honest
participants and an adversary.
inductive Participant
| Hon : String→Participant
| Adv : Participant
The typeTokendenotes the token types exchangeable
through the contract. Our Airdrop uses a single token type:
inductive Token
|τ0: Token
Coherently with the Solidity code in Figure 1, the Airdrop
contract features a single functiondrop, which allows any
participantPto withdraw any amountv>0of tokens
from the contract, failing ifvexceeds the contract balance.
Correspondingly, transactions will take the following form:
inductive Tx
| drop (P : Participant) (v :R+) : Tx
The argumentPin adroptransaction implicitly denotes that
the transaction is signed byP. We assume that transactions arenotmalleable, i.e. the adversary cannot alter the parameterv
without invalidating the signature.
TheStatetype is a structure that denotes the state of
the blockchain without the adversary. More specifically, the
fieldbalrepresents the contract’s balance, while the field
waldenotes the aggregated wallets of all honest participants.
Since MEV analysis does not require distinguishing between
individual honest users, their holdings are abstracted into this
single cumulative wallet. The fieldmempoolrepresents the
transactions previously broadcast by honest participants but
not yet finalised on-chain. Formally, we represent themempool
as an association list mapping transaction identifiers (TxId)
with their associated transactions.
structure State where
bal : Token→R≥0
wal : Wallet Token
mempool : AssocList TxId Tx
We abbreviate the associated system state asADState:
abbrev ADState := @SysState State Token
We now turn to defining the type of adversarial moves. To
this aim, we start by identifying the subset of transactions
that can be crafted by the adversary alone. In our scenario,
the adversary can only craftdroptransactions signed byAdv
itself. This is formalized by propertyadvTx.
inductive advTx : Tx→Prop
| drop {v} : advTx (.drop .Adv v)
TheMovetype captures all possible adversarial actions,
namely: (i) craft a transaction using its own knowledge (i.e.,
Adv’s private key) and append it directly to the blockchain
(adv), or (ii) select a transaction from the mempool and include
it in the blockchain (mempool).
inductive Move
| adv : (t : Tx)→advTx t→Move
| mempool : TxId→Move
The semantics of aMoveis to cause anADStateupdate,
or fail, coherently withSystem.semantics. More precisely,
anadvmove transfers the specified amount of tokens to the
adversary, removing tokens from the contract balance (bal)
and adding them to the adversary’s (∆, in the system state),
accordingly. If there are not enough tokens inbal, the move
has no effect.
Instead, amempoolmove looks up the corresponding transac-
tion in theState.mempoolfield. If there is no such transaction,
the move has no effect. Otherwise, if we find a corresponding
drop P vtransaction, we attempt to execute it, sendingv
tokens toP. If there are not enough tokens inbal, the move has
no effect. Otherwise, we update the contract balance (bal) and
P’s wallet. We distinguish between two cases: ifPis honest,
then we updatewal, while if it is the adversary we update∆.
If the mempool transaction succeeds, it is removed from the
mempoolfield so that it is not reused later on.
Using the above semantics, we define theAirdroptype
as aSystemmodelling the whole contract. While doing that,
we define theAirdrop.honTokensfield, which counts all the
circulating tokens not owned byAdv, by essentially summing
balandwal. We also price the token typeτ 0, thereby
defining theAirdrop.tokenValuefunction which assigns a
value to any wallet. We finally prove the required properties
according to the otherSystemfields, i.e.,preserveTokens,
tokenValue_nonneg, andtokenValue_additive.
def Airdrop : System where ...
Based on this system model, we will analyse the MEV of
the Airdrop contract in §IV-D.
IV. MEV
In this section we present our Lean formalization of MEV
and a general proof technique for certifying the MEV of
contracts. We start in §IV-A by defining thegainof the
adversary upon performing moves, which is the basis for
defining MEV later in §IV-B. In §IV-C we introduce our proof
technique in the form of a MEV characterization theorem.
We illustrate such technique in §IV-D, by applying it to our
Airdrop contract.
A. Gain
We define the adversarial gain between two system states as
the difference of the adversarial wallets. A simple transitivity-
like property follows.
def gainState (σ σ’ : sys.sysState) :R:=
sys.tokenValueσ’.∆- sys.tokenValueσ.∆
theorem gainState_trans (σ σ’σ’’ : sys.sysState) :
gainState sysσ σ’ + gainState sysσ’σ’’
= gainState sysσ σ’’
In order to define the gain achieved by the adversary by
performing alistof moves, we first generalize thesemantics
of adversarial moves. The effect of a list of moves is the
composition of the individual effect of each move in the list,
discarding those that fail. For brevity, we omit the definition
of this function — hereafter, we will similarly omit long
definitions, referring to [26] for their Lean code.
def semMoves (σ: sys.sysState)
(tr : List sys.Move) : sys.sysState
The adversarial gain of a list of moves is given by compar-
ing the initial and final states.
def gainMoves
(σ: sys.sysState) (tr : List sys.Move) :R:=
gainState sysσ(semMoves sysσtr)
We establish a few basic properties ofgainMoves: the empty
list gives zero gain, and the gain of the first move in a list can
be separated from the gain of the rest of the moves.theorem gainMoves_empty (σ: sys.sysState) :
gainMoves sys s [] = 0
theorem gainMoves_step (σ: sys.sysState)
(m : sys.Move) (ms : List sys.Move) :
gainMoves sysσ(m :: ms)
= match sys.semanticsσm with
| .none => gainMoves sysσms
| .someσ’ => gainState sysσ σ’ + gainMoves sysσ’ ms
The gain of a list of moves is bounded above by the value
of all the circulating honest tokens. This will be exploited to
obtain an upper bound to the extractable value.
theorem gainMoves_bound (σ: sys.sysState)
(tr : List sys.Move) :
gainMoves sysσtr≤sys.tokenValue (sys.honTokensσ.s)
B. MEV definition
A system stateσhas MEV equal tovwhen two conditions
are met:(i)there is a list of movestrthat, when performed
inσ, gives the adversary a gain ofv;(ii)any list of movestr,
when performed inσ, gives the adversary a gain of at mostv:
structure MEV (σ: sys.sysState) (v :R) : Prop where
trace_reaches_v :∃tr, gainMoves sysσtr = v
other_traces_worse :∀tr, gainMoves sysσtr≤v
We remark that MEV is not always guaranteed to exist. For
instance, if the adversary can extract any real value<1, but
they cannot extract1, there is nomaximumvalue that can
be extracted, but only a least upper bound. To account for
this, we also define the “least upper bound of the extractable
values”MEVsup. The definition only requires traces whose
gain is arbitrarily close tov. We prove thatMEVsupalways
exists, is unique, and non-negative. Further, whenMEVexists,
it coincides withMEVsup, soMEVis unique and non-negative.
structure MEVsup (σ: sys.sysState) (v :R) : Prop where
traces_approx :∀(ε:R+),∃tr,
gainMoves sysσtr +ε≥v
other_traces_worse :∀tr, gainMoves sysσtr≤v
C. Proving MEV
In principle, one could attempt to prove that a systemsys
in stateσhas a given MEV equal tovby directly applying
the definition ofMEV. Doing that would require to 1) find a
trace givingAdva gainv, and 2) show that no other trace can
extract more value. The second task, in particular, is quite
hard, as it requires reasoning onallthe (infinitely many)
adversarial traces. To address this challenge, we introduce a
MEV characterization theoremthat provides a principled proof
technique for establishing that a given value indeed coincides
with the MEV . More precisely, usingMEV.characterization
theorem (Figure 5) requires following these steps:
1) Fix the system stateσfrom which the adversary is going
to extract MEV .
2) Specify aninvariantinvon system states. The invariant
must be accompanied with a proof ensuring that it holds
theorem MEV.characterization
(σ: sys.sysState)
(inv : sys.sysState→Prop)
(MEV_guess : (σ: sys.sysState)→invσ→R≥0)
(invariant_init : invσ)
(invariant_sound :
∀{m : sys.Move} {σ 0σ1: sys.sysState},
sys.semanticsσ 0m = someσ 1→
invσ 0→invσ 1)
(MEV_guess_coherent :∃tr : List sys.Move,
gainMoves sysσtr = MEV_guessσinvariant_init)
(MEV_guess_sound :
∀{m : sys.Move} {σ 0σ1: sys.sysState},
(hmove : sys.semanticsσ 0m = someσ 1)→
(σ0_inv : invσ 0)→
letσ 1_inv := invariant_sound hmoveσ 0_inv
gainState sysσ 0σ1+ MEV_guessσ 1σ1_inv≤
MEV_guessσ 0σ0_inv) :
MEV sysσ(MEV_guessσinvariant_init)
Fig. 5. MEV characterization theorem (soundness).
onσ(invariant_init), and that it is preserved by any
adversarial move (invariant_sound).
3) Specify aguess functionMEV_guessthat maps any state
satisfying the invariant to a value inR≥0, which is a
candidate MEV for that state.
4) Find an adversarial trace that extracts fromσexactly
MEV_guessσ. This ensures that, on the system stateσ,
the guess function provides a lower bound to the MEV .
We call this propertycoherence(MEV_guess_coherent).
5) Prove that the guess function is an upper bound for
MEV . More precisely, we must prove that, ifσ 0is any
(invariant-abiding) system state, then moving to another
stateσ 1cannot induce a gain for the adversary that is
greater than the difference between the guesses. We call
this propertysoundness(MEV_guess_sound):
MEV_guessσ 0≥gainStateσ 0σ1+MEV_guessσ 1
Once all the steps above are completed, our characterization
theorem establishesMEVσ(MEV_guessσ), proving that the
MEV inσis indeed the one given by the guess function.
The choices of the invariant and of the guess function are
crucial. Intuitively, the invariant defines an over-approximation
of the states that can be reached fromσby the adversary.
Choosing a suitable invariant is key to simplify the subsequent
steps, since they involve properties that are only required to
hold on invariant-abiding states. In our experience, simple
invariants are enough to this purpose: e.g., both in the Coin-
Pusher and in the AMM, it is enough to impose a bound on
the size of the mempool. The other crucial step is choosing
the guess function. Roughly, this corresponds to estimate the
value extracted by an adversary following the optimal strategy.
Fortunately, this estimate must only be provided for the states
satisfying the invariant, simplifying this task.
Our Lean formalization of the MEV characterization the-
orem closely follows the previous informal discussion, withthe only technical difference that one more argument must be
passed to the guess function to ensure the invariant holds.
Below, we sketch the proof forMEV.characterization.
Proof (sketch).We have to prove thatMEV_guessσis the
MEV inσ. The itemtraces_reaches_vfollows directly from
MEV_guess_coherent. Forother_traces_worse, consider an
arbitrary tracem 0, . . . , m n−1 of moves starting fromσ 0=σ
and going through statesσ 1, σ2, . . . , σ n. We have that:
gainMovesσ[m 0, . . . , m n−1]
=gainStateσ σ 1
+···
+gainStateσ n−2σn−1
+gainStateσ n−1σn
≤gainStateσ σ 1
+···
+gainStateσ n−2σn−1
+gainStateσ n−1σn
+MEV_guessσ n sinceMEV_guessσ n≥0
≤gainStateσ σ 1
+···
+gainStateσ n−2σn−1
+MEV_guessσ n−1 byMEV_guess_sound
≤gainStateσ σ 1
+···
+MEV_guessσ n−2 byMEV_guess_sound
≤ ···
≤MEV_guessσbyMEV_guess_sound
In the chain of inequalities above we repeatedly apply the
MEV_guess_soundinequality, replacing at each step the last
part of the sumgainStateσ iσi+1+MEV_guessσ i+1with
its upper boundMEV_guessσ i. At the end, the whole sum is
reduced toMEV_guessσ.
TheMEV.characterizationtheorem ensures that if there
exists a sound and coherent guess function, then that function
actually provides the MEV . We also show that our character-
ization iscomplete: whenever MEV exists, there also exists a
sound and coherent guess function (Figure 6).
Proof (sketch).Since by assumption MEV exists, we choose
as guess function the one that maps each (invariant-abiding)
state to its MEV . Coherence is straightforward, since the
definition of MEV (trace_reaches_v) ensures that there is
a trace extracting that value.
For soundness, letmbe a move from stateσ 0toσ 1. We also
lettrbe the trace providing MEV forσ 1(trace_reaches_v),
hencegainMoves tr = guessσ 1. The definition of MEV
(other_traces_worse) ensures that the value extracted by any
tracetr’fromσ 0is bounded by the MEV . In particular, choose
theorem MEV.characterization_complete
(σ: sys.sysState)
(inv : sys.sysState→Prop)
(invariant_init : invσ)
(invariant_sound :
∀{m : sys.Move} {σ 0σ1: sys.sysState},
sys.semanticsσ 0m = someσ 1→
invσ 0→invσ 1)
(mev :∀σ’, invσ’→ ∃v, MEV sysσ’ v) :
∃guess : (σ’ : sys.sysState)→invσ’→R≥0,
-- guess is coherent
(∃tr : List sys.Move,
gainMoves sysσtr = guessσinvariant_init)∧
-- guess is sound
(∀{m : sys.Move} {σ 0σ1: sys.sysState},
(hmove : sys.semanticsσ 0m = someσ 1)→
(σ0_inv : invσ 0)→
letσ 1_inv := invariant_sound hmoveσ 0_inv
gainState sysσ 0σ1+ guessσ 1σ1_inv≤
guessσ 0σ0_inv)
Fig. 6. MEV characterization theorem (completeness).
tr’ = m::tr, obtaininggainMovesσ 0(m::tr)≤guessσ 0.
From this and theoremgainMoves_step, we conclude:
gainStateσ 0σ1+ guessσ 1
=gainStateσ 0σ1+ gainMoves tr
=gainMovesσ 0(m::tr)
≤guessσ 0
Overall, formalizing our system model and the MEV-related
theorems required∼600 lines of Lean code.
D. Example: MEV of the Airdrop contract
We now analyse the MEV of the Airdrop contract
from §III-B. To this purpose, we exploit our MEV charac-
terization theorem. We start by defining an invariant. For this
basic contract, a trivial invariant suffices.
def Airdrop_invariant (σ: ADState) : Prop := True
We then define our guess function. As intuition suggests,
we guess that the MEV is obtained by transferring the entire
contract balance to the adversary.
def Airdrop_MEV_guess (σ: ADState)
(σ_inv : Airdrop_invariantσ) :R≥0 :=σ.s.bal .τ 0
Finally, by leveraging our MEV characterization theorem,
we establish that our guess is indeed the MEV .
theorem MEV_Airdrop (σ: ADState) :
MEV Airdropσ(Airdrop_MEV_guessσTrue.intro)
V. MEVOF THECOINPUSHER CONTRACT
We now formalize the CoinPusher contract we described
in §II-A. Some parts are similar to the Airdrop contract: e.g.,
typesParticipantandTokenare the same, since we use the
same participants and token types. Transactions are instead
modelled by the new type:inductive Tx
| push (P : Participant) (v :R+) : Tx
A transactionpush P vsendsvtokens (of typeτ 0) to the
contract from participantP, causingPto win the entire contract
balance ifvtips such balance over the threshold.
Then, we let the adversary send only their own tokens:
inductive advTx : Tx→Prop
| push {x} : advTx (.push .Adv x)
The contract state contains the same fields as in the Air-
drop contract, plus an additional field to represent a generic
threshold(which we chose to be100in §II-A).
structure State where
threshold :R+
bal : Token→R≥0
wal : @Wallet Token
mempool : AssocList TxId Tx
We denote the associated system state asCPState.
abbrev CPState := @SysState Token State
The typeMoveof adversarial moves is identical to that
for the Aidrop contract: the adversary can append to the
blockchain either one of its own transactions or a transaction
from the mempool. The semantics of aMovedefines the
contract behaviour. An adversarialdropsends tokens from
the adversary to the contract, possibily making the adversary
win the game. This updates∆andbalaccordingly. Instead, a
mempool move sends tokens from honest participants to the
contract (if there are enough), possibily making the partici-
pants win the game. This updateswalandbalaccordingly.
def semTx (tx : Tx) (σ: CPState) : Option CPState := ...
def semMove (σ: CPState) (m : Move) : Option CPState :=...
We can finally define the CoinPusher contract
def CoinPusher: System := ...
We now turn to the study of MEV . Unlike for the Aidrop
contract, the MEV is now actually affected by the mempool.
We therefore choose to establish MEV in two distinct cases:
•the case where the mempool is empty, and
•the case where the mempool contains one transaction.
As we will see, the general case where the mempool contains
Ntransactions is a simple extension of these two cases:
roughly, the strategy of the adversary is to apply iteratively
Ntimes the strategy for the singleton mempool. Because of
this, we focus on the first two core cases.
For the former case, we declare the following invariant.
def CoinPusher_empty_invariant (σ: CPState) : Prop :=
σ.s.mempool.isEmpty
If there are no transactions in the mempool, the optimal
strategy for the adversary is topushenough tokens to trig-
ger the win. For the sake of simplicity, below we choose
to sendσ.s.thresholdtokens, even if a smaller amount
(σ.s.threshold -σ.s.bal .τ 0) would also suffice.
def CoinPusher_strategy_empty (σ: CPState) :
List Move := [.adv (.push .Advσ.s.threshold) .push]
We define a guess function for the MEV , posing that we
can extract the entire contract balance as MEV .
def CoinPusher_empty_MEV_guess (σ: CPState)
(σ_inv : CoinPusher_empty_invariantσ) :R≥0 :=
σ.s.bal .τ 0
We can prove that our guess function is sound and coherent
(exploiting our strategy). This makes it possible to invoke
our MEV characterization theorem and establish MEV for the
empty mempool case.
theorem MEV_CoinPusher_empty (σ: CPState) :
σ.s.mempool = .nil→
MEV CoinPusherσ(CoinPusher_empty_MEV_guessσ)
We now turn to the case where the mempool contains one
transaction, i.e., it is a singleton list. We use the following
invariant. Note that we have to account for the mempool be-
coming empty after its transaction is appended, so the invariant
actually requires that the mempool is either a singleton or
empty. For the sake of simplicity, we also require that if the
mempool is a singleton, its transaction is from the honest
participants. Indeed, adversarial transactions in the mempool
are irrelevant for the purposes of MEV , so we can ignore them.
def CP_one_or_less_invariant (σ: CPState) : Prop :=
σ.s.mempool.isEmpty∨
(∃idx tx,σ.s.mempool = .cons idx tx .nil∧tx.P̸=.Adv)
The guess function is more complex w.r.t. the empty mem-
pool case. We define it by cases, according to the mempool:
1) If the mempool is empty, our guess isσ.s.bal .τ 0, the
same we mentioned earlier.
2) Otherwise, if the mempool is the singletontx(apush
transaction from the honest participants), the best strategy
for the adversary is(i)first, trigger a win in the contract,
emptying its balance,(ii)attempt to appendtx,(iii)trig-
ger the win again. The first step extractsσ.s.bal .τ 0
tokens, emptying the contract balance.
The second step, appendingtx, might fail if the honest
participant does not have enough tokens to execute it,
i.e. iftx.v >σ.s.wal .τ 0, in which case it has no
effect. Further, even iftxsucceeds, it might send to the
contract enough tokens to immediately trigger the win
for the honest participant, iftx.v≥σ.s.threshold. In
this case, the tokens are immediately sent back to the
participant, and the transaction has no net effect, since
the contract balance was empty. Otherwise,txsucceeds
and sends fewer tokens than the threshold, loading the
contract balance withtx.vtokens. Overall, while the
second step does not make the adversary directly gain
anything, it can potentially load the contract balance.
Finally, the third step extracts the new contract balance.
This could betx.vor zero depending on whethertx
succeeded in loading the contract or not, respectively.
Coherently with our strategy, we guess the MEV to be
σ.s.bal .τ 0+ tx.vor justσ.s.bal .τ 0.def CoinPusher_one_or_less_MEV_guess (σ: CPState)
(σ_inv : CP_one_or_less_invariantσ) :R≥0 :=
matchσ.s.mempool with
| .nil =>σ.s.bal .τ 0
| .cons id tx .nil =>
if tx.v <σ.s.threshold∧tx.v≤σ.s.wal .τ 0
thenσ.s.bal .τ 0+ tx.v
elseσ.s.bal .τ 0
| .cons id tx (.cons id2 tx2 rest) => by
exfalso; ...-- contradictsσ_inv
def CP_strategy_singleton_mempool (σ: CPState)
(id : TxId) (tx : Tx) : List Move :=
[ .adv (.push .Advσ.s.threshold ) .push
, Move.mempool id
, .adv (.push .Advσ.s.threshold ) .push ]
We can prove that our guess function is sound
and coherent (exploiting our strategy). This makes it
possible to invoke our MEV characterization theorem
and establish MEV for the singleton mempool case.
theorem MEV_CoinPusher_singleton
(σ: CPState) (id : TxId) (tx : Tx)
(singleton :σ.s.mempool = .cons id tx .nil)
(nonadv : tx.part̸=.Adv) :
MEV CoinPusherσ
(if tx.v <σ.s.threshold∧tx.v≤σ.s.wal .τ 0
thenσ.s.bal .τ 0+ tx.v
elseσ.s.bal .τ 0)
We remark that this result extends to the general case
where the mempool contains any number of transactions. The
optimal strategy here is to attempt to append all the mempool
transactions, while interleaving them with an adversarial trans-
action that triggers the win and empties the contract balance:
[trigger 0, tx 1, trigger 1, tx 2, ..., tx n, trigger n].
Overall, the formalization of the CoinPusher contract and
the proofs to establish its MEV amount to∼1000 lines of
Lean code. This required more effort than the Airdrop contract,
because the value extraction strategy is no longer trivial, but
did not pose a significant challenge.
VI. MEVOF THEAMMCONTRACT
We now move to our main contribution, the formalization
of an Automated Market Maker contract, which we described
in §II-B.
For this contract, theParticipanttype is akin to the
previous examples, with one adversary, and infinitely many
honest ones. The AMM swaps exchange two different types
of tokens:
inductive Token
|τ0: Token
|τ1: Token
The only operations supported by our AMM are tokens
swaps. We define transactions accordingly.
inductive Tx
| swap (P : Participant) (v 0:R+)
(τ: Token) (vmin :R≥0) : Tx
When aswap P v 0τvminis executed, participantPex-
changesv 0of their ownτtokens with at leastvmintokens of
the other type in the AMM reserves. If such an exchange is
impossible, i.e. whenPdoes not own enough tokens or when
the AMM exchange rate would cause fewer thanvmintokens
to be exchanged, the transaction has no effect.
The contract state features the same fields as the Airdrop
contract (i.e.bal,wal, andmempool). The resulting system
state is then denoted with withAMMState.
Again, the typeMoveis analogous to the other examples: the
adversary can either append a transaction from the mempool or
one of their own. Like in theCoinPusherexample, an adversar-
ialswapupdates△andbal, while a mempool move exchanges
tokens between a honest participant and the contract, updating
walandbalaccordingly.
To study the MEV of the AMM contract, we focus on two
cases depending on the initial state of the mempool:
•the mempool is empty, and
•the mempool contains one transaction.
As we will see, the general case where the mempool contains
Ntransactions is a simple extension of these two cases:
roughly, the strategy of the adversary is to apply iteratively
Ntimes the strategy for the singleton mempool. Because of
this, we focus on the first two core cases.
A. Empty mempool
For the empty mempool case, we define a simple invariant:
def empty_mempool_invariant (σ: AMMState) : Prop :=
σ.s.mempool.isEmpty
We easily prove the invariant to be sound.
We now define our guess function for the empty mempool
case. We start by definingextractableσas the value that can
be extracted by rebalancing the AMM. This can be expressed
with the following formula, which we derive from [23].
def extractable (σ: AMMState) :R≥0 :=
⟨( Real.sqrt (pr .τ 0*σ.s.bal .τ 0) -
Real.sqrt (pr .τ 1*σ.s.bal .τ 1) )^2,. . .⟩
We then define our guess function asextractableσ.
def AMM_MEV_guess (σ: AMMState)
(σ_inv : empty_mempool_invariantσ) :R≥0 :=
extractableσ
We finally prove that our guess is indeed the MEV .
theorem MEV_empty_mempool (σ: AMMState)
(σ_inv :σ.s.mempool = .nil) :
MEV (AMM pr)σ(AMM_MEV_guess prσ σ_inv)
This effectively guarantees that the best adversarial strategy,
when the mempool is empty, is to rebalance the AMM.
Overall, formalizing the AMM contract required∼700 lines
of Lean code, while establishing MEV in the empty mempool
case required further∼500 lines. The main challenge here was
to deal with the mathematical formulas that arise in the proofs.B. Non-empty mempool
We now turn to the case where the mempool contains one
transactiontx. Here, our invariant actually requires that the
mempool contains onlytxor is empty, sincetxis consumed
when it is fired. Further, we also require thattxis owned by
a honest participant (tx.part̸=.Adv) and thattxrequires a
minimum positive amount of tokens in exchange (tx.vmin
> 0). Indeed, adversarial transactions in the mempool are
pointless, since they can be crafted, so we can rule them out.
Further, having a mempool transaction withtx.vmin = 0leads
to a corner case in which MEV does not exist(see Section A).
def inv_one_or_less (σ: AMMState) : Prop :=
σ.s.mempool.isEmpty∨
(∃idx tx,σ.s.mempool = .cons idx tx .nil∧
tx.vmin > 0∧tx.part̸=.Adv)
We now define our guess function, which turns out to be
significantly more complex than that for the empty mempool
case. We have to provide a guess for all the states satisfying
the invariant, so we must handle mempools having size zero or
one. When the mempool is empty, we guessextractableσ,
coherently with the empty mempool case. When there is one
transactiontxin the mempool, we proceed as follows.
We first check iftxcan be beneficial to the adversary. This
happens when:
1) Transactiontxcan actually be executed in some AMM
state, i.e., its honest sender actually owns the tokenstxis
trying to swap (tx.inputVal≤σ.s.wal tx.inputTok).
2) Transactiontxcauses its honest sender to transfer to the
contract an amount of tokens whose value (tx.inputVal
* pr tx.inputTok) is larger than the value of the min-
imum amount of tokens it is requiring in exchange
(tx.vmin * pr (other_tok tx.inputTok)).
If either of the above conditions does not hold,txis useless
for the adversary, who can then disregardtx. In this case, our
guess is the same as the one for the empty mempool case,
henceextractableσ.
Instead, when both of the above conditions hold, we exploit
txas follows. First, the adversary employs its unlimited token
reserves and performs a swapmove, bringing the AMM to
a stateσ’where executingtxwill transfer to the honest
participant exactlytx.vmintokens. Intuitively, from the point
of view of the honest participant,σ’is theworst statewhere
txstill can be executed. Dually,σ’is also thebest statefor
the adversary in which to executetx. We refer toσ’as the
tight statefortx. After themove, having reached the tight state
the adversary indeed appendstxto the blockchain. After that,
we reach a new stateσ’’where the mempool is empty, so the
adversary proceeds as in the empty mempool case.
We coherently define our guess function as the sum of:
1) the gain ofmove(gainMoves (AMM pr)σ[move]);
2) the gain oftx, which is zero, since it does not directly
transfer tokens to or from the adversary;
3) the gain from the rebalancing, i.e.,extractableσ’’.
We remark that the gain of the first step may be negative.
The adversary can therefore temporarilylosevalue in that step,
which makes the overall MEV strategy non-trivial. In our Lean
development, we first defined our guess function as having
codomainR. We then showed that its result is always non-
negative, allowing its codomain to be restricted toR≥0, as
required by ourMEV.characterizationtheorem. This actually
shows how the temporary loss of value for the adversary at
the first step is then compensated by the next steps.
We finally remark that, as a corner case, it is possible that
the initial stateσis already tight fortx. If so, nomoveis
needed, and we simply useextractableσas our guess.
def AMM_MEV_guess’ (σ: AMMState)
(σ_inv : inv_one_or_lessσ) :R:=
matchσ.s.mempool with
| .nil => extractable prσ
| .cons id tx .nil =>
if tx.inputVal≤σ.s.wal tx.inputTok∧
(tx.inputVal * pr tx.inputTok >
tx.vmin * pr (other_tok tx.inputTok))
then. . .
letσ’ := tight_state_from_mempoolσid tx. . .
letσ’’ := state_after_tightσid tx. . .
match move_from_to_stateσ σ’ with
| .some move =>
gainMoves (AMM pr)σ[move] + extractable prσ’’
| .none =>--σ=σ’, no move needed
extractable prσ’’
else
extractable prσ
| _ =>. . .-- contradicts the invariant
def AMM_MEV_guess (σ: AMMState)
(σ_inv : inv_one_or_lessσ) :R≥0 :=
⟨AMM_MEV_guess’ prσ σ_inv ,. . .⟩
We finally establish MEV for the AMM contract when the
mempool contains a single transaction. To do so, we prove our
guess to be coherent, showing that its value can actually be
extracted using a trace. We also prove our guess to be sound,
showing that no adversarial move can extract more value.
theorem MEV_singleton_mempool (σ: AMMState)
(id : TxId) (tx : Tx) (vmin_pos : tx.vmin > 0)
(singleton :σ.s.mempool = .cons id tx .nil)
(part_nonAdv : tx.part̸=.Adv) :
letσ_inv : inv_one_or_lessσ:=. . .
MEV (AMM pr)σ(AMM_MEV_guess prσ σ_inv)
Overall, establishing MEV in the singleton mempool case
required∼3200 lines of Lean code, on top of the base AMM
model (∼700 lines) and the empty mempool case (∼500
lines). The main challenge here was dealing with the complex
extraction strategy, requiring the proofs to consider all the
possible cases. Further, the involved mathematical formulas
were more complex, and required more effort to handle.
VII. LIMITATIONS
In this section we discuss how our design choices affect the
practical applicability of the proposed Lean formalization.
Realvs.integer arithmetic:In our MEV formalization,
we represent token balances and their market values as realnumbers. In practice, however, blockchain platforms use high-
precision integers to encode such amounts. For instance, in
Ethereum it is common to employ the integer typeuint256,
since floating point types are not supported. As a consequence,
when a financial contract performs its numerical computations
— e.g., calculating the exchange rate in aswapof an AMM
— the result is inevitably affected by a small rounding error.
Although these errors usually have a negligible economic
impact on the real-world usage of the contract, it is possible to
craft artificial scenarios where the MEV differs substantially
depending on whether rounding errors are present or not. For
instance, consider a slightly modifiedCoinPusherwhere the
winning threshold is9991, and a0.1%fee is subtracted from
the value sent to the contract upon each call topush. Consider
a state where the contract has zero balance and the mempool
contains apushtransaction where a honest participant is
sending10001tokens. Using real numbers, thepushwould
compute the fee as10.001and transfer9990.999to the con-
tract — so, slightly less than the threshold required to trigger
the win. The adversary could extract a MEV of9990.999by
back-running the mempool transaction with anotherpushof
1.0001or more, triggering the win. Instead, using integers,
thepushwould round the fee to10, and transfer9991token
units to the contract balance — i.e. exactly the threshold value.
Here, the MEV is zero, since the mempool transaction would
immediately trigger the win for the honest user, hence it is
useless for the adversary.
Adapting our system model and MEV formalization to
use integers instead of reals is easy, but we anticipate that
it would significantly complicate the reasoning needed to
establish MEV for certain contracts. For instance, in our
AMM, performing two consecutive adversarialswaps has the
same effect as a combined singleswap, which simplifies the
treatment. This is no longer the case when rounding errors are
taken into account. On the positive side, using integers would
ensure that MEV always exists. This does not hold with real
numbers: anAirdropvariant which allows to withdraw (drop)
any amountsmallerthan its balance has no associated MEV .
Indeed, any strategy can be improved by adding one more
dropto grab a tiny amount of additional tokens.
Proof automation:While Lean does provide several
tactics to automate the proof of certain kinds of mathematical
goals, in our experience we often wished for more powerful
arithmetic simplification tactics. For instance, the proofs for
our AMM model often make use of inequalities involving
square roots. We managed to prove these only through several
manual algebraic steps, invoking each time a suitable theorem
from the mathematical library. This could change in the future
as Lean improves its tactics.
Adversary model:Our system model keeps the adversary
syntactically distinct from honest users. This choice requires
a certain care when encoding smart contracts into our system
model, especially for contracts implementing access control
mechanisms. In general, the system designer must ensure that
theMovetype and its associated semantics faithfully capture
all the possible adversarial actions. Omitting even a single
adversarial move could lead to overlooked attacks.
VIII. RELATED WORK
Analysis tools for MEV:The seminal work [14] was the
first to propose a general definition of MEV and a tool to
estimate MEV upper bounds. Their verification technique is
based on a symbolic semantics that over-approximates the set
of execution paths and their reachable states. Based upon this
symbolic semantics, they encode the problem of estimating a
MEV bound as a reachability problem. Compared to our work,
this technique requires less manual effort, since the designer
is only required to provide a specification of the contract
(in their domain-specific language), and from that point the
tool automatically performs the analysis of MEV . A main
drawback of the approach is the lack of scalability (as observed
in [7]): even for relatively simple contracts, the exponential
blowup of the generated paths may lead the tool to exhaust
the computational resources. Another difference with our work
is that our notion of MEV isexact: whenMEV sysσ v
holds, it actually means thatvcan be extracted, and there
is no adversarial strategy that can extract more. The technique
in [14] insteadover-approximates MEV , without guaranteeing
that the verified upper bound can actually be extracted.
The work [7] approached the problem of MEV estimation
from a different perspective, by proposing a machine-learning
technique tounder-approximate MEV . Their algorithm takes
as input a blockchain state and a mempool, and gives as
output a sequence of transactions (containing both transactions
crafted by the adversary and transactions from the mempool)
that can be played by the adversary to extract value. This
approach is more scalable than [14], and allows the adversary
to fine-tune the computational resources used by the algorithm
in order to match the available hardware. Of course this
technique does not guarantee that the synthesised sequence
of transactions is optimal: instead, our approach pursues the
goal of certifying the optimality of the adversarial strategy.
Formalization of the adversary:Our definition of MEV
keeps the adversary distinct from the other participants — so
being similar in spirit to [14], where MEV is parameterized by
the player who extracts it. As noted in §VII, this requires some
extra care when modelling the contract behaviour, to avoid the
risk of omitting some adversarial actions. Some approaches to
avoid fixing the identity of the adversary have been proposed
in literature. The work [15] defines an adversary-agnostic
MEV by first considering the MEVs that can be extracted by
any individual participant, and then taking the minimum. As
noted in [15], this definition has some drawbacks when extract-
ing value requires the adversary to make upfront payments. In
such cases, the MEV is under-estimated as zero, since the
minimum also covers the zero value that can be extracted by
a “poor” adversary. The notion ofuniversal MEVproposed
in [17] overcomes this problem by defining MEV as a game
where honest players try to minimize the damage, while
adversaries try to maximize their gain. A token redistribution
mechanism ensures that the adversaries have enough wealth
to execute their extraction strategy. The token redistribution isnot completely equivalent to our wealthiness assumption about
adversaries (§III-A), since the token to be distributed may not
be sufficient for the attack. A wealthiness assumption more
similar to ours was used in [31], which introduces the notion of
“MEV of wealthy adversaries” by taking the maximum MEV
over all possible adversarial wallets.
Analysis of the AMM contract:Compared to real-world
AMM implementations such as Uniswap [30], our Lean for-
malization introduces a few simplifications, that overall con-
tribute to keeping our proofs manageable. A first simplification
is that in Uniswap, when a user executes aswap, part of
the input tokens are paid to the protocol as a fee. Studying
the effect of swap fees on MEV would require a further
complication of the adversarial strategies, who would need
to minimize the impact of fees on their own swaps. The
Lean formalization in [32] studies AMMs with swap fees, but
unlike ours, it does not address MEV . The additional burden
introduced by swap fees is, however, already visible in [32]
in the analysis of arbitrage (i.e., the optimal swap in a zero-
player game). We expect swap fees to impact MEV analysis
to an even greater extent.
Besides swaps, concrete AMM implementations typically
allow users to deposit and withdraw tokens from the AMM.
In particular, deposit transactions can increase the profits
obtainable from subsequent swaps [29], and can thus be lever-
aged by an adversary to amplifly MEV . The work [23] intro-
duces an extended sandwich attack that combines deposit and
swap transactions from the mempool with adversary-crafted
transactions, showing that this may increase the extractable
value. Extending our proof to handle mempools containing
arbitrary combinations of deposit and swap transactions would,
however, cause a substantial explosion in the number of cases
in our proof of MEV optimality.
A different Lean formalization of constant-product AMMs
is presented in [33]. Compared to our work — which proposes
a general framework for analysing MEV of arbitrary smart
contracts — the work [33] is specifically targeted on AMMs,
and only deals with arbitrage.
Sandwich attacks on AMMs were originally analysed
in [22], and later in [23], [24], [34], [35], [25], among the
others. Compared to these works, ours provides the first
machine-checked proof of optimality of sandwich attacks.
MEV countermeasures:Given the relevance of MEV on
the blockchain ecosystem, several techniques to mitigate its
effects have been proposed in the past few years. Some of these
techniques are applicable to arbitrary smart contracts [36],
[37], [38], [39], [40], while some others are specific to certain
classes of contracts, such as AMMs [41], [42]. Formally
verifying within our Lean framework that some of these
techniques achieves the expected MEV reduction would be
a challenging extension of our work.
IX. CONCLUSIONS
We present a Lean framework for reasoning about MEV
in smart contracts. The framework is blockchain-agnostic and
can be instantiated to model different smart contract languages,
making it applicable to a wide range of real-world scenarios.
Unlike prior tools that are focussed on under- or over- ap-
proximations, our proof technique can establishexactMEV
bounds, by identifying attacks that are realistically executable
by an adversary and proving their optimality (no strictly
more profitable attacks exist). We validate the framework by
formalising representative DeFi protocols and mechanising
their analysis in Lean. In particular, we provide the first
machine-checked proof of the optimality of sandwich attacks
on Uniswap v2-based Automated Market Makers, demonstrat-
ing the effectiveness of our approach.
ACKNOWLEDGMENT
Work partially supported by project SERICS (PE00000014)
under the MUR National Recovery and Resilience Plan funded
by the European Union – NextGenerationEU, and by PRIN
2022 PNRR project DeLiCE (F53D23009130001).
REFERENCES
[1] B. Weintraub, C. F. Torres, C. Nita-Rotaru, and R. State, “A Flash(Bot)
in the pan: Measuring maximal extractable value in private pools,” in
ACM Internet Measurement Conference. ACM, 2022, p. 458–471.
[2] C. F. Torres, R. Camino, and R. State, “Frontrunner Jones and the
Raiders of the Dark Forest: An empirical study of frontrunning on the
Ethereum blockchain,” inUSENIX Security Symposium, 2021, pp. 1343–
1359.
[3] K. Qin, L. Zhou, and A. Gervais, “Quantifying blockchain extractable
value: How dark is the forest?” inIEEE Symp. on Security and Privacy.
IEEE, 2022, pp. 198–214.
[4] K. Qin, L. Zhou, B. Livshits, and A. Gervais, “Attacking the DeFi
ecosystem with Flash Loans for fun and profit,” inFinancial Cryptog-
raphy, ser. LNCS, vol. 12674. Springer, 2021, pp. 3–32.
[5] P. Daian, S. Goldfeder, T. Kell, Y . Li, X. Zhao, I. Bentov, L. Brei-
denbach, and A. Juels, “Flash boys 2.0: Frontrunning in decentralized
exchanges, miner extractable value, and consensus instability,” inIEEE
Symp. on Security and Privacy. IEEE, 2020, pp. 910–927.
[6] Z. Li, J. Li, Z. He, X. Luo, T. Wang, X. Ni, W. Yang, X. Chen, and
T. Chen, “Demystifying DeFi MEV Activities in Flashbots Bundle,” in
ACM SIGSAC Conference on Computer and Communications Security
(CCS). ACM, 2023, pp. 165–179.
[7] K. Babel, M. Javaheripi, Y . Ji, M. Kelkar, F. Koushanfar, and A. Juels,
“Lanturn: Measuring economic security of smart contracts through
adaptive learning,” inACM SIGSAC Conference on Computer and
Communications Security (CCS). ACM, 2023, pp. 1212–1226.
[8] E. Hildenbrandt, M. Saxena, N. Rodrigues, X. Zhu, P. Daian, D. Guth,
B. M. Moore, D. Park, Y . Zhang, A. Stefanescu, and G. Rosu, “KEVM:
A Complete Formal Semantics of the Ethereum Virtual Machine,”
inIEEE Computer Security Foundations Symposium (CSF). IEEE
Computer Society, 2018, pp. 204–217.
[9] I. Grishchenko, M. Maffei, and C. Schneidewind, “A Semantic Frame-
work for the Security Analysis of Ethereum Smart Contracts,” inPrin-
ciples of Security and Trust (POST), ser. LNCS, vol. 10804. Springer,
2018, pp. 243–269.
[10] F. Cassez, J. Fuller, M. K. Ghale, D. J. Pearce, and H. M. A. Quiles,
“Formal and Executable Semantics of the Ethereum Virtual Machine in
Dafny,” inFormal Methods (FM), ser. LNCS, vol. 14000. Springer,
2023, pp. 571–583.
[11] S. Crafa, M. D. Pirro, and E. Zucca, “Is Solidity Solid Enough?” in
Workshop on Trusted Smart Contracts (WTSC), ser. LNCS, vol. 11599.
Springer, 2019, pp. 138–153.
[12] J. Jiao, S. Kan, S. Lin, D. Sanán, Y . Liu, and J. Sun, “Semantic
Understanding of Smart Contracts: Executable Operational Semantics
of Solidity,” inIEEE Symposium on Security and Privacy (SP). IEEE,
2020, pp. 1695–1712.
[13] D. Marmsoler and A. D. Brucker, “Isabelle/Solidity: A deep embedding
of Solidity in Isabelle/HOL,”Formal Aspects Comput., vol. 37, no. 2,
pp. 15:1–15:56, 2025.[14] K. Babel, P. Daian, M. Kelkar, and A. Juels, “Clockwork finance:
Automated analysis of economic security in smart contracts,” inIEEE
Symposium on Security and Privacy. IEEE Computer Society, 2023,
pp. 622–639.
[15] A. Salles, “On the formalization of MEV,” 2021, https://writings.
flashbots.net/research/formalization-mev.
[16] B. Mazorra, M. Reynolds, and V . Daza, “Price of MEV: towards a game
theoretical approach to MEV,” inACM CCS Workshop on Decentralized
Finance and Security. ACM, 2022, pp. 15–22.
[17] M. Bartoletti and R. Zunino, “A theoretical basis for MEV,” inFinancial
Cryptography and Data Security, ser. LNCS. Springer, 2025.
[18] L. d. Moura and S. Ullrich, “The Lean 4 Theorem Prover and Program-
ming Language,” inAutomated Deduction (CADE). Springer-Verlag,
2021, p. 625–635.
[19] The mathlib Community, “The Lean Mathematical Library,” inCertified
Programs and Proofs (CPP). ACM, 2020, p. 367–381.
[20] G. Angeris and T. Chitra, “Improved price oracles: Constant Function
Market Makers,” inACM Conference on Advances in Financial Tech-
nologies (AFT). ACM, 2020, pp. 80–91.
[21] S. Werner, D. Perez, L. Gudgeon, A. Klages-Mundt, D. Harz, and W. J.
Knottenbelt, “SoK: Decentralized Finance (DeFi),” inACM Conference
on Advances in Financial Technologies, (AFT). ACM, 2022, pp. 30–46.
[22] L. Zhou, K. Qin, C. F. Torres, D. V . Le, and A. Gervais, “High-
Frequency Trading on Decentralized On-Chain Exchanges,” inIEEE
Symp. on Security and Privacy. IEEE, 2021, pp. 428–445.
[23] M. Bartoletti, J. H. Chiang, and A. Lluch-Lafuente, “Maximizing
extractable value from Automated Market Makers,” inFinancial Cryp-
tography, ser. LNCS, vol. 13411. Springer, 2022, pp. 3–19.
[24] J. Xu, K. Paruch, S. Cousaert, and Y . Feng, “SoK: Decentralized
Exchanges (DEX) with Automated Market Maker (AMM) Protocols,”
ACM Comput. Surv., vol. 55, no. 11, 2023. [Online]. Available:
https://doi.org/10.1145/3570639
[25] K. Kulkarni, T. Diamandis, and T. Chitra, “Routing MEV in Constant
Function Market Makers,” inWeb and Internet Economics (WINE), ser.
LNCS, vol. 14413. Springer, 2023, pp. 456–473.
[26] “MEV Lean formalization,” 2025. [Online]. Available: https://github.
com/r-marche/MEV-formal
[27] S. Eskandari, S. Moosavi, and J. Clark, “SoK: Transparent Dishonesty:
Front-Running Attacks on Blockchain,” inFinancial Cryptography.
Springer, 2020, pp. 170–189.
[28] G. Angeris, H.-T. Kao, R. Chiang, C. Noyes, and T. Chitra, “An analysis
of Uniswap markets,”Cryptoeconomic Systems, vol. 1, no. 1, 2021.
[29] M. Bartoletti, J. H. Chiang, and A. Lluch-Lafuente, “A theory of
Automated Market Makers in DeFi,”Logical Methods in Computer
Science, vol. 18, no. 4, 2022.
[30] “Uniswap token pair implementation,” 2021,
https://github.com/Uniswap/uniswap-v2-core/blob/
4dd59067c76dea4a0e8e4bfdda41877a6b16dedc/contracts/
UniswapV2Pair.sol.
[31] M. Bartoletti, R. Marchesin, and R. Zunino, “DeFi composability as
MEV non-interference,” inFinancial Cryptography, ser. LNCS, vol.
14744. Springer, 2024.
[32] M. Dessalvi, “Automated Market Makers in the Lean 4 Theorem Prover,”
Master’s thesis, DTU Compute, Technical University of Denmark, 2025.
[Online]. Available: https://fulltext-gateway.cvt.dk/oafilestore?oid=
6865ca59ee615523af43fd05&targetid=6865ca59c998ab10401d3143
[33] D. Pusceddu and M. Bartoletti, “Formalizing Automated Market Makers
in the Lean 4 Theorem Prover,” inFormal Methods for Blockchains
(FMBC), ser. OASIcs, vol. 118. Schloss Dagstuhl - Leibniz-Zentrum
für Informatik, 2024, pp. 5:1–5:13.
[34] J. Wang, J. Li, Z. Li, X. Deng, and B. Xiao, “n-MVTL Attack: Optimal
Transaction Reordering Attack on DeFi,” inEuropean Symposium on
Research in Computer Security (ESORICS), ser. LNCS, vol. 14346.
Springer, 2023, pp. 367–386.
[35] A. Park, “The conceptual flaws of decentralized automated market
making,”Management Science, vol. 69, no. 11, pp. 6731–6751, 2023.
[36] L. Breidenbach, P. Daian, F. Tramèr, and A. Juels, “Enter the Hydra:
Towards principled bug bounties and exploit-resistant smart contracts,”
inUSENIX Security Symposium. USENIX Association, 2019, pp. 1335–
1352.
[37] C. Baum, J. H. Chiang, B. David, T. K. Frederiksen, and L. Gentile,
“SoK: Mitigation of Front-Running in Decentralized Finance,” inFinan-
cial Cryptography Workshops, ser. LNCS, vol. 13412. Springer, 2022,
pp. 250–271.
[38] L. Heimbach and R. Wattenhofer, “Sok: Preventing transaction reorder-
ing manipulations in decentralized finance,” inAdvances in Financial
Technologies, 2022.
[39] A. Canidio and V . Danos, “Commitment against front-running attacks,”
Manag. Sci., vol. 70, no. 7, pp. 4429–4440, 2024.
[40] K. Babel, N. Jean-Louis, Y . Ji, U. Misra, M. Kelkar, K. Y . Mudiyanse-
lage, A. Miller, and A. Juels, “PROF: protected order flow in a profit-
seeking world,”CoRR, vol. abs/2408.02303, 2024.
[41] M. Ciampi, M. Ishaq, M. Magdon-Ismail, R. Ostrovsky, and V . Zikas,
“FairMM: A fast and frontrunning-resistant crypto market-maker,” in
Cyber Security, Cryptology, and Machine Learning (CSCML), ser.
LNCS, vol. 13301. Springer, 2022, pp. 428–446.
[42] C. Baum, B. David, and T. K. Frederiksen, “P2DEX: privacy-preserving
decentralized cryptocurrency exchange,” inApplied Cryptography and
Network Security (ACNS), ser. LNCS, vol. 12726. Springer, 2021, pp.
163–194.
APPENDIX
A. Non existence of MEV in the general case
In this appendix we consider the corner case in which MEV
fails to exist for an AMM contract.
Specifically, we consider an AMM contract, starting in a
stateσsuch that the mempool inσcontains a single transaction
txwithtx.vmin = 0andtx.inputValue =τ 0. In such a
scenario we can prove thatMEVσdoes not exist, and that
MEVSupσis equal toextractableσ+ tx.v * pr 0.
We prove the existence ofMEVSupσwith two propositions:
the first one establishes that the gain of the adversary is strictly
bounded from above, while the second one establishes that the
adversary can extract a value that is arbitrarily close to that
upper bound.
Proposition 1.The value that the adversary can gain
by performing a sequence of transactions inσis strictly
less thanextractableσ+ tx.v * pr 0. In short, we have
∀tr, gainMovesσtr < extractableσ+ tx.v * pr 0
Proof.Since the mempool contains a single transaction, we
can assume thattreither includes a single mempool move or
none at all. Indeed, although theoreticallytrcould include
more than one mempool move, at most one of them can
be executed succesfully, since the contract semantics would
remove the transaction from the mempool after executing it.
An unsuccessful move leaves the contract state unaltered, so
we can prune these failing moves fromtr.
The case in whichtrfeatures no mempool transactions
is simple: indeed this is akin to working in a contract
with an empty mempool. From our results on AMMs with
empty mempool (MEV_empty_mempool,AMM_MEV_guessand
exact_gain_simple) we know that such a contract would have
MEV equal toextractableσ, and since bothtx.vandpr 0
are positive, we have:
gainMovesσtr≤extractableσ
< extractableσ+ tx.v * pr 0
which proves our proposition.
Instead, iftrcontains the mempool move that executestx,
we can write it as follows:
tr = tr’ :: mempool id :: tr’’wheretr’andtr’’are lists of adversarial moves, andid
is the transaction id associated totx. Thus we would have
gainMovesσtr=gainMovesσtr’
+gainMoveσ′(mempool id)
+gainMovesσ′′tr”(1)
whereσ′andσ′′are such thattr’− − →σ′andσ′tx− →σ′′.
Now, letb 0(respectivelyb′
0) be equal to the balance of
σ(respectivelyσ′) inτ 0andb 1, b′
1be the balance of those
contract states inτ 1. From this point onward we will also
denotetx.vasv. Finallypr0andpr1are the prices of tokens.
The adversarial gain can be calculated from the contract
balances as follows:
gainMovesσtr’=pr0(b0−b′
0) +pr1(b1−b′
1)
Sinceσ′tx− →σ′′we can calculate the balance ofσ′′. Inτ 0this
balance is equal tob′
0+v, and inτ 1it isb′
0b′
1
b′
0+v.
To give a bound ongainMovesσ’’ tr’’we notice that
tr”only contains adversarial moves. Therefore we can use
the results on the MEV of AMMs with an empty mempool to
conclude that
gainMovesσ′′tr”≤extractableσ′′=
=pr0(b′
0+v) +pr1b′
0b′
1
b′
0+v−2p
b′
0b′
1pr0pr1
Finally remembering thattxitself gains no token for the
adversary, and thatb 0b1=b′
0b′
1, we can use Equation (1) to
obtain thatgainMovesσtrmust be smaller than
pr0(b0+v) +pr1b′
0b′
1
b′
0+v+pr1(b1−b′
1)−2p
b0b1pr0pr1
which in turn can be rewritten as
extractableσ+pr0v+pr1b′
0b′
1
b′
0+v−pr1b′
1
Sinceb′
0
b′
0+v<1we have shown that every trace extracts a
value that is belowextractableσ+pr0v.
Proposition 2.There exists a sequence movestrthat the
adversary can perform inσorder to gain an amount of value
that is arbitrarily close toextractableσ+ tx.v * pr 0. In
short, we have:
∀(ε:R+),∃tr,
gainMovesσtr +ε≥extractableσ+ tx.v * pr 0
Proof.To prove this proposition we will calculate the gain of
a trace parametrized by the positive real valuex∈R+.
First, we name some contract states and transactions.
•σis the state in which the AMM is balanced, i.e. the state
in which
b0·pr0=b1·pr1
where b0(respectively b1) is the balance of σinτ 0
(respectivelyτ 1).
•mσis the transaction that balances the AMM when
applied inσ, i.e. the transaction such that
σmσ− − →σ
•adv(x)is an adversarial transaction that sendsxtokens
of typeτ 0to the contract.
•σ′andσ′′are states such that
σadv(x)− − − − →σ′tx− →σ′′
It easily follows from the definition ofadv(tx)that the
balance ofσ′inτ 0isb0+x, and that its balance inτ 1is
b0b1
b0+x. Similarly, from the definition oftx, we have that
the balance ofσ′′isb0+x+tx.vinτ 0andb0b1
b0+x+tx.vinτ 1.
•mσis the transaction that balances the AMM when
applied inσ′′
We definetr(x)as the following list of moves:
tr(x) :=m σ::adv(x) ::tx::m σ′′
We will now calculate the amount of tokens that the
adversary gains from appendingtr(x)to the blockchain.
•mσyields
pr0(b0−b0) +pr1(b1−b1)
•adv(x)yieldspr1
b1−b0b1
b0+x
−pr0x(a negative quan-
tity).
•txis a mempool transaction, so it doesn’t yield any gain
for the adversary.
•Finally,m σ′′yieldsextractableσ′′for the adversary
which is equal to
pr0(b0+x+v) +pr1b0b1
b0+x+v−2q
b0b1pr0pr1
The gain oftr(x), which is the sum of all the above gains,
amounts to:
pr0(b0−b0) +pr1(b1−b1)
+pr1(b1−b0b1
b0+x)−pr0x
+pr0(b0+x+v) +pr1b0b1
b0+x+v−2q
b0b1pr0pr1
Since we are working with a constant product AMM, we
have thatb 0b1=b0b1, meaning that expression above can
be simplified as
pr0b0+pr1b1−2p
b0b1pr0pr1+pr0v
+pr1b0b11
b0+x+v−1
b0+x
which is equal to
extractableσ+pr0v−pr1b0b1v1
(b0+x+v)( b0+x)
which gets arbitrarily close toextractableσ+pr0vfor
large values ofx. Therefore, for allϵone can find a value of
xsuch thatgainMovesσtr(x) +ε≥extractableσ+ tx.v * pr 0
proving our proposition.