A theory of Automated Market Makers in DeFi

Automated market makers (AMMs) are one of the most prominent decentralized finance (DeFi) applications. AMMs allow users to trade different types of crypto-tokens, without the need to find a counter-party. There are several implementations and models for AMMs, featuring a variety of sophisticated economic mechanisms. We present a theory of AMMs. The core of our theory is an abstract operational model of the interactions between users and AMMs, which can be concretised by instantiating the economic mechanisms. We exploit our theory to formally prove a set of fundamental properties of AMMs, characterizing both structural and economic aspects. We do this by abstracting from the actual economic mechanisms used in implementations, and identifying sufficient conditions which ensure the relevant properties. Notably, we devise a general solution to the arbitrage problem, the main game-theoretic foundation behind the economic mechanisms of AMMs.


Introduction
Decentralized finance (DeFi) is a software infrastructure, based on blockchains and smart contracts, which allows users to create and trade crypto-tokens without the intermediation of central authorities, unlike traditional finance [WPG + 21, QZA + 21].Automated Market Makers (AMMs) are one of the main DeFi archetypes: roughly, AMMs are decentralized markets of crypto-tokens, providing users with three core operations: depositing cryptotokens to obtain shares in an AMM; the dual operation of redeeming shares in the AMM for the underlying tokens; and swapping tokens of a given type for tokens of another type.The amount of tokens received by a user upon a swap is algorithmically determined by the AMM: roughly, this is the amount of tokens sent from the user to the AMM, times the swap rate, which is computed by the AMM based on its internal state and the input amount.
Despite the apparent simplicity of these operations, AMMs manifest an emerging behaviour, where users are incentivized to swap tokens to keep their swap rates aligned with the exchange rate, i.e. the ratio between the prices of the exchanged tokens given by external price oracles.Namely, if an AMM offers a better swap rate than the oracles' exchange rate, rational users will perform swaps to narrow the gap.Formally, the optimal strategy can be seen as the solution of a game, called the arbitrage game.Executing the optimal strategy closes the gap between AMM's and oracles' exchange rates, and in this sense AMMs offer users exhange rates that align towards the external, global exchange rates.and redeem transactions: in particular, we establish that two deposit actions on the same AMM can be merged in a single action (and similarly for two redeems), and that the effect of deposits and redeem actions can be reverted by suitable transactions.Remarkably, all the structural properties in section 4 do not depend on the choice of the swap rate function.(4) In section 5 we devise sufficient conditions on swap rate functions that induce good behavioural properties of AMMs.These conditions allow us to extend to swap actions the additivity and reversibility properties enjoyed by deposit and redeem actions (Theorems 5.6 and 5.9), as well as to compute the gain of composed and reversed swaps (Lemmata 5.7 and 5.10).We study the effect of deposits and redeems on the swap rate and on the internal exchange rate (Lemma 5.13).We then study the properties of three notable swap rate functions: the constant sum, the constant product, and the constant mean.(5) In section 6 we investigate the incentive mechanism of AMMs.We start by considering the arbitrage problem, which requires to find the action which maximizes the gain of a user.Performing such optimal action has the side effect of aligning the internal exchange rate of the AMM to the external exchange rate given by token price oracles.This gives one of the landmark economic properties of AMMs: assuming rational users, AMMs can be seen as price oracles themselves [AC20].Notably, while solutions to the arbitrage problem are already known for specific swap rate functions, in Theorem 6.3 we generalize the result to any swap rate function respecting the conditions given in section 5. We then show that depositing tokens into AMMs incentivizes subsequent swaps (Theorem 6.6), while redeeming tokens disincentivizes them (Theorem 6.9).Finally, in Theorems 6.8 and 6.10 we relate the solution of the arbitrage problem in the states before and after a deposit or redeem action, and we compare their gains.(6) In section 7 we discuss Maximal Extractable Value (MEV), a class of attacks where miners exploit their power of dropping and reordering user transactions (and inserting their own) to increase their gain to the detriment of users.These attacks are one of the most carefully studied AMM phenomena, occuring widely in practice and frequently making up the bulk of interactions with AMMs [QZG21].The fact that our AMM model can accurately express these attacks supports the coherence of our modelling choices with respect to behaviour exhibited by actual AMM implementations.(7) In section 8 we discuss some extensions to our basic AMM model to make it closer to the implementation of Uniswap [uni21], and their impact on the results in the paper.(8) As a byproduct, we provide an open-source Ocaml implementation of our executable semantics as a companion of this paper.1 (9) We provide full proofs of all our statements in the Appendices.1.2.Related Work.The work [AKC + 21] proposed one of the first analyses of the incentive mechanism of Uniswap.This analysis was then generalised in [AC20] to constant function AMMs (CFMMs), where, for a pair of token types, the reserves r 0 , r 1 before a swap and the reserves r 0 , r 1 after the swap must preserve the invariant f (r 0 , r 1 ) = f (r 0 , r 1 ), for a given trading function f .Constant product AMMs, like Uniswap, are an instance of CFMMs, where f (x, y) = xy.Both works study the arbitrage problem, for constant product AMMs and CFMMs, respectively.The two works show that the solution can be efficiently computed, and suggest that constant product AMMs accurately report exchange rates.Our work and [AC20] share a common goal, i.e. a theory of AMMs generalizing that of constant product AMMs.However, the two approaches are quite different.The work [AC20] considers a class of AMMs, i.e.CFMMs with a convex trading set, and studies the properties enjoyed by AMMs under these assumptions.Instead, in this paper we devise a minimal set of properties of the swap rate function which induce good behavioural properties of AMMs.Notably, we find conditions on the swap rate function which ensure that a given swap action maximizes the gain of the player (Theorem 6.3).Another difference is that the AMM model in [AC20] describes the evolution of a single AMM, abstracting away the other components of the state (i.e. the users and the other AMMs); instead, we model AMMs as reactive systems, borrowing techniques from concurrency theory.While the approach followed by [AC20] is still adequate to study problems that concern AMMs in isolation (e.g., arbitrage), viewing AMMs as reactive systems allows us to study what happens when many agents (users and AMMs) can interact.E.g., we are able to reason about Maximal Extractable Value (section 7).
The work [DKP21] generalises the arbitrage problem to the setting where a swap between two token types τ 0 and τ n can be obtained through a sequence of n intermediate swaps between τ i and τ i+1 , for 0 ≤ i < n.In practice, this represents the situation where users can interact with different AMM platforms, each one providing its own set of token pairs.To model this scenario, [DKP21] introduces exchange networks, i.e. multi-graphs where nodes are tokens, and edges are AMMs which allow users to swap the two endpoint tokens.To encompass different AMM platforms, each edge has its own price function, which determines how many output tokens are paid for a given amount of input tokens.The authors show that, under some conditions on the price functions (i.e., monotonicity, continuity, boundedness and concavity), the arbitrage problem always admits a non-trivial solution.In the special case of constant product AMMs, a closed formula for the solution is provided.Besides arbitrage, [DKP21] also considers the optimal routing problem, i.e. finding a strategy to maximize the amount of tokens τ 1 received for at most a given amount of tokens τ 0 .Under the same assumptions on the price function used for the arbitrage problem, the optimal routing problem admits a solution.There are several differences between our approach and that of [DKP21], besides the fact that we assume the same swap rate function for all AMMs, and a graph instead of a multi-graph (i.e., we admit at most one AMM for each token pair).A technical difference is that we assume that the amount y of output tokens received for an amount x of input tokens is given by y = SX (x, r 0 , r 1 ) • x, whereas [DKP21] defines this amount as y = f r 0 ,r 1 (x).This results in different structural properties for SX (x, r 0 , r 1 ) and f (x) in order to achieve the desired behavioural properties of AMMs.Having the AMM reserves r 0 , r 1 as parameters of our swap rate functions SX has a benefit, in that we can express conditions which relate states before and after a transaction: this is what happens, e.g., in the additivity, reversibility and homogeneity properties (Definitions 5.5,5.8 and 5.11).As a consequence of this choice, compared to [DKP21] our theory encompasses also deposit and redeem actions, providing results that clarify how these actions interfere with swaps (e.g., Theorems 6.6, 6.9, 6.8, and 6.10).
A few alternatives to constant product AMMs have been studied.Balancer [bal19] generalizes the constant product function used by Uniswap to a constant (weighted geometric) where the weight w i reflects the relevance of a token τ i in a tuple of tokens (τ 1 , • • • , τ n ).This still fits within the CFMM setting of [AC20], thus inheriting its results about solvability of the arbitrage problem [EAC21].Curve [Ego19] features a hybrid 12:5 of a constant sum and constant product function, optimized for large swap volumes between stable coins, where the swap rate can support large amounts with small sensitivity.To efficiently compute swap rates, implementations perform numerical approximations [cur21a].Should these approximations fail to converge, these implementations still guarantee that the AMM remains liquid.The work [KFG21] proposes a constant product invariant that is adjusted dynamically based on the oracle price feed, thus reducing the need for arbitrage transactions, but at the cost of lower fee accrual.AMMs with virtual balances have been proposed [vir18] and implemented [moo20b,moo20a].In these AMMs, the swap rate depends on past actions, besides the current funds balances in the AMM.This, similarly to [KFG21], aims to minimize the need for arbitrage transactions to ensure the local AMM swap rate tends towards the exchange rates.Establishing whether these sophisticated swap rate functions enjoy the properties in section 5 is an interesting open problem.
AMMs are well-known to suffer from transaction-ordering attacks, through which an adversary with the power of influencing the order of transactions (e.g., a miner) can extract value from user transactions.For instance, if the transaction pool contains a swap transaction sent by user A, then a miner M can extract value from A's swap through a transaction "sandwich" constructed as follows.First, M front-runs A's swap with its own swap, crafted so that A's swap decreases A's net worth as much as possible.Then, M closes the sandwich by appending another swap transaction which maximizes M's gain, and finalises the whole sandwich on the blockchain.In this way, A will always have a negative gain, which is counterbalanced by a positive gain of M. This and other kinds of attacks have fostered the research on adversarial and defensive strategies, and on empirical analyses of the impact of attacks [BCL22,CAE22,ZQT + 21,QZG21,DGK + 20,EMC20].For instance, the work [BCL22] devises an optimal strategy through which an adversary can extract the maximal value from users' transactions (not only swaps, but also deposits and redeems), in the setting of Uniswap-like AMMs.The swap-rate-agnostic approach pursued by this paper could be exploited to generalise the attack of [BCL22] to AMMs beyond Uniswap.
A high-level survey on various AMM protocols is in [XVPC22].
Comparison with previous work.A preliminary version of this work was presented at COORDINATION 2021 [BCL21b].The current version substantially extends it, streamlining the theory and providing additional results.A crucial difference between the two papers is that, while in [BCL21b] the semantics of swap actions was parameterized by an invariant between the old and the new token reserves, here we make the semantics parametric w.r.t. the swap rate function SX .This leads to a substantial simplification of the conditions that are put to obtain nice behavioural properties of swaps, and consequently of the corresponding proofs.Among the new results w.r.t.[BCL21b], we mention in particular the additivity and reversibility properties (Theorems 4.10,4.11,5.6,and 5.9), and the results that relate the gain of swaps before and after deposit/redeem actions (Theorems 6.6, 6.9, 6.8, and 6.10).Besides these extensions, the current paper includes a discussion of the constant sum and of the constant mean swap rate functions, a new section on MEV attacks (see section 7), and it provides detailed proofs for all its statements.

A formal model of Automated Market Makers
We introduce a formal, operational model of AMMs, which focusses on the common operations implemented by AMM platforms.In order to simplify the resulting theory, our model abstracts from a few features that are often found in AMM implementations, like e.g.fees, price updates, and guarded transactions.We discuss in §8 how to extend our model to make it closer to the Uniswap protocol [uni21].
We introduce here some general notation.We denote by f x the application of a function f to a value x (we use parentheses, e.g.f (x), to resolve ambiguities).We denote with dom f the domain of f .We use the standard notation f { v /x} to update a partial map f at point x: 2.1.AMM basics.
Tokens.We assume a set T 0 of atomic token types, which represent native cryptocurrencies and application-specific tokens.For instance, T 0 may include ETH, the native cryptocurrency of Ethereum, and WBTC, i.e.Bitcoins wrapped with the ERC20 interface for Ethereum tokens.A minted token type is an unordered pair of distinct atomic token types: if τ 0 and τ 1 are atomic token types and τ 0 = τ 1 , then the minted token type {τ 0 , τ 1 } represents shares in an AMM holding reserves of τ 0 and τ 1 .We denote by T 1 the set of minted token types.In our model, tokens are fungible, i.e. individual units of the same type are interchangeable.This means that amounts of tokens of the same type can be split into smaller parts, and two amounts of tokens of the same type can be joined.We use v, v , r, r , x, x to range over nonnegative real numbers (R ≥0 ).We write T for the universe of all token types, i.e.T = T 0 ∪ T 1 , and we use τ, τ , . . . to range over T. We write r : τ to denote r units of a token of type τ, either atomic or minted.
Wallets and AMMs.We assume a set of users A, ranged over by A, A , . . .We model the wallet of a user A as a term A[σ], where the finite partial map σ ∈ T R ≥0 represents A's token balance.We model an AMM holding reserves of r 0 : τ 0 and r 1 : τ 1 (with τ 0 = τ 1 ) as an unordered pair {r 0 : τ 0 , r 1 : τ 1 }.Since the order of the token reserves in an AMM is immaterial, the terms {r 0 : τ 0 , r 1 : τ 1 } and {r 1 : τ 1 , r 0 : τ 0 } denote exactly the same AMM.
States.We model the interaction between users and AMMs as a labelled transition system (LTS).Its labels represent blockchain transactions, while the states Γ, Γ , ∆, . . .are finite non-empty compositions of wallets and AMMs.Formally, states are terms of the form: and subject to the following conditions.For all i = j: (1) A i = A j (each user has a single wallet); (2) {τ i , τ i } = {τ j , τ j } (distinct AMMs cannot hold exactly the same token types).
Note that these conditions allow AMMs to have a common token type τ, e.g. as in {r 1 : τ 1 , r : τ}, {r : τ, r 2 : τ 2 }, thus enabling indirect trades between token pairs not directly provided by any AMM.A state is initial when it has no AMMs, and its wallets hold only atomic tokens.We stipulate that the ordering of terms in a state is immaterial.Hence, we 12:7 consider two states Γ and Γ to be equivalent when they contain the same terms (regardless of their order).For a term Q and a state Γ, we write Q ∈ Γ when Γ = Q | Γ , for some Γ .
2.2.AMM semantics.We now formalise the transition rules between states.We write Γ T − → Γ for a state transition from Γ to Γ , triggered by a transaction T. When Γ T − → Γ for some Γ , we say that T is enabled in Γ.We denote with − → * the reflexive and transitive closure of − →.Given a finite sequence of transactions and in this case we say that λ is enabled in Γ.We say that a state Γ is reachable if Γ 0 − → * Γ for some initial Γ 0 .Hereafter, all the states mentioned in our results are implicitly assumed to be reachable.Given a partial map σ ∈ T R ≥0 , a token type τ ∈ T and a partial operation R ≥0 with • ∈ {+, −}, we define the partial map σ • v : τ as follows: These partial operations allow to increase/decrease the amount of tokens in a balance.For instance, if σ = 5 : τ 0 , then σ + 1 : τ 0 = 6 : τ 0 , and σ + 1 : τ 1 = 5 : τ 0 , 1 : τ 1 .
Deposit.Any user can create an AMM for two tokens τ 0 and τ 1 , if such an AMM is not already present in the state.This is achieved by the transaction A : dep(v 0 : τ 0 , v 1 :τ 1 ), through which A transfers v 0 : τ 0 and v 1 : τ 1 to the new AMM.In return for the deposit, A receives a certain positive amount of units of a new token type {τ 0 , τ 1 }, which is minted by the AMM. 2 We formalise this behaviour by the rule: Note that the premise S Γ {τ 0 , τ 1 } = 0 implies that τ 0 , τ 1 are distinct atomic tokens, since otherwise {τ 0 , τ 1 } would not be a minted token.If Γ is reachable, then this premise also implies that Γ does not contain an AMM for the token pair τ 0 , τ 1 .
Once an AMM is created, any user can deposit tokens into it -as long as doing so preserves the ratio of the token reserves in the AMM.When a user deposits v 0 : τ 0 and v 1 : τ 1 to an existing AMM, it receives in return an amount of minted tokens of type {τ 0 , τ 1 }.This amount is the ratio between the deposited amount v 0 and the redeem rate of {τ 0 , τ 1 } in the current state Γ, which is defined as follows for i ∈ {0, 1}: The effect of a deposit transaction on the state is then formalised by the following rule: We anticipate that the premises of the [Dep] rule ensure that deposits preserve some key quantities across state transitions, namely: • the ratio between the reserves of τ 0 and τ 1 in the AMM (see Lemma 4.4(a)).This ratio is always defined, since the reserves of a token in an AMM cannot be zeroed (see Lemma 4.2); • the net worth of the user performing the action (see Lemma 4.5).In particular, the value of the minted tokens {τ 0 , τ 1 } received by the user upon a deposit is equal to the value of the tokens τ 0 , τ 1 transferred to the AMM; • the internal exchange rate of the AMM (see Lemma 5.12).This preservation property holds for a relevant class of swap rate functions, called homogeneous (see Definition 5.11).
Redeem.Any user can redeem units of a minted token {τ 0 , τ 1 }, obtaining in return units of the underlying atomic tokens τ 0 and τ 1 .Their actual amounts are determined by the redeem rate: the idea is that each unit of the minted token {τ 0 , τ 1 } can be redeemed for equal fractions of τ 0 and τ 1 remaining in the AMM: Vol. 18:4 A THEORY OF AUTOMATED MARKET MAKERS IN DEFI 12:9 Note that the premise v < S Γ {τ 0 , τ 1 } ensures that the reserves are not depleted, i.e. v i < r i .Similarly to the [Dep] rule, the premises of [Rdm] ensure that: • the net worth of the user performing the action is preserved (i.e., the net worth of burnt minted tokens is equal to that of the tokens received by A); • the internal exchange rate of the AMM is unaffected by the transition, if the swap rate function is homogeneous.
Swap.Any user A can swap v units of τ 0 in her wallet for some units of τ 1 in an AMM {r 0 : τ 0 , r 1 : τ 1 } through the transaction A : swap(v, τ 0 , τ 1 ).Symmetrically, A can swap v of her units of τ 1 for units of τ 0 in the AMM through a transaction A : swap(v, τ 1 , τ 0 ).The swap rate SX (x, r 0 , r 1 ) determines the amount of output tokens τ 1 that a user receives upon an amount of x input tokens τ 0 in an AMM {r 0 : τ 0 , r 1 : τ 1 }.
The swap rate function is a parameter of our model: we will discuss in §5 some desiderata for this function, and the behavioural properties they induce on the AMM semantics.As an instance, we consider below the constant product swap rate [rva18], which is used in mainstream AMM implementations, like e.g. in Uniswap v2 [uni21], Mooniswap [moo20a] and SushiSwap [sus21].We will use this swap rate function in all the examples in this paper.
Definition 2.1 (Constant product swap rate).The constant product swap rate function is: The constant product swap rate ensures that, if an AMM {r 0 : τ 0 , r 1 : τ 1 } evolves into {r 0 + x : τ 0 , r 1 − y : τ 1 } upon a swap, then the product between the reserves is preserved: Overall, the behaviour of the transition rules discussed above highlights some landmark properties of AMMs, namely: • since neither deposits nor redeems affect the net worth of the users performing them, the only way for users to increase their net worth is to perform swaps.Since, as we will see in Lemma 4.5, the global net worth is constant, this means that increasing ones' net worth results in a decrease of someone else's net worth; • the internal exchange rate of an AMM is affected only by swap actions (provided that the swap rate function is homogeneous).This is a natural behaviour, because swaps reflect the value of tokens perceived by users.We will show later in §5 that the constant sum/product/mean swap rate functions are homogeneous.
Note that the swap rate, i.e. 40 /40+30 ≈ 0.57, has decreased w.r.t. the first swap, i.e. 70 /70+30 = 0.7, even though the AMM has the same 1-to-1 reserves ratio.This is caused by the reduction in reserves occurred after A's redeem action: thus, the swap rate is sensitive not only to the ratio of reserves in the AMM, but also on their actual values.(6) A : rdm(30 : {τ 0 , τ 1 }).A redeems 30 units of the minted token {τ 0 , τ 1 }, thereby extracting 52 units of τ 0 and 17 units of τ 1 from the AMM.Note that the ratio of redeemed tokens is no longer 1-to-1 as in the previous redeem action, as the prior swap has changed the ratio between the funds of τ 0 and τ 1 in the AMM.Finally, observe that the supply of both τ 0 and τ 1 remains constant.We will show in Lemma 4.3 that the supply of atomic token types is always preserved.

Prices, exchange rates and net worth
In this section we introduce some economic notions which are pivotal for understanding the economic mechanisms of AMMs.
Token prices and exchange rates.We assume an external oracle that prices atomic tokens.Formally, we model this oracle as a function P : T 0 → R >0 , assuming that the prices given by the oracle are constant along executions (see subsection 8.2 for a discussion about dynamic price updates).While the prices of atomic tokens are constant, that of minted 12:11 tokens may vary at run-time as a function of the state.More precisely, the price P Γ {τ 0 , τ 1 } of a minted token {τ 0 , τ 1 } depends both on the supply of the minted token in the users' wallets and on the reserves of τ 0 and τ 1 in the AMM: For uniformity, we define P Γ τ = P τ when τ ∈ T 0 .Lemma 4.2 will ensure that r 0 , r 1 > 0 and S Γ {τ 0 , τ 1 } > 0 in every reachable state Γ containing an AMM for the token pair τ 0 , τ 1 .Therefore, the price of the token {τ 0 , τ 1 } is always defined and positive in reachable states.
The idea underlying Equation (3.1) is that the price of one unit of minted token must be equal to the value of the atomic tokens that can be obtained by redeeming the minted token.Indeed, by rule [Rdm] and Equation (2.1) we have that: which substantiates our desideratum.This intuition will be formalized later in Lemma 4.6.
The exchange rate X(τ 0 , τ 1 ) between atomic token types τ 0 and τ 1 is the number of units of τ 1 that one can buy with 1 unit of τ 0 at the price given by the external oracle: Hence, assuming an exchange at the prices of the external oracle, a user paying x units of τ 0 would receive x • X(τ 0 , τ 1 ) units of τ 1 .
Note that the exchange rate between two token types only depends on external oracles, neglecting the state of AMMs.However, AMMs themselves can act as (decentralised) price oracles [AC20], since they induce an exchange rate based on the effect of swaps in the current state.More precisely, the internal exchange rate X Γ (τ 0 , τ 1 ) between two atomic token types τ 0 and τ 1 in a state Γ is the limit of the swap rate function as x approaches 0:3 The intuition is similar to that in Equation (3.2): a user swapping x units of τ 0 for τ 1 through the AMM (for x very small ) would expect to receive x • X Γ (τ 0 , τ 1 ) units of τ 1 .We will see later in section 6 that rational users will perform actions that align the internal exchange rate to the one given by external oracles.
Slippage measures the discrepancy between the internal exchange rate and the actual ratio between the amounts of output and input tokens obtained upon the swap [XVPC22]: Ideally, slippage should disadvantage large trades, i.e. trying to obtain a larger amount of tokens with a swap should make them more expensive, increasing the slippage.We will compute in sections 5.6-5.8 the internal exchange rate and the slippage of some common AMMs.
be the final state of the computation in Figure 1.We have that S Γ {τ 0 , τ 1 } = 10, since only A's wallet contains units of the minted token.Assume that the prices of atomic tokens are P τ 0 = 5 and P τ 1 = 9.The price of the minted token {τ 0 , τ 1 } is then: The exchange rate between the two tokens is: which means that to buy 1 unit of τ 0 , one needs 0.55 units of τ 1 .Note instead that the internal exchange rate is: We will see in Example 6.5 that the discrepancy between internal and oracle exchange rate can by exploited by users to increase their gain.The slippage of a swap(x, τ 0 , τ 1 ) is: from which we can see that the slippage grows with the input amount x.
Net worth and gain.The net worth of a user A is a measure of A's wealth in tokens (both atomic and minted).Formally, we define the net worth of A in a state Γ as: Note that W A (Γ) ∈ R ≥0 , since balances σ are finite maps, and P Γ τ is always defined.The global net worth W (Γ) in a state Γ is the sum of the net worth in users' wallets.Note that the token reserves in AMMs are not accounted for by W (Γ), because their value is already recorded by minted tokens held in users' wallets.Indeed, the equality: between the net worth of a minted token and the value of the AMM is a direct consequence of the definition of price in Equation (3.1).
We denote by G A (Γ, λ) the gain of user A upon performing a sequence of transactions λ enabled in state Γ (if λ is not enabled in Γ, we stipulate that the gain is zero): To maximize their gain, users can perform different interactions with the AMM, e.g., by investing tokens or trading units of differently priced token types.
The following lemma quantifies the gain of users upon firing a swap transaction.Note that this quantification does not depend on any of the properties of the swap rate function introduced later on in section 5: actually, it holds for any swap rate function.
Lemma 3.2 (Swap gain).Let Γ = {r 0 : τ 0 , r 1 : τ 1 } | ∆, and let T = A : swap(x, τ 0 , τ 1 ) be enabled in Γ. Then: A direct consequence of Lemma 3.2 is that if A performs a swap between τ 0 and τ 1 and she holds all the units of the minted token {τ 0 , τ 1 }, then her gain will be zero.Further, A maximizes her gain when she has no minted tokens of type {τ 0 , τ 1 }.The lemma also implies that if the user performing the swap has a positive gain, then all the users who hold units of {τ 0 , τ 1 } will have a negative gain.
The following lemma states that a swap transaction on an AMM {r 0 : τ 0 , r 1 : τ 1 } has a strictly positive gain if and only if the swap rate is strictly greater than the oracle exchange rate between τ 0 and τ 1 .This holds for any swap rate function, under the condition that the user who performs the swap has no minted tokens of type {τ 0 , τ 1 }.Lemma 3.3 (Swap rate vs. exchange rate).Let Γ = A[σ] | {r 0 : τ 0 , r 1 : τ 1 } | ∆ be such that σ{τ 0 , τ 1 } = 0, and let T = A : swap(x, τ 0 , τ 1 ) be enabled in Γ. Then: Note that A's net worth of has decreased w.r.t. the initial state, while that of B has increased: indeed, the gain of A upon the sequence of transactions λ is G A (Γ, λ) = 977 − 980 = −3, while that of B is G B (Γ, λ) = 243 − 240 = 3.One may think that B has been more successful than A, but this depends on the users' goals.Note, e.g., that A holds 10 units of the minted token {τ 0 , τ 1 }, whose price may increase in the future.

Structural properties of AMMs
We now establish some structural properties of AMMs, which do not depend on the design of the economic mechanisms, i.e. on the choice of the swap rate function.These structural properties are the basis for AMM interactions that occur in the wild, and that cumulatively give rise to complex emerging behaviours like arbitrage and MEV.Hence, establishing these structural properties is a preliminary sanity check for our AMM model.We will provide further support for the coherence between our model and actual AMMs by showing that the above-mentioned complex behaviours are expressible in our model (see section 6 and section 7).
First, we establish that the AMMs' transition system is deterministic.This follows from the fact that, given a state Γ and a transaction T, there is at most one applicable rule.Note that determinism is a crucial property for blockchains, since it ensures that all the nodes in the blockchain network are able to reconstruct a common state from a sequence of transactions.Therefore, it makes sense that determinism holds also for our AMM model.
We can lift the statement to sequences of transactions by using a simple inductive argument.The same applies to other single-step results in this section.
Lemma 4.2 ensures that the reserves in an AMM cannot be zeroed, and that the same holds for the units of any minted token.Summing up, this ensures that the price of any minted token is always defined and positive.
Lemma 4.2 (Non depletion).For all states Γ, if {r 0 : τ 0 , r 1 : τ 1 } ∈ Γ then: 4.1.Preservation properties.Lemma 4.3 ensures that transactions preserve the supply of atomic tokens.Minted tokens, instead, are preserved only by swap transactions, since deposit and redeem transactions, respectively, create and destroy minted tokens.This fact will be instrumental to prove the preservation of the net worth (see Lemma 4.5).

Lemma 4.3 (Preservation of token supply
Lemma 4.4 states that deposit and redeem transactions preserve the reserves ratio in AMMs, the redeem rate, and the price of minted tokens.These preservation properties will be exploited later on to determine the solution to the arbitrage game after deposits and redeems (see Theorems 6.8 and 6.10).
Lemma 4.4 (Preservation upon deposits/redeems).Let Γ T − → Γ , with {r 0 : τ 0 , r 1 : Lemma 4.5 ensures that transactions (of any type) preserve the global net worth, whereas the net worth of individual users is preserved only by redeem and deposit transactions.A direct consequence of this preservation result is that users can increase their net worth only by performing swaps: Indeed, we will find in Theorem 6.3 that the solution of the arbitrage game only contains swap transactions.Furthermore, if a user has a positive gain, then some other user must have a loss.
The following lemma, which is a direct consequence of Lemma 4.5(a), supports the definition of the price of minted tokens in Equation (3.1): indeed, computing the net worth of a user A under that price definition corresponds to making A first redeem all her minted tokens, and then summing the price of the resulting atomic tokens.4.2.Liquidity.Lemma 4.8 ensures that funds cannot be frozen in an AMM, i.e. that users can always redeem arbitrary amounts of the tokens deposited in an AMM, as long as the reserves are not zeroed.Note that, since {r 0 : τ 0 , r 1 : τ 1 } = {r 1 : τ 1 , r 0 : τ 0 }, the statement also holds when swapping r 0 with r 1 .

Reordering of transactions.
In general, given two transactions T 0 and T 1 and a state Γ, executing T 0 T 1 or T 1 T 0 from Γ yields different states.However, under some conditions it is possible to invert the order of the two transactions, preserving the resulting state.This is always the case, e.g., of two transactions which operate on disjoint sets of tokens.Lemma 4.9 establishes sufficient conditions for preserving the state upon reordering.
Besides the case cited before, this is always possible if both transactions are deposits, or if they are bot redeems (case (a) of the statement).Note that, in these cases, the assumption that T 0 T 1 is enabled in Γ implies that also T 1 T 0 is such.This is no longer true when one of the two transactions is a deposit and the other one is a redeem.For instance, if T 1 redeems the minted tokens obtained upon a deposit T 0 , then T 1 may not be enabled in Γ because 12:16 there are not enough minted tokens in the user's wallet.Therefore, case (b) of the statement uses the additional hypothesis that also T 1 T 0 is enabled in Γ.
Lemma 4.9 (Reordering of transactions).Let Γ As we shall see in section 6, it is actually desirable, and crucial for the economic mechanism of AMMs, that swaps interfere with other transactions that trade the same token type.
4.4.Additivity of deposit and redeem actions.Deposit and redeem actions satisfy an additivity property: if a user performs two successive deposits (resp.redeems) on an AMM, then the same result can be obtained through a single deposit (resp.redeem).Instead, swap actions are not additive, in general: we will study sufficient conditions for the additivity of swap actions in section 5 (see Theorem 5.6).
Theorem 4.10 (Additivity).Let Γ (2) if T 0 = A : rdm(v : τ) and T 1 = A : rdm(v : τ), then: Reversibility of deposit and redeem actions.The following theorem establishes that deposit and redeem transactions are reversible: more precisely, the effect of a deposit action can be reverted by a redeem action, and vice versa, the effect of a redeem action can be reverted by a deposit action.The only exception is a deposit action that creates an AMM, through the rule [Dep0].Swap actions are not reversible, in general: we will study sufficient conditions for their reversibility in section 5 (see Theorem 5.9).In general, the study of reversible computation models, which dates back to [Ben73], is an active area of research, which has led to a wide range of applications in software systems [MSG + 20].In particular, the reversibility of AMM actions has useful consequences on their behaviour.For instance, it guarantees that, starting from a "stable" state where no arbitrage is possible, after any transaction it is possible to return to the stable state.More in general, if the swap rate function satisfies the conditions of section 5 that ensure the additivity and reversibility also for swap actions, then for any sequence of transactions: it is possible to fire another transaction and return to the state Γ 0 .Indeed, by additivity we obtain that the effect of the sequence T 1 • • • T n can be emulated by a single transaction T, and then reversibility ensures that T can be reversed, i.e.:

The swap rate function
In the previous section we have established some key structural properties of deposit and redeem actions, e.g.their additivity and reversibility.In general, these properties do not hold for swap actions: it is easy to find swap rate functions SX ∈ R 3 ≥0 → R ≥0 that make these properties false.Throughout this section we introduce some general properties of swap rate functions, and we discuss the properties they induce on the behaviour of AMMs.In sections 5.6-5.8we then discuss the properties enjoyed by the swap rate functions used in some concrete AMM implementations.Coherently with these implementations, we assume that a swap rate function is defined and non-negative for all x > 0, and that the internal exchange rate (i.e., the limit of SX for x leading to 0, see (3.3)) is always defined.5.1.Output-boundedness.Output boundedness guarantees that an AMM has always enough output tokens τ 1 to send to the user who performs a swap(x, τ 0 , τ 1 ).Definition 5.1 (Output-boundedness).A swap rate function SX is output-bounded when, for all x, r 0 , r 1 such that x ≥ 0 and r 0 , r 1 > 0: x • SX (x, r 0 , r 1 ) < r 1 The following lemma establishes sufficient conditions for a swap action to be enabled.
Lemma 5.2.Let T = A : swap(x, τ 0 , τ 1 ), and let A[σ] ∈ Γ.If S Γ {τ 0 , τ 1 } > 0, σ(τ 0 ) ≥ x and SX is output-bounded, then T is enabled in Γ. 5.2.Monotonicity.Consider a transaction A : swap(x, τ 0 , τ 1 ) on an AMM {r 0 : τ 0 , r 1 : τ 1 }.Without making any assumptions on the swap rate function, there is no relation between the effect of this transaction and that of a swap where the parameters have been varied.Monotonicity, instead, ensures that there exists a meaninful relation: the swap rate increases if we decrease the input amount x or the reserves of τ 0 , and if we increase the reserves of τ 1 .The intuition is that lower reserves of τ 0 in the AMM make the x : τ 0 paid by A more "valuable" for the AMM, hence the AMM will output more units of τ 1 for the same input amount.Increasing the reserves of τ 1 in the AMM (keeping those of τ 0 unaltered) produces the same effect.Monotonicity on x also ensures that the internal exchange rate of the AMM is defined, for each token pair.

Additivity.
To extend the additivity property of Theorem 4.10 to swap actions, we must require that the swap rate function is additive.
Definition 5.5 (Additivity).A swap rate function SX is additive when: The idea here is that a user fires a swap transaction (say, T 0 ) with input amount x in a state Γ, and then in the state reached after firing T 0 , she fires another swap transaction (say, T 1 ) with input amount y on the same AMM.The definition of additivity requires that the swap rate of a swap transaction with input amount x + y in Γ is in a given relation with the swap rates computed for T 0 and T 1 and with the input amounts x and y.Theorem 5.6 states that if this relation holds, then a single swap with input amount x + y in Γ produces exactly the same effect of performing first T 0 and then T 1 .Then, Lemma 5.7 allows us to compute the gain of this transaction as the sum of the gains of T 0 and T 1 .
Theorem 5.6 (Additivity of swap).Let Γ If SX is output-bounded and additive, then: 5.4.Reversibility.The reversibility property in Theorem 4.11 states that the effect of deposit and redeem transactions can be reverted.We now devise a property of swap rate functions that give the same guarantee for swap transactions.
Definition 5.8 (Reversibility).A swap rate function SX is reversible when: Consider now a state Γ = {r 0 : τ 0 , r 1 : τ 1 } | ∆, and let α = lim x→0 SX (x, r 0 , r 1 ) be the internal exchange between τ 0 and τ 1 in Γ.If the swap rate function is reversible, then: The intuition of Definition 5.8 is that, to reverse the effect of a swap transaction T that pays x : τ 0 to receive y : τ 1 , one must fire a swap transaction T −1 that pays y : τ 1 to receive x : τ 0 .Of course, this results in the same AMM state that we had before performing T. Writing α for the swap rate SX (x, r 0 , r 1 ), the [Swap] rule fixes y = αx.Hence, assuming that in the initial state the AMM has reserves r 0 : τ 0 and r 1 : τ 1 , after performing T its reserves will be r 0 + x : τ 0 and r 1 − αx : τ 1 .In this state, requiring that the swap rate for an input of y : τ 1 is 1 α (as done by Definition 5.8) implies that the AMM outputs x : τ 0 , reverting the reserves of the AMM to the initial values.
The following theorem formalises the intuition above, establishing that, when the swap rate function is reversible, swap transactions are reversible.Together with Theorem 4.11, all the AMM actions are reversible under this hypothesis.
Theorem 5.9 (Reversibility of swap).Let T = A : swap(x, τ 0 , τ 1 ), and let Lemma 5.10 allows us to compute the gain of the reverse transaction T −1 in the state reached after performing T as a function of the gain of T. As expected by preservation of the global net worth, the gain of T −1 is the opposite of that of T.

Homogeneity.
A swap rate function is homogeneous when the swap rate is not affected by a linear scaling of the three parameters.Homogeneity is useful to relate the swap rate before and after deposit or redeem transactions, since their effect is a linear scaling of the AMM reserves.Lemma 5.12 establishes one the the landmark properties of AMMs we have anticipated in section 2: when the swap rate function is homogeneous, deposits and redeems do not affect the internal swap rate.
Theorem 5.14 (Constant sum swap rate).The constant sum swap rate function: SX (x, r 0 , r 1 ) = 1 is monotonic, reversible, additive, and homogeneous.Furthermore, its internal swap rate and its slippage are given by: Note that the constant sum function is not output-bounded, since the output amount may exceed the reserves of the output token.A positive aspect of constant sum AMMs is that they do not suffer from slippage.With constant sum AMMs, the internal exchange rate is always 1, and so there is zero slippage (see Equations (3.3) and (3.4)).A negative aspect is that constant sum AMMs do not allow the token reserves to grow unboundedly: indeed, the bound is fixed with the first deposit.This makes constant sum AMMs unsuitable for scenarios where one wants the liquidity of the AMM to increase over time, and to incentivise users to deposit through minted tokens.When the oracle and internal exchange rates are not aligned (i.e., when the prices of the two tokens are different), then rational users will drain the reserves of the most expensive token type held by the AMM.Despite these drawbacks, the constant sum swap rate is suitable situations where the two token types in the AMM are supposed to be equally prices, like for stablecoins.This is the case e.g. for mStable [mSt20].5.7.Constant product swap rate.The constant product swap rate function (introduced before in Definition 2.1) enjoys all the properties discussed previously in this section. 4  Theorem 5.15 (Constant product).The constant product swap rate function is outputbounded, strictly monotonic, reversible, additive, and homogeneous.Furthermore, its internal swap rate and its slippage are given by: Compared to the constant sum swap rate, a point in favour of the constant product is output-boundedness, which allows users to add unbounded liquidity to the AMM.A point against is slippage, which grows linearly with the amount of the input token.Therefore, when the internal exchange rate is aligned with the oracle's, users are disincentivised from performing large swaps.The most prominent AMM platform adopting the constant product is Uniswap v2 [uni21].Curve [cur20] uses a hybrid swap rate function, which approximates a constant sum for an interval of input values x, and behaves as a constant product outside the interval.In this way, it achieves a small slippage within the interval, at the same time allowing unbounded liquidity thanks to output-boundedness.
5.8.Constant mean swap rate.The constant mean swap rate function generalises the constant product by associating weights w 0 , w 1 ∈ R >0 to the token types held by the AMM, so to preserve the following equality: The following theorem shows that the constant mean function enjoys most of the properties of the constant product, except reversibility.
Theorem 5.16 (Constant mean swap rate).The constant mean swap rate function: is output-bounded, monotonic, additive, and homogeneous.Furthermore, its internal swap rate and its slippage are given by: The most prominent AMM plaform using the constant mean swap rate is Balancer [bal19].Users fix the weights w 0 , w 1 of token types when an AMM is created; once fixed, these weights cannot be changed.The constant product swap rate can be seen as the special case of the constant mean where the two weights are equal.

The economic mechanism of AMMs
AMMs can be seen as games where users compete to increase their net worth.We now study the incentive mechanisms of AMMs from a game-theoretic perspective.
6.1.Arbitrage.The arbitrage game is a single-player, single-round game, where the player can perform a single move on a given AMM pair τ 0 , τ 1 in order to maximize her gain.The initial game states have the form Γ 0 = A[σ] | {r 0 : τ 0 , r 1 : τ 1 } | ∆, where A is the player; the moves of A are all the possible transactions that can be fired by A (we also consider doing nothing as a possible move).More formally, a move is a sequence λ such that either λ = ε (the empty sequence), or λ = T with wal (T) = A. The goal of A is to maximize her gain G A (Γ 0 , λ) on the AMM pair τ 0 , τ 1 .A solution to the game is a move λ that satisfies such goal.We study the arbitrage game under the assumption that A holds no minted tokens {τ 0 , τ 1 }.In this way, by Lemma 3.2, A's gain only depends on the input amount of A's swap, on the reserves of τ 0 and τ 1 in the AMM, and on their prices.In practice, AMM users are logically partitioned in two groups, e.g.liquidity providers (who perform deposits and redeems) and traders (who perform swaps), so basically here we are considering the arbitrage game from the traders' point of view.We further assume that A's balance is enough to allow A to perform the optimal swap.This is a common assumption in formulations of the arbitrage game: in practice, this can be achieved by borrowing the needed amount of the input token from a lending pool via a flash-loan [QZLG21, WWL + 20].Theorem 6.3 shows that a rational agent is incentivized to perform a swap to realign the internal and the oracle's exchange rate.The optimal solution to the arbitrage game can be approximated by multiple users who swap smaller amounts than the optimal one.
Before devising a solution to the arbitrage game, we examine the potential candidates for the solution.Observe that doing nothing (i.e., λ = ε) has clearly zero gain, as well as depositing or redeeming, as established by Lemma 4.5.Hence, if one of such moves is a solution, so are the other two: without loss of generality, we assume that A's move will be λ = ε when there is no strategy which allows A to increase her gain.
We first show in Lemma 6.2 that, if a swap with input τ 0 and output τ 1 has a positive gain, then a swap with input τ 1 and output τ 0 will have a negative gain, whatever input amount is chosen.This holds whenever the swap rate function is monotonic and reversible.Lemma 6.1 is instrumental to prove Lemma 6.2, as it finds the needed relation between the swap rate function and the exchange rate.Passing from this relation to the gain of the swap transaction is obtained by means of Lemma 3.3.Lemma 6.1.If SX is strictly monotonic and reversible, then for all x > 0: SX (x, r 0 , r 1 ) ≥ X(τ 0 , τ 1 ) =⇒ ∀y > 0. SX (y, r 1 , r 0 ) < X(τ 1 , τ 0 ) Lemma 6.2 (Unique direction for swap gain).Let Γ = A[σ] | {r 0 : τ 0 , r 1 : τ 1 } | ∆ be such that σ{τ 0 , τ 1 } = 0, and let T d (x) = A : swap(x, τ d , τ 1−d ), for x > 0 and d ∈ {0, 1}.If SX is output-bounded, strictly monotonic and reversible, then for all y > 0 such that στ 1−d ≥ y: Theorem 6.3 devises a general solution to the arbitrage game, determining the swap transaction that maximizes A's gain.This is the transaction A : swap(x 0 , τ 0 , τ 1 ) such that, in the state Γ reached after performing it from the initial state, the internal exchange rate between τ 0 and τ 1 is aligned to the oracle's exchange rate.By Lemma 3.3, no move from Γ can increase A's gain, i.e. the solution for the arbitrage game in Γ is to do nothing.Lemma 6.2 guarantees that swaps in the other direction are not solutions, since they decrease A's gain.Note that if the internal exchange rate is already aligned to the oracle's, or if A has not enough balance to perform the optimal swap, then the solution to the arbitrage problem is to do nothing.
An implicit desideratum on these solutions is that, given a specific instance of the swap rate function, they are efficiently computable: this is the case, e.g., for the constant product, for which Lemma 6.4 finds a closed formula for the arbitrage solution.
6.2.Swaps after deposits.We show in Theorem 6.6 that deposits incentivise swaps.Namely, if a user B performs a deposit on an AMM for the token pair τ 0 , τ 1 , and then a different user A performs a swap in the resulting state, then A's gain is increased w.r.t. the gain that she would have obtained by performing the same transaction before B's deposit.
The intuition is that larger amounts of tokens in an AMM provide decrease the slippage, therefore attracting users interested in swaps.
Let Γ be such that both T swap and T dep T swap are enabled in Γ.If the swap rate function is homogeneous and strictly monotonic, then: , and let T swap = A : swap(5, τ 0 , τ 1 ).Assuming the constant product swap rate, we have that: Now, assuming P τ 0 = 1 and P τ 1 = 1, we have the following gains for A: as correctly predicted by Theorem 6.6.Note that in the state Γ before the deposit, A has zero gain from her swap, while the same transaction has a positive gain after the deposit.
Theorem 6.8 finds the solution of the arbitrage game after a deposit of another user.More precisely, let λ be the solution in Γ, and let λ be the solution in the state Γ reached after a deposit.If λ is empty, then also λ is such.If λ is a swap with input τ 0 and output τ 1 , then also λ is such (but for the input amount).(1) if λ = A : swap(x, τ 0 , τ 1 ), then 6.3.Swaps after redeems.We now study swaps and arbitrage after redeems.Conversely to what we have shown before in Theorem 6.6, we find that redeems disincentivise swaps (Theorem 6.9).Similarly to Theorem 6.8, if the solution to the arbitrage game in a state Γ is a swap, then after a redeem in Γ the solution is still a swap which only differs in the input amount (Theorem 6.10).Theorem 6.9 (Swap after redeem).Let T swap and T rdm be two transactions such that wal (T swap ) = A = wal (T rdm ) and, for ∈ {swap, rdm}, type(T ) = and tok (T ) = {τ 0 , τ 1 }.
Let Γ be such that both T swap and T rdm T swap are enabled in Γ.If the swap rate function is homogeneous and strictly monotonic, then: (1) if λ = A : swap(x, τ 0 , τ 1 ), then

Maximal extractable value
Maximal Extractable Value (MEV) refers to a class of attacks to smart contracts where miners/validators exploit their power to reorder, drop or insert transactions in a block to "extract" value from the mempool (i.e., the set of transactions sent to the blockchain network, but not appearing yet in a block).Empirical research has shown that AMMs are routinely targeted by MEV attacks [DGK + 20,QZG21,ZQC + 21,ZQT + 21], and indeed recent versions of the Ethereum protocol implementation include a MEV extraction mechanism [mev22].This has negative effects on AMM users, as well as on transaction fees and network congestion.
We show that our AMM model makes it possible to faithfully express MEV attacks.Consider a constant product AMM for two token types τ 0 , τ 1 with the same price, e.g.P τ 0 = P τ 1 = 1, and consider a state: where we use A to impersonate a honest user, and M for a miner, acting as an adversary.By Lemma 3.3 we know that the AMM is in equilibrium in Γ, because, for each x > 0: SX (x, 10, 10) = 10 10 + x < 1 = X(τ 0 , τ 1 ) Therefore, neither a miner nor any other user can increase their net worth in Γ. Assume now that A sends the transaction T A = A : swap(50, τ 0 , τ 1 ) to the blockchain network.Before being included in a block, T A is added to the mempool, from where miners gather transactions to construct blocks.Any miner owning enough token units can increase their gain by firing A's transaction within a sandwich of M's swaps.For instance, assume that M's wallet is M[40 : τ 0 , 1 : τ 1 ].Then M can construct a block: We have that Γ λ − → Γ , where: This results in a positive gain for M, since: Summing up, M has managed to extract value from A's transaction in the mempool, improving her gain to the detriment of A's net worth.
The mechanism of guarded transactions, which allows users to specify a lower bound to the amount of tokens outputted upon a swap (see section 8), is a partial countermeasure against MEV attacks.For instance, in the scenario above A could have sent a guarded transaction T A = A : swap(50 : τ 0 , 8.3 : τ 1 ), which would have ensured A to receive at least 8.3 : τ 1 upon the swap.This would have neutralised the sandwich attack described before, since after the first M's transaction, T A is no longer valid.Even though guarded transactions mitigate the issue of not knowing the state where one's transaction will be fired, they are not a complete defence against MEV attacks.Indeed, in [BCL22] it is shown that adversaries can craft sandwiches that extract value from any non-empty mempool of swap and dep (guarded) transactions.Further analyses the effect of MEV on constant-function AMMs are developed in [KDC22].Several approaches to prevent MEV attacks are discussed in [HW22, ByCD + 21].

Variants of the basic model
Our AMM model abstracts from implementation-specific features, and from the features that are orthogonal to the core functionality of AMMs (e.g., governance).We discuss below some extensions and variants of our model to make it closer to actual implementations, and their impact on our theory.
12:26 8.1.Fees.In actual AMM implementations, the swap rate -and consequently, the semantics of [Swap] actions -also depends on a trading fee 1 − φ.For instance, incorporating this fee in the constant product swap rate function is usually done as follows: In this case, when the trading fee is zero (i.e., φ = 1), the swap rate preserves the product between AMM reserves; a higher fee, instead, results in reduced amounts of output tokens received from swap actions.Intuitively, the AMM retains a portion of the swapped amounts, but the overall reserves are still distributed among all minted tokens, thereby increasing the redeem rate of minted tokens.The structural properties in section 4 are not affected by swap fees.
8.2.Price updates.An underlying assumption of our model is that the price of atomic tokens is constant, and consequently that exchange rates are stable.In the wild, prices and exchange rates can vary over time, possibly making the net worth of users holding minted tokens decrease -a phenomenon commonly referred to as impermanent loss [imp20].
Introducing price updates in our AMM model is straightforward: it suffices to extend states Γ with price oracles, parameterize with Γ the exchange rate X, and extend the AMM semantics with a rule to non-deterministically update token prices.Most of the structural properties in section 4 would not be affected by this extension: the exceptions are determinism (Lemma 4.1) and net worth preservation (Lemma 4.5(b), while part (a) would still be true for deposits and redeems).Technically, also the properties about swaps and incentives in section 5 and section 6 are preserved, although this happens because most of these properties assume sequences of deposits, redeems and swaps.If we allow these actions to be interleaved with price updates, some properties no longer hold: notably, the optimality of the solution λ to the arbitrage problem (Theorem 6.3) is lost if λ is front-run by a price update that alters the exchange rates, since this affects the condition provided by Theorem 6.3.
In practice, the assumption of constant exchange rates assumed by Theorem 6.3 may hold in the case of exchanges between stable coins [mak20].Here, arbitrage ensures the alignment between swap rates and exchange rates, so users are hence incentivized to provide liquidity to AMMs, as the redeem rate is likely to increase over time.8.3.Guarded transactions.The semantics of AMMs in section 2 defines how the state evolves upon transactions.In practice, when a user emits a transaction, she cannot predict the exact state in which it will be actually committed.This may lead to unexpected or unwanted behaviours.For instance, the gain of a swap transaction sent by A may be reduced if the transaction is front-run by a redeem transaction sent by B, as established by Theorem 6.9.The problem here is that redeems decrease the swap rate (by Lemma 5.13), and consequently the amount of output tokens received by A. As a partial countermeasure to this issue, Uniswap allows users to specify a lower bound y min to the amount of received tokens.In our model, we could formalise this behaviour by amending the [Swap]  Similar countermeasures apply to [Rdm] and [Dep] rules.For redeems, the user can enforce lower bounds v min 0 , v min 1 on the amount of received tokens τ 0 , τ 1 as follows: Amending the [Dep] rule is more complex, since here we must define ranges for the deposited amounts v 0 , v 1 , and we must preserve the ratio between the AMM reserves.A possible way to achieve this behaviour is the following rule: These amendments, which are coherent with Uniswap implementation [uni21], preserve all the properties, both structural and economic, established in the previous sections, modulo a restatement of the properties which have transactions in their hypotheses.For instance, in Theorem 6.8, the scaling factor a will be computed on the actual deposited value, rather than on the parameter of the transaction.Note that, although the new rules can disable some transactions which were enabled with the rules in section 2, this does not affect the transactions reordering result (Lemma 4.9).

Other variants.
There are further differences between our model and the existing AMM platforms, that could be accounted for in extensions of our model.Uniswap implements flash-loans as part of the swap actions: namely, the user can optionally borrow available pair funds [uni20a] whilst returning these within the same atomic group of actions.Further, Uniswap implements an exchange rate oracle, allowing smart contracts to interpret (averages of) recent swap rates as exchange rates [uni20b].Balancer [bal19] extends token pairs to token tuples: a user can swap any two non-coinciding sets of supported tokens, such that the swap rate is maintained.In all AMM implementations, token balances are represented as integers: consequently, they are subject to rounding errors [rva18].AMM platforms frequently implement a governance logic, which allow "governance token" holders to coordinate changes to AMM fee-rates or swap rate parameters.

Conclusions
We have proposed a theory of AMMs, which encompasses and generalizes the main functional and economic aspects of the mainstream AMM implementations, providing solid grounds for the design of future AMMs.
The core of our theory is a formal model of AMMs (section 2), based on a thorough inspection of leading AMM implementations like Uniswap [uni21], Curve [cur21b], and Balancer [bal19].An original aspect of our model is that it is parametric with respect to the key economic mechanism -the swap rate function -that algorithmically determines exchange rates between tokens.Our model features an executable semantics, which can support future implementations and analysis tools; an open-source implementation of our semantics is available as a companion of this paper.
Building upon our model, we prove a set of properties characterizing both structural (section 4) and economic (section 3, section 6) aspects of AMMs.Structural properties include, e.g., that value cannot be created or destroyed (Lemma 4.5), that tokens cannot be frozen within an AMM (Lemma 4.8) and that some sequences of transactions can be reordered without affecting their semantics (Lemma 4.9).Concerning the economic properties, we address the arbitrage problem, the main game-theoretic foundation behind the economic incentives of AMMs.Theorem 6.3 provides sufficient conditions for the existence of solutions, and links the solutions to the expected relation between internal exchange rate and oracle's exchange rate.We show that deposits incentivize swaps, while redeems have the opposite effect.With respect to previous works, which focus on specific economic mechanisms, all our results are parametric with respect to the swap rate function.We identify indeed, for each property, a set of conditions on swap rate functions that are sufficient for the property to hold (section 5).
AMM platforms like Uniswap [uni21] and Curve [Ego19] have overtaken centralized cryptocurrency markets in size and usage.On the one hand, a better understanding of AMM design in cases where AMMs host the majority of the token's global swap volume is critical [AEC20].On the other hand, the growth of AMMs is making them more attractive for malicious users, even if it is difficult to exactly quantify the effect of attacks.
This paper, together with our work on formalizing another DeFi archetype called lending pool [BCL21a], is the first step towards a general theory of DeFi [BCL21c].We believe that a general theory encompassing interactions between different DeFi archetypes is crucial to be able to reason about their structural, economic and security aspects, as typical DeFi applications operate within a wider ecosystem, composed by a set of collaborating or competing agents, which interact through possibly separate execution environments.

Figure 1 :
Figure 1: Interactions between two users and an AMM.