SoK: Decentralized Exchanges (DEX) with Automated Market Maker (AMM) protocols

Jiahua Xu Nazariy Vavryk Krzysztof Paruch Simon Cousaert UCL CBT reNFT Vienna University of Economics and Business UCL CBT

Abstract—As an integral part of the liquidity providers benefit from asset supply with exchange (DeFi) ecosystem, Automated Market Maker (AMM) based fees from pool users. Furthermore, maintaining the state of Decentralized Exchanges (DEXs) have gained massive traction an order book is computationally expensive, which is costly with the revived interest in and distributed technology in general. Most prominently, the top six AMMs— given the native price mechanism on the blockchain. , Balancer, Curve, DODO, and Sushiswap— While this problem is minimized by keeping the order books hold in aggregate 15 billion USD worth of crypto-assets as off-chain, DEX with AMMs allows for more accessible liq- of March 2021. Instead of matching the buy and sell sides, uidity provision, especially for low-liquid assets. AMMs employ a peer-to-pool method and determine asset Despite apparent advantages such as , au- price algorithmically through a so-called conservation function. Compared to centralized exchanges, AMMs exhibit the appar- tomation and continuous liquidity, AMMs are often charac- ent advantage of decentralization, automation and continuous terized by high slippage with asset exchange and divergence liquidity. Nonetheless, AMMs typically feature drawbacks such loss with liquidity provision. Throughout the last three years, as high slippage for traders and divergence loss for liquidity new protocols have been introduced to the market one after providers. This work establishes a general AMM framework another with incremental improvements and the attempt to describing the economics and formalizing the system’s state-space representation. We employ our framework to systematically com- tackle different issues which were identified as weak spots pare the top AMM protocols’ mechanics, deriving their slippage in a previous version. and divergence loss functions. We further discuss security and While innovative on certain aspects, the various AMM privacy concerns associated with AMM DEXs, and conduct a protocols generally consist of the same set of composed comprehensive literature review on related work covering both mechanisms to allow for multiple functionalities of the system. DeFi and conventional market microstructure. Index Terms—Decentralized Finance, , Therefore these systems are structurally similar, and their automated market maker, blockchain, Ethereum main differences lie in parameter choices and/or mechanism adaptations. Describing a class of mechanisms that defines I.INTRODUCTION the characteristics of an AMM allows assessing the differences A. Background of design choices and their impacts on the system to conse- With the revived interest in blockchain and quently discuss the structural composition of AMMs and make among both the general populace and institutional actors, the statements about their stability for different market conditions. past year has witnessed a surge in crypto trading activity and B. Contributions increasing competition and accelerated development in the Decentralized Finance (DeFi) space. This work establishes a taxonomy of the major components Among all the prominent DeFi applications, Automated of an AMM focusing on stakeholder roles, asset types, mech- Market Makers (AMM) based Decentralized Exchanges anisms, metrics and attack vectors. This framework is used (DEXs) are on the ascendancy, with an aggregate value locked for a comparative analysis of selected projects by comparing exceeding 15 billion USD at the time of writing.1 Different slippage and divergent loss functions of example protocols. arXiv:2103.12732v3 [q-fin.TR] 19 Apr 2021 from order-book based exchanges where the market price This work represents the first systematization of knowledge of an asset is determined by the last matched buy and sell in AMM-based DEXs with deployed protocol examples to the orders, each AMM uses a so-called conservation function that best of our knowledge. determines asset price algorithmically by only allowing the II.AMMPRELIMINARIES exchange rates to move along predefined trajectories which are conditioned upon the quantities of available assets. AMMs This section presents a taxonomy of the main components implement a peer-to-pool method, where liquidity providers across major decentralized exchanges [1]. To guide the fol- contribute assets to liquidity pools while individual users lowing formal definitions, Uniswap can be used as an intuitive exchange assets with a pool containing both the input and example. This protocol allows exchanging two tokens via the the output assets. Exchange users obtain immediate liquidity use of one liquidity pool containing both assets. A constant without having to find an exchange first, whereas product function is parametrized at the time of pool inception, defining a number that has to hold true as the product of both 1https://defipulse.com/ asset quantities for all future states of the system. This property determines the swap prices as any trade must uphold the B. Assets constant product under updated asset amounts in the pool. The Several distinct sorts of assets are used in AMM protocols liquidity is provided to the pool by liquidity providers, which for operations and governance. One or more assets can fulfil receive a pool share representing their relative contribution to several functionalities; one asset may assume multiple roles. the pool. The trading fee for token swaps is accumulated in a) Risk assets: This is the primary type of asset for which the pool and therefore acts as a reward for liquidity providers. the protocol was designed: to provide liquidity in these assets, Other protocols extend this basic functioning, and their specific to facilitate exchange between them and to allow liquidity components are discussed later in this paper. providers to earn rewards in return for their contribution. Typ- ically many different risk assets are involved in one protocol - A. Actors they have to be whitelisted, compatible with the protocol and fulfil the technical requirements (e.g. ERC202 for most AMMs a) Liquidity provider (LP): A liquidity pool creator is on Ethereum). the first liquidity provider (LP) when deploying a new smart b) Base assets: For some protocols, a trading pair always contract that acts as a liquidity pool with some initial supply of consists of a risk asset and a designated base asset. In the case crypto assets. Other LPs can subsequently increase the pool’s of Bancor, every risk asset is paired with BNT, the protocol’s reserve by adding more of the assets that are contained in the native token with an elastic supply [4]. In their early version, pool. In turn, they receive pool shares proportionate to their Uniswap required every pool to be initiated with ETH as one liquidity contribution as a fraction of the entire pool [2]. LPs of the risk assets making it an obligatory base asset. Many earn transaction fees paid by exchange users. While sometimes protocols, such as Balancer and Curve are managed without a subject to a withdrawal penalty, LPs can freely remove funds designated base asset as they connect two or more risk assets from the pool [3] by surrendering a corresponding amount of directly in the composition of their portfolios. pool shares [2]. c) Pool shares: Also known as “liquidity shares” and The liquidity pool must be initialized with two or more “liquidity provider shares”, pool shares represent ownership different assets for the to parametrize the in the portfolio of assets within a pool, and are distributed conservation function and set the initial relative prices. Pool to liquidity providers. Shares qualify for the reception of fees creators initialize the pool with quantities that reflect the that are earned in the portfolio whenever a trade occurs. Shares market prices to avoid unnecessary divergence loss. The act can be redeemed at any time to withdraw back the liquidity of liquidity provision or removal updates the value of the initially provided. conservation function invariant(s) (see Section III). Liquidity d) Protocol tokens: Protocol tokens are used to represent providers are also called liquidity miners due to new protocol voting rights in a decision formation process defined in the tokens minted and distributed to them as a reward in addition protocol and are thus also termed “governance tokens”. Pro- to pool shares when they supply funds. Like centralized tocol tokens are typically valuable assets that are sometimes exchanges, an AMM-based DEX can facilitate an initial ex- tradeable even outside of the AMM and can incentivize change offering to supply a new asset through liquidity pool participation. For example, they might be rewarded to liquidity creation. providers in proportion to their liquidity supply. b) Exchange user (Trader): A trader submits an ex- C. Fundamental AMM economics change order to a liquidity pool by specifying the input and output asset and one associated quantity - the smart contract 1) Rewards: AMM protocols often run several reward will automatically calculate the exchange rate based on the schemes, including liquidity reward, staking reward, gover- conservation function and execute the exchange order accord- nance rights, and security reward, distributed to different actors ingly. A fee is charged on top of each trade to compensate to encourage participation and contribution. liquidity providers for their capital provision. a) Liquidity reward: Liquidity providers are rewarded for supplying assets to a liquidity pool, as this can be deemed c) Arbitrageurs: Arbitrageurs are a particular type of service for the broader community for which they have to exchange users who compare asset prices across different bear the opportunity costs associated with funds being locked markets to execute trades whenever closing price gaps can in the pool. Liquidity providers receive their share of trading extract profits. In doing so, arbitrageurs ensure consistency of fees paid by exchange users. asset price in other decentralized, centralized, on-chain and b) Staking reward: On top of the liquidity reward in the off-chain exchanges. form of transaction income, liquidity providers are offered the d) Protocol foundation: Protocol foundation consists of possibility to stake certain tokens as part of an initial incentive protocol founders, designers, and developers responsible for program from the token protocol. The ultimate goal of the designing and improving the protocol. The development ac- individual token protocols (see e.g. GIV [5] and TRIPS [6]) tivities are often funded directly or indirectly through accrued is to further encourage token holding, while simultaneously earnings such that the foundation members are financially facilitating token liquidity. incentivized to build a user-friendly protocol that can attract high trading volume. 2https://eips.ethereum.org/EIPS/eip-20 c) Governance right: An AMM may encourage liquidity asset prices. Instead of matching buy and sell orders, exchange provision and/or swapping by rewarding participants gover- rates are determined on a continuous curve. Every trade on an nance right in the form of protocol tokens (see II-B). AMMs AMM-based DEX will always encounter slippage conditioned compete with each other to attract funds and trading volume. upon the trade size, the pool amounts and the exact design To bootstrap an AMM in the early phase with incentivized of the conservation function. The spot price approaches the early pool establishment and trading, a feature called liquidity realized price for infinitesimally small trades, but they deviate mining can be installed where the native protocol’s tokens are more for bigger trade sizes. This effect is amplified for smaller minted and issued to liquidity providers and/or exchange users. liquidity pools as every trade will significantly impact the d) Security reward: Just as every protocol built on top of relative quantities of assets in the pool and, therefore, higher an open, distributed network, AMM-based DEXs on Ethereum slippage. suffer from security vulnerabilities. Besides code auditing, b) Divergence loss: For liquidity providers, assets sup- a common practice that a protocol foundation adopts is to plied to a protocol are still exposed to volatility risk, which have the code vetted by a broader developer community and comes into play in addition to the loss of time value of locked reward those who discover and/or fix securities of the protocol funds. A swap alters the asset composition of a pool, which with monetary prizes, commonly in fiat currencies, through a automatically updates the asset prices implied by the conser- bounty program. vation function of the pool (Equation 3). This consequently 2) Explicit costs: Interacting with AMM protocols incurs changes the value of the entire pool. Compared to holding the various costs, including charges for some form of “value” assets outside of an AMM pool, contributing the same amount created or “service” performed and fees for interacting with of assets to the pool in return for pool shares can result in the blockchain network. AMM participants need to anticipate less value with price movement, an effect termed “divergence three types of fees: liquidity withdrawal penalty, swap fee and loss” or “impermanent loss” (see Section IV). This loss is gas fee. “impermanent” because as asset price moves back and forth, a) Liquidity withdrawal penalty: As introduced in III-B the depreciation of the pool value disappears and reappears all and demonstrated in Section IV later in this paper, withdrawal the time and is only realized when assets are actually taken of liquidity changes the shape of the conservation function out of the pool. and negatively affects the usability of the pool by elevating Since assets are bonded together in an pool, changes of the slippage. Therefore, AMMs such as DODO [7] levy a prices in one asset affect all others in this pool. For an AMM liquidity withdrawal penalty to discourage this action. protocol that supports single-asset supply, this forces liquidity b) Swap fee: Users interacting with the liquidity pool providers to be exposed to risk assets they have not been for token exchanges have to reimburse liquidity providers for holding in the first place. the supply of assets. This compensation comes in the form of swap fees that are charged in every exchange trade and then distributed to liquidity pool shareholders. A small percentage III.FORMALIZATION OF MECHANISMS of the swap fees may also go to the foundation of the AMM to further develop the protocol. Overall, the functionality of an AMM can be generalized c) Gas fee: Every interaction with the protocol is ex- formally by a set of few mechanisms. These mechanisms ecuted in the form of an on-chain transaction and is thus define how users can interact with the protocol and what subject to gas fee applicable to all transactions on the un- the response of the protocol will be given particular user derlying blockchain. In a decentralized network validating actions. Action-related mechanisms dictate how providing and nodes verifying transactions need to be compensated for their withdrawing liquidity as well as swapping assets are executed efforts, and transaction initiators must cover these operating where protocol-related properties define how fees and rewards costs. The paid gas fees depend on the price of, for example, are calculated. On top of that, there are some protocol- ETH and the gas price of the transaction chosen by the user. specific mechanisms for governance and security, but the The average gas price evolution shows that the gas fees are aforementioned basic mechanisms are the same. becoming increasingly more substantial3 as a result of the While all AMMs are similar in this basic functionality, growing adoption of Ethereum. Compounded with the rising they have two ways of differentiating themselves and propose ETH price and the complexity of AMM contracts, gas fees improvements to existing protocols. The first option is to must be taken into consideration when interacting with AMMs. take an existing implementation as given, copy and reuse all 3) Implicit costs: Two essential implicit costs native to mechanisms and adjust the fee and reward structure to change AMM-based DEXs are slippage for exchange users and di- the incentives and payouts of the protocol and by doing so, vergence loss for liquidity providers. potentially improve targeted user or protocol metrics. The a) Slippage: Slippage is defined as the difference be- second option is to change the composition or functionality of tween the spot price and the realized price of a trade and the mechanism or propose a new pool structure that will call is caused by the curve design of an AMM that dictates the for major changes in how the protocol works. In this way, key metrics can be improved as well but in a completely different 3https://ycharts.com/indicators/ethereum average gas price way. User actions Pool state Invariant C, despite its name, refers to the pool variable that Reserves Provide liquidity + stays constant only with swap actions but changes at liquidity in all assets (mint Token A Token B Token C Core actors LP shares) provision and withdrawal. In contrast, trading moves the price Liquidity pool Provide liquidity + creator of traded assets; specifically, it increases the price of the output in one asset ... (mint LP shares) Liquidity + asset relative to the input asset, reflecting a value appreciation provider Withdraw - of the output asset driven by demand. Liquidity provision and liquidity (redeem - Exchange user LP shares) Liquidity shares withdrawal, on the other hand, should not move the asset price. - Swap + General rules of AMM-based DEX 1) The price of assets in an AMM pool stays constant Figure 1: Stylized AMM mechanism for pure liquidity provision and withdrawal activi- ties. 2) The invariant of an AMM pool stays constant for A. State space representation pure swapping activities. The functioning of any blockchain-based system can be modeled using the state-space terminology. States and agents Formally, the state transition induced by pure liquidity constitute main system components; protocol activities are change and asset swap can be expressed as follows. described as actions (Figure 1); the evolution of the system over time is modelled with state transition functions. This can ({rk}k=1,...,n, {pk}k=1,...,n, C, Ω) liquidity change 0 0 be generalized into a state transition function f encoded in the −−−−−−→({rk}k=1,...,n, {pk}k=1,...,n, C , Ω) (2) protocol such that χ −→a χ0, where a ∈ A represents an action f f imposed on the system while χ and χ0 represent the current and future states of the system respectively. The object of interest is the state χ of the liquidity pool ({rk}k=1,...,n, {pk}k=1,...,n, C, Ω) which can be described with swap 0 0 −−→({rk}k=1,...,n, {pk}k=1,...,n, C, Ω) (3) f 0 χ = ({rk}k=1,...,n, {pk}k=1,...,n, C, Ω) (1) Note that protocol-specific intricacies may result in asset where rk denotes the quantity of token k in the pool, pk price change with liquidity provision/withdrawal, or invariant the current spot price of token k, C the conservation function C update with trading. invariant(s), and Ω the collection of protocol hyperparameters. The asset spot price can remain the same only when assets This formalization can encompass various AMM designs. are added to or removed from a pool proportionate to the The most critical design component of an AMM is its current reserve ratio (r1 : r2 : ... : rn). Disproportionate conservation function which defines the relationship between addition or removal can be treated as a combination of two different state variables and the invariant(s) C. The conser- actions: proportionate reserve change plus asset swap, such as vation function is protocol-specific as each protocol seeks to with Balancer [3]. Therefore, this action is no longer a pure prioritize a distinct feature and target particular functionalities. liquidity provision/withdrawal and would thus move the asset For example, Uniswap implements an elementary conservation spot price. function that achieves a low gas fee; Balancer’s conservation Specific fee mechanisms also cause invariant C to become function links mul whereas Curve’s conservation function is variant through trading. Specifically, when trading fees are complex but guarantees low slippage (see Section IV). kept within the liquidity pool, a trading action can be decom- The core of an AMM system state is the quantity of each posed into asset swap and liquidity provision. This action is, asset held in a liquidity pool. Their sums or products are therefore, no longer a pure asset swap and would thus move typical candidates for invariants. Examples of a constant- the value of C (see e.g. [11]). Also, as float numbers are not yet sum market maker include mStable [8]. Uniswap [9] rep- fully supported by [12]—the language for Ethereum resents constant-product market makers, while Balancer [3] smart contracts, AMM protocols typically recalculate invariant generalizes this idea to a geometric mean. The Curve [10] C after each trade to minimize the accumulation of rounding conservation function is notably a combination of constant- errors. sum and constant-product (see Section IV).

B. Liquidity change and asset swap C. Generalized formulas Hyperparameter set Ω is determined at pool creation and In this section, we generalize AMM formulas necessary shall remain the same afterwards. While this value of hy- for demonstrating the interdependence between various AMM perparameters might be changed through protocol governance state variable, as well as for computing slippage as well as activities, this does not and should not occur on a frequent divergence loss. Mathematical notations and their definitions basis. can be found in Table I. Table I: Mathematical notations for pool mechanisms 0 Apparently, ro can be expressed as a function of the original Notation Definition Applicable protocols reserve composition {rk}, input quantity xi, namely, 0 Preset hyperparameters, Ω ro := Ro(xi, {rk}; C) (10) wk Weight of asset reserve rk Balancer A Slippage controller Uniswap V3, Curve, DODO c) Compute swapped quantity: The quantity of tokeno State variables swapped is simply the difference between the old and new C Conservation function invariant all reserve quantities: r Quantity of token in the pool all k k 0 pk Current spot price of tokenk all xo := Xo(xi, {rk}; C) = ro − ro (11) Process variables 4) Slippage: Slippage measures the deviation between ef- x Input quantity added to reserve all i fective exchange rate xi and the pre-swap spot exchange rate of tokeni (removed when xi < xo 0) iEo, expressed as: ρ Token value change all xi/xo Functions S(xi, {rk}; C) = − 1 (12) C Conservation function all iEo Z Implied conservation function all 5) Divergence loss: Divergence loss describes the loss in iEo tokeno price denominated in all value of the all reserves in the pool compared to holding tokeni S Slippage all the reserves outside of the pool, after a price change of V Reserve value all an asset. Based on the formulas for spot price and swap L Divergence loss Uniswap, Balancer, Curve quantity established above, the divergence loss can generally be computed following the steps described below. In the 1) Conservation function: An AMM conservation function, valuation, we assign tokeni as the denominating currency for also termed “bonding curve”, can be expressed explicitly as all valuations. While the method to be presented can be used a relational function between AMM invariant and reserve for multiple token price changes through iterations, we only demonstrate the case where only the value of tokeno increases quantities {rk}k=1,...,n: by ρ, while all other tokens’ value stay the same. Tokeni is C = C({rk}) (4) the numeraire.´ Designating one of the tokens in the pool as a numeraire´ can also be found in DeFi simulation papers such A conservation function for each token pair, say ri—r0, must be concave, nonnegative and nondecreasing [13] (see as [13]. also Figure 3). For complex AMMs such as Curve, it might a) Calculate the original pool value: The value of the be convenient to express the conservation function implicitly pool denominated in tokeni can be calculated as the sum of in order to derive exchange rates between two assets in a pool: the value of all token reserves in the pool, each equal to the reserve quantity multiplied by the exchange rate with tokeni: Z({rk}; C) = C({rk}) − C = 0 (5) X V ({rk}; C) = iEj({rk}; C) · rj (13) 2) Spot exchange rate: The spot exchange rate between j token and token can be calculated as the slope of the r —r i o i o b) Calculate the reserve value if held outside of the pool: curve (see examples in Figure 3) using partial derivatives of If all the asset reserves are held outside of the pool, then a the conservation function Z. change of ρ in tokeno’s value would result in a change of ρ ∂Z({rk}; C)/∂ro iEo({rk}; C) = (6) in tokeno reserve’s value: ∂Z({rk}; C)/∂ri Vheld(ρ; {rk}, C) = V ({rk}; C) + [jEo({rk}; C) · ro] · ρ Note that iEo = 1 when i = o. 3) Swap amount: The amount of tokeno received xo (spent c) Obtain re-balanced reserve quantities: Exchange when xo < 0) given amount of tokeni spent xi (received when users and arbitrageurs constantly re-balance the pool through xi < 0) can be calculated following the steps below. trading in relatively “cheap”, depreciating tokens for relatively a) Update reserve quantities: Input quantity xi is simply “expensive”, appreciating ones. As such, asset value move- added to the existing reserve of tokeni; the reserve quantity ments are reflected in exchange rate changes implied by the of any token other than tokeni or tokeno stays the same: dynamic pool composition. Therefore, the exchange rate between token and each other r0 := R (x ; r ) = r + x (7) o i i i i i i j 6= o {r0 } 0 tokenj ( ) implied by new reserve quantities k , r = rj, ∀j 6= i, o (8) j compared to that by the original quantities {rk}, must satisfy b) Compute new reserve quantity of tokeno: The new equation sets 14. At the same time, the equation for the reserve quantity of all tokens except for tokeno is known from conservation function must stand (Equation 15). the previous step. One can thus solve r0 , the unknown quantity 0 o jEo({rk}; C) of token , by plugging it in the conservation function: ρ = − 1, ∀j 6= o (14) o jEo({rk}; C) 0 0 Z({rk}; C) = 0 (9) 0 = Z({rk}; C) (15) 2.25 6.4 Table II: Comparison Table of discussed DEXs: value locked, 28 28000 2800 16 0.8 16 2.00 5.6 14 14 24 24000 1.75 2400 0.7 4.8 12 12 20 20000 1.50 2000 0.6 4.0 trade volume of the past 7 days, the market share by the last 30 10 0.5 10 16 16000 1.25 1600 3.2 8 8 1.00 0.4 12 12000 1200 6 6 0.75 2.4 0.3 days volume, the governance token, the number of governance 8000 800 8 1.6 4 0.2 4

Total pool count 0.50 Total pool count Total pool count Total pool count Volume (bn USD) 4000 Volume (bn USD) Volume (bn USD) 2 Volume (bn USD) 2 4 0.25 400 0.8 0.1 token holders and the fully diluted value, as on 15 April 2021. 0 0 0 0 05/2020 08/2020 11/2020 02/2021 05/2020 08/2020 11/2020 02/2021 05/2020 08/2020 11/2020 02/2021 05/2020 08/2020 11/2020 02/2021 Data retrieved from DeFi Pulse and Dune Analytics on 22 (a) Uniswap (b) Balancer (c) Curve (d) DODO March 2021. Figure 2: Monthly volume and the total pool count for AMMs. Data Protocol Value locked Trade volume Market Governance Governance Fully diluted value from The Graph and Dune Analytics. (billion USD) (billion USD) (%) token token holders (billion USD)

Uniswap 6.30 6.99 53.8 UNI 212,506 37.4 Sushiswap 4.26 1.99 15.4 SUSHI 43,306 3.78 Curve 5.33 1.89 14.6 CRV 28,669 4.89 Bancor 1.96 0.66 5.1 BNT 38,881 1.37 slippage, as well as divergence loss of those protocols. A Balancer 2.33 0.46 3.6 BAL 34,225 2.8 DODO 0.07 0.15 1.16 DODO 9,568 5.0 summary of formulas can be found in Table III. We refer our readers to Appendix A for a detailed explanation and derivation of those formulas. The protocols’ conservation A total number of n-equations (n−1 with equation sets 14, function, slippage, as well as divergence loss under different plus 1 with Equation 15) would suffice to solve n unknown hyperparameter values are plotted in in Figure 3, Figure 4 and 0 variables {rk}k=1,...,n, each of which can be expressed as a Figure 5, respectively. We always use token1 as price or value function of ρ and {rk}: unit; namely, token1 is the assumed numeraire.´ 0 1) Uniswap V2: The Uniswap protocol prescribes that a rk := Rk(ρ, {rk}; C) (16) liquidity pool always consists of one pair of assets. The pool’s d) Calculate the new pool value: The new value of the smart contract always assumes that the reserves of the two pool can be calculated by summing the products of the new assets have equal value. Uniswap implements a conservation reserve quantity multiplied by the new price (denominated by function with a constant-product invariant. tokeni) of each token in the pool: 2) Uniswap V3: Uniswap V3 enhances Uniswap V2 by 0 X 0 0 allowing liquidity provision to be concentrated on a fraction of V (ρ, {rk}; C) = iEj({r }; C) · r (17) k j the bonding curve, thus virtually amplifying the conservation j function invariant and reducing the slippage. Uniswap V3 is e) Calculate the divergence loss: Divergence loss can be a special case of the Uniswap V2 with the slippage controller expressed as a function of ρ, the change in value of an asset A → ∞ (Figure 3a). in the pool: 3) Balancer: The Balancer protocol allows each liquidity 0 V (ρ, {rk}; C) pool to have more than two assets [3]. Each asset reserve rk is L(ρ, {rk}; C) = − 1 (18) P Vheld(ρ; {rk}, C) assigned with a weight wk at pool creation, where wk = 1. k Weights are pool hyperparameters and do not change with IV. COMPARISON OF AMM PROTOCOLS either liquidity provision/removal or asset swap. The weight AMM-based DEXs are home to billions of dollars worth of an asset reserve represents the value of the reserve as a of on-chain liquidity. Table II lists major AMM protocols, fraction of the pool value. Balancer can also be deemed a their respective value locked, as well as some other general generalization of Uniswap; the latter is a special case of the metrics. Uniswap is undeniably the biggest AMM measured 1 former with w1 = w2 = 2 (Figure 3b). by trade volume, as confirmed by the volume growth dis- 4) Curve: With the Curve protocol, formerly StableSwap played in Figure 2a, and the number of governance token [10], a liquidity pool consists of two or more assets with holders, although it is remarkable that Sushiswap has more the same peg, for example, USDC and , or wBTC and value locked within the protocol. The number of governance renBTC. Curve approximates Uniswap V2 when its constant- token holders of smaller protocols as Bancor and Balancer is sum component has a near-0 weight (Figure 3c). relatively significant compared to Curve token holders, as they 5) DODO: DODO only supports 2-asset liquidity pools at do approximately half of the volume but have 25 to 50% more the moment. The pool creator opens a new pool with some governance token holders. reserves on both sides, which determines the pool’s initial A. Major AMM protocols equilibrium state. Notably, the pool permanently anchors the exchange rate This section focuses on the four most representative AMMs: between the two assets to the external data fed by a price Uniswap (including V2 and V3), Balancer V1, Curve, and oracle. Thus, unlike Uniswap, where their reserve quantities DODO. Figure 2 shows an increasing trend over those AMMs. imply asset exchange rates, DODO allows the reserve ratio While Curve only has 17 pools at the moment of writing, between the two assets within a pool to be arbitrary while still Uniswap has over 30,000. DODO is relatively new but already maintaining the asset exchange rate close to the market rate. showcases around 200% growth compared to the start of 2021 Due to this feature, DODO differentiates itself from traditional in terms of volume. AMMs and terms their pricing algorithm as the “Proactive We describe the liquidity pool structures of those protocols Market Making” algorithm, or PMM. in the main text. We also derive the conservation function, Table III: Function comparison table of Uniswap, Balancer, Curve and DODO. Formulas are derived in Appendix A. Conservation functions are visualized in Figure 3, slippage functions in Figure 4 and divergence loss functions in Figure 5.

Uniswap V2 Uniswap V3 Balancer Curve DODO

C ! C !     1 2  P  C2 Conservation function r1 + √ · r2 + √ r  C n r1 − C1 = P · (C2 − r2) · 1 + A· − 1 , r1 ≥ C1 Y wk k  r2 A − 1 A − 1 C = r k n    r1 · r2 k A  − 1 = Q − 1 C A·C ·C  C  r (C −r )· 1+A· 1 −1 1 2 k k  1 1 r Z({r }; C) = 0 = √ k r − C = 1 , r ≤ C k ( A − 1)2 2 2 P 1 1

Spot Exchange rate " #  " !#  n  2 C1 Q C  C2 r r + √ r · w r1· A·r2· rk+C· P 1 + A − 1 , r1 ≥ C1 1 1 A−1 1 2 n  r2 E ({r }; C) k i o k " # ,"  2 !# r C2 r · w  n  C 2 r2 + √ 2 1 r · A·r ·Q r +C· C P 1 + A 1 − 1 , r ≤ C ∂Z({rk}; C)/∂ro A−1 2 1 k n  r 1 1 = k  1 ∂Z({rk}; C)/∂ri 0 Post-swap token1 reserve r1 r1 + x1  C −r0 +P ·C ·(1−2A)+  1 1 2 C C v  n  2  r 1 2 w u 4C C 0 0  h 0 i2 2 1 2   1 u n  1  P  1  P  C1−r +P ·C2·(1−2A) +4A·(1−A)·(P ·C2) C (1− √ ) w u + 1− C−  + 1− C−  1 0 0 A C r1 2 u 0 A A , r ≥ C Post-swap token reserve r − √ 2 r u Q k6=2 k6=2 2P ·(1−A) 1 1 2 2 r0   2   t A· " !# 1 0 C1 A−1 r0  r + √ 1 k6=2  0 C1 1 A−1  (C1−r1)· 1+A· 0 −1 2  r C + 1 , r0 ≤ C 2 P 1 1 0 Swap amount x2 r2 − r2 " #  n x · A·r ·Q r +C· C 1 1 k n k  2·(1−A)·x1 0 Slippage " #  0 − 1, r1 ≥ C1 x1 w1  n  r −C1+C2·P − · r · A·r ·Q r +C· C  1 x1 r1 w2 1 2 k n  r x1 − 1 k  h 0 i2 2 S(x , {r }; C) C w1 − 1 C1−r +P ·C2·(1−2A) +4A·(1−A)·(P ·C2) i k r + √ 1 ! v  n  2 1 r1 1 r1 w2 u 4C C 0 0  x1 0 x /x A−1 1 − u n  1  P  1  P  " !# − 1, r ≤ C i o r0 u + 1− C−  + 1− C−  1 1 = − 1 1 u 0 a a  0 C1 u Q k6=2 k6=2  (r −C1)· 1+A· 0 −1 iEo t a· 1 r k6=2 1 1− √ 2r2  (ρ+1)· A−1 1 Divergence loss  , −1 ≤ ρ ≤ − 1  √ 2+ρ A  √  1+ρ w 1 + ρ  ρ −1 (1 + ρ) 2 L(ρ, {r }; C) − 1 1+ k ρ 2 1 − 1 Complex 0 at equilibrium 1 + 1 , − 1 ≤ ρ ≤ A − 1 0 2  1− √ A 1 + w2 · ρ V (ρ, {r }; C)  A k  √ = − 1  A−1−ρ  , ρ ≥ A − 1 Vheld(ρ; {rk}, C) 2+ρ 2 2 3 3 r 4 r 4

, , w1/w2 e 10000 e 0.5/0.5 v v r 5 r 0.8/0.2 2 2 e 3 e 3 S S s s 1.01 0.2/0.8 , , e e e e r r

g g 2 2 a a 2 2 1 1 p p n n e e p p i i k k l l w1/w2 s s o o

t 1 t 1 0 10000 0 0.5/0.5

s s

' ' 5 0.8/0.2 l l

o o 1.01 0.2/0.8 o 0 o 0 1 1 P 0 1 2 3 4 P 0 1 2 3 4 0 2 0 2 Pool's token 1 reserve, r1 Pool's token 1 reserve, r1 trade size to reserve, x1/r1 trade size to reserve, x1/r1 (a) Uniswap V2 & 3, Equation 19 (b) Balancer, Equation 36 (a) Uniswap V2 & 3, Equation 22 (b) Balancer, Equation 39

2 2 3 3 r 4 r 4

, ,

e 0 e 0.99 v v r 5 r 0.5 2 2 e 3 e 3 S S s s 10000 0.01 , , e e e e r r

g g 2 2 a a 2 2 1 1 p p n n e e p p i i k k l l s s o o

t 1 t 1 0 0 0 0.99

s s

' ' 5 0.5 l l

o o 10000 0.01 o 0 o 0 1 1 P 0 1 2 3 4 P 0 1 2 3 4 0 2 0 2 Pool's token 1 reserve, r1 Pool's token 1 reserve, r1 trade size to reserve, x1/r1 trade size to reserve, x1/r1 (c) Curve, Equation 44 (d) DODO, Equation 50 (c) Curve, Equation 48 (d) DODO, Equation 53 Figure 3: Conservation function of different AMMs Figure 4: Slippage function of different AMMs

4 B. Other AMM protocols formula as Balancer. As the vast majority of bancor pools consist of two assets, one of which is usually BNT, with the 1) Sushiswap: Sushiswap is a of Uniswap, though the reserve weights of 50%–50%, Bancor’s swap mechanism is two mainly differ in governance token structure and user ex- equivalent to Uniswap. Bancor V2.1 now allows single-sided perience. The conservation function, slippage and divergence asset exposure, and provides divergence loss insurance [19] loss are identical to the Uniswap protocol. (see IV-B4c). In August 2020, Sushiswap gained a considerable portion 4) Additional AMM features: of Uniswap’s liquidity by conducting a so-called “vampire a) Time component: A time component refers to the attack”, where Sushiswap users were incentivized to provide ability to change traditionally fixed hyperparameters over time. Uniswap liquidity tokens into the Sushiswap protocol and Balancer V1 and V2 implement this (Table IV), by allowing rewarding them with SUSHI tokens [14]. After Uniswap liquidity pool creators to set a scheme that changes the weights launched UNI and its corresponding liquidity mining program, of two pool assets over time. This implementation is called a Uniswap is back on track with its growth schedule. Neverthe- Liquidity Bootstrapping Pool and is discussed in IV-C. less, as shown in Table II, Sushiswap remains a popular choice b) Dynamic swap fee: Dynamic fees are introduced by for users to deposit their funds. Kyber 3.0 to reduce the impact of divergence loss for LPs. The idea is to increase swap fees in high-volume markets 2) QuickSwap: Previous sections only cover AMMs on and reduce them in low-volume markets. This should result the Ethereum native blockchain, but AMM protocols also in more protection against divergence loss, as during periods gain popularity on Ethereum sidechains. QuickSwap [15] is of sharp token price movements during a high-volume mar- a Uniswap clone that went live in February 2021 on Polygon ket, LPs absorb more fees. In low-volume and low-volatility (previously Matic Network). Polygon [16] is a protocol and markets, trading is encouraged by lowering the fees. framework for building and connecting Ethereum-compatible c) Divergence loss insurance: Popularized by Bancor blockchain networks, called a “Layer 2 aggregator” of multiple V2.1, LPs are insured against impermanent loss after 100 “Layer 2 solutions” such as Optimistic Rollups and zkRollups. days in the pool, with a 30-day cliff at the beginning. Bancor TVL on QuickSwap has reached more than $100M in March achieves this by using an elastic BNT supply that allows 2021, with 24h volumes peaking at $30M decreasing to $10M the protocol to co-invest in pools and pay for the cost of at the beginning of April [17]. impermanent loss with swap fees from its co-investments [20]. 3) Bancor V2.1: While Bancor’s white paper [18] gives the This insurance policy is earned over time, 1% each day that impression that a different conservation function is applied, liquidity is staked in the pool. a closer inspection of their transaction history and smart contract leads to the conclusion that Bancor is using the same 4This has been confirmed by a developer in the Bancor Discord community Table IV: Overview of important existing AMM protocols on Ethereum, Solana, Polkadot, and EOS. CS = Constant-Sum, CP = Constant-Product, OP = Oracle price component, CC = Capital concentration, TD = Time component.

Conservation function AMM add-ons Associated Attacks Protocol Pool CP CS OP CC T Divergence loss Flash loan Vampire Chain Mainnet structure compensation attack attack launch Uniswap V1 [21] asset-pair — [22] — Ethereum 11/2018 [24], [25], Uniswap V2 [23] asset-pair # # # # — — Ethereum 05/2020 [26], [27] Uniswap V3 [28] asset-pair # # # # — — — Ethereum 05/2021 Balancer V1 [3] multi-asset # # # — [29] — Ethereum 03/2020 Balancer V2 [30] multi-asset # # # — — — Ethereum — Curve [10] multi-asset # # # — [24], [26] — Ethereum 01/2020 DODO [7] single-asset # # # — — — Ethereum, BSC 09/2020 Bancor V1 [18] asset-pair # # # — — — Ethereum, EOS 06/2017 Bancor V2 [19] asset-pair # # # # — — — Ethereum, EOS 04/2020 Divergence loss Bancor V2.1 [4] asset-pair # # # — — Ethereum, EOS 10/2020 insurance SushiSwap [14] asset-pair # # # # — [26], [27] [31] Ethereum 08/2020 Mooniswap [32] asset-pair # # # # — — — Ethereum 08/2020 mStable [8] asset-pair # # # — — — Ethereum 07/2020 Dynamic Kyber 3.0 [33] multi-asset # # # # — — Tezos — swap fee StableSwap [34] multi-asset # # # — — — Solana — TrueSwap [35] asset-pair # # # — — — Tron — HydraDX [36] multi-asset # # # # — — — Polkadot — # #

0.0 0.0 risks. Gyro Dollars can be minted for a price near $1 and can be redeemed for an amount worth of near $1 in reserve L L

0.2 0.2 , , s s

s s assets, as determined through a new Automated Market Maker o o l l

0.4 0.4

e e (AMM) design that balances risk in the system. c c n n

e 0.6 e 0.6 Gyroscope includes a Primary-market AMM (P-AMM), g g r r

e e through which Gyro Dollars are minted and redeemed, and a v v

i i w1/w2

d 0.8 d 0.8 10000 0.5/0.5 Secondary-market AMM (S-AMM) for Gyro Dollar trading. 5 0.8/0.2 1.01 0.2/0.8 1.0 1.0 Similar to Uniswap V3, where a price range constraint is 0 2 4 0 2 4 spot price change, spot price change, imposed. The P-AMM yields a mint quote and a redeem quote that serves as a price range constraint for the S-AMM to decide (a) Uniswap V2 & 3, Equation 26 (b) Balancer, Equation 43 upon concentrated liquidity ranges [38]. 0.0 0.0 2) EulerBeats: EulerBeats [39] is a protocol that issues limited edition sets of algorithmically generated art and music, L L

0.2 0.2 , , s s

s s based on the Euler number and Euler totient function. The o o l l

0.4 0.4

e e project uses self-designed bonding curves to calculate burn c c n n

e 0.6 e 0.6 prices of music/art prints, depending on the existing supply. g g r r

e e The project thus implements a form of AMM to mint and burn v v i i

d 0.8 d 0.8 0 0.99 NFTs price-efficiently. 5 0.5 10000 0.01 1.0 1.0 3) Pods Finance: Pods [40] is a decentralized non-custodial 0 2 4 0 2 4 spot price change, spot price change, options protocol that allows users to create calls and or puts and trade them in the Options AMM. Users can participate (c) Curve, Equation 18 (d) DODO, no div. loss as sellers and buy puts and calls in a liquidity pool or act Figure 5: Divergence loss of different AMMs as liquidity providers in such a pool. The specific AMM is one-sided and built to facilitate an initially illiquid options market and price option algorithmically using the Black- C. DeFi protocols with AMM implementations Scholes pricing model. Users can effectively earn fees by AMMs form the basis of other protocols that implement providing liquidity, even if the options are out-of-the-money, existing or invent newly designed bonding curves, facilitating reducing the cost of hedging with options. the functionalities of these implementing protocols. In this 4) Balancer Liquidity Bootstrapping Pool: Liquidity Boot- section, we present few examples of projects that use AMM strapping Pools (LBPs) are pools where controllers can change designs under the hood. the parameters of the pool in controlled ways, unlike im- 1) Gyroscope Protocol: Gyroscope Protocol [37] is a sta- mutable pools described in section Section IV. The idea of blecoin backed by a reserve portfolio that diversifies all DeFi an LBP is to launch a token fairly, by setting up a two-token pool with a project token and a collateral token. The weights Attack 1 Flash-loan-funded price oracle attack are initially set heavily in favour of the project token, then 1: Take a flash loan to borrow xA tokenA from a PLF, gradually ”flip” to favour the collateral coin by the end of whose value is equivalent to xB tokenB at market price. the sale. The sale can be calibrated to keep the price more or 2: Swap xA tokenA for xB − ∆1 tokenB on an AMM, less steady (maximizing revenue) or declining to the desired pushing the new price of tokenA in terms of tokenB down xB −∆2 minimum (e.g., the initial offering price) [41]. to , where ∆2 > ∆1 > 0 due to slippage. xA 5) YieldSpace: The YieldSpace paper [42] introduces an 3: Borrow xA + ∆3 tokenA with xB − ∆1 tokenB as automated liquidity provider for fixed yield tokens. A formula collateral on a PLF that uses the AMM as their sole called the ”constant power sum invariant” incorporates time price oracle. To temporarily satisfy overcollateralization, to maturity as input and ensures that the liquidity provider xB −∆2 < xB −∆1 . xA xA+∆3 offers a constant interest rate—rather than price—for a given 4: Repay the flash loan with xA tokenA. ratio of its reserves. fyTokens are synthetic tokens that are redeemable for a target asset after a fixed maturity date [43]. The price of a fyToken floats freely before maturity, and that deals with strongly unequally divided pool weights, the trade price implies a particular interest rate for borrowing or lending size has a relatively high impact on the slippage compared that asset until the fyToken ’s maturity. Standard AMM to a pool with equal weights, as is shown in Figure 4b. protocols as discussed in Section IV are capital-inefficient. By Conversely, divergence loss is less impactful in that situation introducing the concept of a constant power sum formula, the since arbitrageurs are eating fewer profits from the liquidity writers want to build a liquidity provision formula that works providers. In Curve, the bigger A is, the smaller the price in ”yield space” instead of ”price space”. slippage should be, but the more significant the divergence 6) Notional Finance: Notional Finance [44] is a protocol loss is in case of spot price changes, as shown in Figure 4c that facilitates fixed-rate, fixed-term crypto-asset lending and and Figure 5c. It must be noted that because all assets in a borrowing. Fixed interest rates provide certainty and minimize Curve pool are backed by the same asset, spot price changes risk for market participants, making this an attractive protocol should have a low impact, since all assets in the pool are facing among volatile asset prices and yields in DeFi. Each liquidity that same spot price change. This is why Curve has an inherent pool in Notional refers to a maturity, holding fCash tokens advantage when trading similar assets. From a theoretical point attached to that date. For example, fDai tokens represent a of view, it seems like DODO can offer similar functionalities fixed amount of DAI at a specific future date. The shape of the as Curve, as seen in Figure 3 and Figure 4, but without having Notional AMM follows a logit curve, to prevent high slippage the disadvantage of divergence loss for liquidity providers. in normal trading conditions. Three variables parameterize The one-to-one comparison of these protocols may not make the AMM: the scalar, the anchor, and the liquidity fee [45]. complete sense in some cases, such as when one compares The first and second mentioned allowing for variation in Curve and Uniswap, but it sheds light, nevertheless, on how the steepness of the curve and its position in a xy-plane, much better it is to trade and similarly priced assets respectively. By converting the scalar and liquidity fee to a on Curve. function of time to maturity, fees are not increasingly punitive V. SECURITYANDPRIVACYISSUESWITH AMM when approaching maturity. 7) Gnosis Custom Market Maker: The Gnosis CMM [46] A. AMM-associated attacks allows users to set multiple limit orders at custom price brack- 1) Oracle attack: At the end of 2020, a series of flash loan- ets and passively provide liquidity on the Gnosis Protocol. funded price oracle attacks caused exploits in numerous pro- The mechanism used is similar to the Uniswap V3 structure, tocols. In this kind of attack, adversaries manipulate protocols although it allows for even more possibilities to market makers that use a DEX as their sole price oracle. by allowing them to choose price upper and lower limits and Following Attack algorithm 1, an attacker profits with a number of brackets within that price range. Uniswap V3 ∆3 tokenA less any transaction fees incurred. The attack allows liquidity providers to solely choose the upper and lower temporarily distorts the price of tokenA relative to tokenB. limits. Because users deposit funds to the assets at different After the prices are arbitraged back, the attack would leave price levels specifically, this specific application behaves more the loan taken from step 3 undercollateralized, jeopardizing the like a central limit order book than an AMM pool. safety of lenders’ funds on PLF. Examples of such attacks are exploits on Harvest finance [24], Value DeFi [26] and Cheese D. Discussion bank [25]. If one needs to trade similarly priced assets, then Curve does This broken design can generally be fixed by either provid- that the best. Suppose it concerns an ETF-like portfolio, which ing time-weighted price feeds, or using external decentralized automatically re-balances, Balancer will help. As mentioned oracles. The first solution ensures that a price feed cannot be before, Balancer has the same slippage and divergence loss manipulated within the same block, while the second solution formulas as Uniswap in case of an equal 0.5/0.5 split, while aggregates price data from multiple independent data providers Curve has almost identical formulas in case of A → 0, that add a layer of security behind the aggregation algorithm, as can be seen in Figure 5. On Balancer, when the user makes sure that prices are not easily manipulated. 2) Rug pull: The general idea of a rug pull is to lure find that the attacker will be on most of those buying at least people into buying the coin with no value, subsequently 200-300 ETH worth of the just listed token. swapping this coin for ETH or another cryptocurrency with Normal exchange users could set a low slippage tolerance to value, as shown in Attack algorithm 2. One method is to avoid suffering from a price elevated by front-runners. How- create a coin with the same name as an existing one. This ever, an overly low slippage tolerance may lead a transaction attracts a lot of attention since everyone wants to pick up the to fail, resulting in a waste of gas fee. coin at the lowest price possible. The coin is being bought 4) Backrunning: Backrunners place their trade immediately up, and the original liquidity provider swaps his fake coin after someone else’s trade. The attacker needs to fill up for ETH. There are other ways rug pulls are performed. One the block with a large number of cheap gas transactions of the co-authors of this paper was used as a marketing to definitively follow the target’s transaction. In comparison, pawn in one ploy. The creators of the fake token send it out frontrunning requires a single high valued transaction. Fron- to several prominent people, creating false hype. Potential trunning is detrimental to the user, in contrast, backrunning buyers see that major buyers have purchased the token is detrimental to the network as a whole and so has more and start buying themselves. They very quickly realize that negative externalities.6 the token cannot be swapped back for ether. Sometimes, There are a number of agents in this flow. There needs to the attackers let people trade the coin back for ether, but be a miner and / or the “extractor”. One way to extract the only for a short period since they are running the risk of value is for the miner to amend the order of the transactions losing money. One example of this is the RAM token (address: and place his. For example, a big trade on Uniswap with high 0x90b7a437ddaf1d5686445b928da82d86dd447ec5). slippage will be sniped by placing the transactions around it. The attacker extracted 24 ETH from the rug pull. See detailed example below.

Attack 2 Rug Pull Attack 3 Sandwich price attack 1: Mint a new coin XYZ. 1: UserA wishes to purchase xA XYZ whose spot price is P1 2: Create a liquidity pool with xXYZ XYZ and xETH ETH on an AMM with gas fee g1. (or any other valuable cryptocurrency) on an AMM, and 2: UserB observes the mempool and sees the transaction receive LP tokens. 3: UserB front-runs by buying xB XYZ with a higher gas 3: Attract unwitting traders to buy XYZ with ETH from the fee g2 > g1 on the same AMM . pool, effectively changing the composition of the pool. 4: UserB and UserA’s transactions are executed sequentially 4: Withdraw liquidity from the pool by surrendering LP at respective average price of PB and PA, pushing XYZ’s tokens, and obtain xXYZ − ∆1 XYZ and xETH + ∆2 ETH, spot price up to P2, where P2 > PA > PB > P1 due to where ∆1, ∆2 > 0. slippage. 5: UserB back-runs by selling xB XYZ at an average price 0 0 of PB, with P2 > PB > PB due to slippage. 3) Frontrunning: Frontrunners place their trade immedi- ately before someone else’s trade. These are usually the traders 5) Sandwich attacks: Combing front- and back-running, an that attempt to get the best price of a new coin before anyone adversary of a sandwich attack places his orders immediately else. They then sell these coins onto the market. Almost all before and after the victim’s trade transaction. The attacker Polkastarter IDOs are frontran on Uniswap. Each listing brings uses front-running to cause victim losses, and then uses the attacker at least $1 million in profits. Sometimes, the back-running to pocket benefits. Zhou et al. [1] detail two attackers use Flashbots5 for this. Most of the time, they spam sandwich attacks that can occur on an AMM: one exchange the block in a fashion similar to how backrunners fill the user attacking another, and an LP attacking an exchange user. block. This is done to definitively achieve nonce index that Attack algorithms 3 and 4 describe those two attacks. immediately follows the nonce of the transaction that unpauses 6) Vampire attack: As mentioned in IV-B1, Sushiwap trading on Uniswap. The attacker buys up almost all of the launched in August 2020 as a fork of Uniswap and gained a token supply. Since there is hype, this does not stop retailers lot of traction by allowing users to deposit their Uniswap LP from buying at exorbitant prices. However, now the seller with tokens in Sushiswap in return for rewards, thereby siphoning the most significant supply is the attacker, and he swaps the out liquidity from Uniswap, a sequence later called a “Vampire purchased coin for ether supplied by the retail. These attacks Attack” [47]. are incredibly vicious since they motivate more Polkastarter In a first step of a Vampire attack, a new protocol B incen- IDOs. In a sense, this is value extraction from the Ethereum tives liquidity providers of another platform A to stake their blockchain. LP tokens into protocol B. In case of Sushiswap, Uniswap A simple way to identify these attacks is to observe new LPs were rewarded with SUSHI tokens when they staked their listings on Uniswap and observe the transaction immediately LP tokens into the Sushiswap protocol. In the second stage, following the unpause transaction in the ERC20 coin. You will a migration of liquidity happens from protocol A to protocol

5https://github.com/flashbots/pm 6https://github.com/ethereum/go-ethereum/issues/21350 Attack 4 Sandwich LP attack VI.RELATED WORK 1: UserA wishes to purchase xA tokenA with tokenB using A. Blockchain-based DEXs an AMM pool of r token and r token with gas fee A A B B Our work is first and foremost related to the literature body g . 1 covering blockchain-based DEXs. 2: LP observes the mempool and sees the transaction. B 1) Security: Qin et al. [50] conduct empirical analyses on 3: LP front-runs by withdrawing liquidity k r token and B A A various AMM attacks, including transaction (re)ordering and k r token with a higher gas fee g > g . B B 2 1 front-running, and demonstrate the profitability in performing 4: LP and User ’s transactions are executed sequentially, B A transaction replay through a simple trading bot. Security risk resulting in a new composition of the pool with (1−k)r + A in terms of attack vectors in high-frequency trading on DEXs x token and (1 − k)r − x token . A A B B B are discussed in Zhou et al. [1], and Qin et al. [51]. Flash loan 5: LPB back-runs by re-providing k rA tokenA and k · (1−k)rB −xB attacks with the aid of AMMs on Ethereum are described in tokenB. (1−k)rA+xA Cao et al. [52], Perez et al. [53] and Wang et al. [54]. Victor (1−k)rB −xB 6: LPB back-runs by selling (1 − ) tokenB for (1−k)rA+xA et al. [55] detect self-trading and wash trading activities on some tokenA order-book based DEXs. Gudgeon et al. [56] explore design weaknesses and volatility risks in AMM DEXs. 2) Privacy: Angeris et al. [57] argue that privacy is im- B. By doing this, protocol B now has sucked liquidity from possible with typical constant-function market makers and protocol A and moved it to its own contracts, giving access to propose several mitigating strategies. Stone et al. [58] describe more volume and thus creating a more attractive proposition to a protocol that allows trustless, privacy-preserving cross-chain users. The migration process was executed by a smart contract cryptocurrency transfers but is yet susceptible to vampire that took the Uniswap LP tokens in Sushiswap, converted attacks. those to the represented liquidity on Uniswap, transferred the 3) Protocol mechanism: Angeris et al. [59] discuss arbi- assets to Sushiswap and got Sushiswap LP tokens in return. trage behaviour and price stability in constant product and Effectively, Sushiswap migrated liquidity from Uniswap to constant mean markets. Lo et al. [60] empirically evidence Sushiswap on 9 September 2020 [31], thereby moving $830 that the simplicity of Uniswap ensures the ratio of reserves to million to the new born AMM. Users’ Uniswap LP tokens match the trading pair price. Despite historical oracle attacks got automatically replaced with Sushiswap LP tokens, repre- associated with AMMs (see Section V), Angeris et al. [59], senting the same liquidity. To encourage liquidity providers to [61] show that constant-function-AMM users are incentivized participate in the migration, Sushi continued to reward LPs to correctly report the price of an asset, suggesting the suit- and users that were staking SUSHI. ability for those AMMs to act as a decentralized price oracle for other DeFi protocols. Angeris et al. [13] present a method B. Privacy concerns for constructing constant-function AMM whose portfolio value On AMM DEX, security problems often go hand in hand functions match an arbitrary payoff. with privacy issues. Among the named attacks from the B. DEX and AMM in the context of market microstructure previous section, the sandwich attacks are enabled by the As two core topics of market microstructure [62], decen- transparency and openness of public such as tralized exchange and market-making have been intensively Ethereum, where transactions are observable to everyone. covered in the discipline of financial economics long before Against this backdrop, on-chain privacy-preserving services the emergence of blockchain. and products are on the rise. For example, Blank [48], a 1) DEX: Existing literature primarily suggests the higher non-custodial Ethereum browser extension wallet, offers IP efficiency of DEX markets over centralized ones. protection and transaction obfuscation; Enigma [49] builds a Perraudin et al. [63] investigate decentralized forex markets network of “secret nodes” that can perform computations on and conclude that DEXs are efficient when different market encrypted data without the necessity to expose original raw makers can transact with each other and that decentralized data. markets are more immune to crashes than centralized ones. Nava [64] analyzes quantity competition in the decentralized C. Public information on attacks oligopolistic market and suggest perfect competition can be We have found that the current MEV dashboard7 includes approximated in large rather than small DEX markets. Mala- but a tiny subset of maximum extractable value. Only single mud et al. [65] develops an equilibrium model of general transaction externalities are logged. Our experience showed DEX and prove that decentralized markets can more efficiently that initial coin listings are pulling at least the daily dashboard allocate risks to traders with heterogeneous risk appetites than quoted MEV alone. An exciting avenue would be to explore centralized ones. this area more closely since that would mean highly optimistic 2) AMM: The concept of automated market making can reported DEX volumes. be traced back to Hanson’s logarithmic market scoring rules (LMSR) [66], [67]. LMSR has since been refined and com- 7https://explore.flashbots.net pared to alternative market-making strategies. Othman et al. [68] address non-sensibility to liquidity and APPENDIX non-profitability of LMSR market making. They propose a A. Protocol formulas bounded, liquidity-sensitive AMM that runs with a profit by levying transaction cost to subsidize liquidity, a strategy later 1) Uniswap V2: widely implemented by blockchain-based DEXs with AMM a) Conservation function: The product of reserve quan- protocols to compensate for divergence loss (see II-C3b) expe- tity of token1, r1, and reserve quantity of token2, r2, stays rienced by LPs. Brahma et al. [69] propose a Bayesian market constant with swapping: maker for binary markets which exhibit better convergent C = r1 · r2 (19) behaviour at equilibrium than LMSR. Jumadinova et al. [70] compare LMSR with different AMM b) Spot exchange rate: Given the equal value assumption strategies, including myopically optimizing market-maker, re- encoded in the pool smart contract, the implied spot price of inforcement learning market maker and utility-maximizing assets in a liquidity pool can be derived based on the ratio market maker. Simulating empirical market data, they find that between their reserve quantities. Specifically, denominated in reinforcement learning-based AMM outperforms other strate- token 1, the price of token2 can be expressed as: gies in terms of maintaining low spread while simultaneously r1 obtaining high utilities. Slamka [71] compare LMSR with dy- 1E2 = (20) r2 namic parimutuel market (DPM), dynamic price adjustments (DPA) and an AMM by the Hollywood stock exchange (HSX) c) Swap amount: Based on the Uniswap conservation in the context of prediction markets. They show that LMSR function (Equation 19), the amount of token2 received x2 and DPA generate the highest forecast accuracy and lowest (spent when x2 < 0) given amount of token1 spent x1 losses for market operators. Today, LMSR has become the de (received when x1 < 0) can be calculated following the steps facto AMM for prediction markets [72] and was adopted by described in III-C3: the Ethereum-based betting platform [73]. 0 r = r1 + x1 Wang [72] compares mathematical models for AMMs, 1 C including LMSR, liquidity sensitive LMSR (LS-LMSR) and r0 = 2 r0 common constant-function AMMs, and proposes constant cir- 1 0 cle/ellipse based cost functions for superior computational ef- x2 = r2 − r2 (21) ficiency. Capponi et al. [74] analyze the market microstructure d) Slippage: The slippage that a Uniswap user expe- of constant-product AMMs, and predict that AMMs will be riences when swapping x token with x token can be used more for low-volatility tokens. 1 1 2 2 expressed as: VII.CONCLUSION x1/x2 x1 S(x1) = − 1 = (22) The DeFi ecosystem is a relatively new concept, and inno- 1E2 r1 vations within the space are being developed at an incredible Figure 4a illustrates the relationship between Uniswap slip- speed. AMMs are an incredible innovation sprung up by x1 page and normalized token1 reserve change . the trustless, verifiable and censorship-resistant decentralized r1 e) Divergence loss: Given the equal value assumption Turing complete and global execution machine. As the use of with Uniswap, the reserve value of token 1, V , equals exactly Decentralized Exchanges becomes increasingly crucial in the 1 half of original value of the entire pool V (token being industry of Decentralized Finance, it is essential to understand 1 numeraire):´ how different flavours of those protocols may fit in a general AMM framework and how the significant players differentiate V = V = V = r (23) themselves given that framework. 2 1 2 1 We have systematized the knowledge around Automated Should a liquidity provider have held r1 token1 and r2 Market Makers during this research and applied that expertise token2, then when token2 appreciates by ρ (depreciates when to several exchanges: Uniswap, Balancer, Curve and DODO ρ < 0), the total value of the original reserve composition and made comments on other AMM protocols: Sushiswap, Vheld becomes: QuickSwap, Bancor V2.1 and others. We use state-space rep- resentation to formalize and generalize the AMM algorithms. Vheld = V + V2 · ρ = r1 · (2 + ρ) (24) Existing protocols can be explored more in-depth using this r r framework. Our research summarizes the economics and risks With 1 token1 and 2 token2 locked in a liquidity pool from in AMMs. We find that non-order book DEXs are highly the beginning, their quantity ratio would have been updated susceptible to a plethora of economic risks such as wash through users’ swapping to result in token2’s price change of ρ trading, frontrunning, backrunning, sandwiching, rug pulling. . The equal value assumption still holds, and the updated V 0 Future research into AMM mechanisms can build upon this pool value becomes: systematization of knowledge and establish unique ways for V 0 = V 0 = V 0 = r0 = r · p1 + ρ (25) differentiating and sustaining AMM innovations. 2 1 2 1 1 (1+ρ)r 0 √r2 0 1 Note that r2 = 1+ρ and p = r , which preserves e) Divergence loss: Using the intermediary results from 2 0 0 the invariance of C, and reflects the change in token2’s spot A1e, we can easily derive Vheld, r1 and r2, and subsequently 0 exchange rate against token1. V : As illustrated in Figure 3a, the divergence loss due to liq- Vheld = C1 · (2 + ρ) (31) uidity provision as opposed of holding can thus be expressed √ 1 equivp C1·( 1+ρ− √ ) as a function of price change: r0 = r 1 + ρ − √ C1 = A 1 1 A−1 1− √1 √ A 0 equiv 1 1 V 1 + ρ r C2( √ − √ ) r0 = √2 − √ C2 = 1+ρ A L(ρ) = − 1 = ρ − 1 (26) 2 1+ρ A−1 1− √1 Vheld 1 + 2 A √ 2+ρ 0 C1(2 1+ρ− √ ) 0 0 0 0 C1(1+ρ)r2 A V = V + V = r + = 1 (32) 2) Uniswap V3: 1 2 1 C2 1− √ A a) Conservation function: Suppose a liquidity provider 1 When −1 ≤ ρ ≤ −1, then token1 becomes depleted, and supplies C1 token1 and C2 token2, with the restriction that his A liquidity is only used for a specific range of exchange rates: the liquidity provider is left with token2: C1 C1·A √ [ , ] where A > 1 and the initial exchange rate equals 0 C1(1 + ρ) 0   C2·A C2 C V = · r2 = C1 · (1 + ρ) · A + 1 (33) 1 . The shape of the conservation function is then identical to C2 C2 liquidity provision of the following amounts under Uniswap When ρ ≥ A − 1, then token2 becomes depleted, and the V2: liquidity provider is left with token1: √ equiv C1 equiv C2 0 0   r = and r = V = r1 = C1 · A + 1 (34) 1 1 − √1 2 1 − √1 A A The divergence loss can thus be calculated as: The bonding curve of a Uniswap V3 pool is equivalent to V 0 that of a Uniswap V2 one moving left along the x-axis by L(ρ) = − 1 equiv equiv Vheld √ (r1 − C1) and down along the y-axis by (r2 − C2). Thus,  (ρ+1)· A−1 , −1 ≤ ρ ≤ 1 − 1 Uniswap V3 conservation function can be expressed as:  √ 2+ρ A  1+ρ  ρ −1 1+ equiv equiv equiv equiv = 2 , 1 − 1 ≤ ρ ≤ A − 1 (35) [r1 + (r1 − C1)] · [r2 + (r2 − C2)] = r1 · r2 1− √1 A      √ A C1 C2 A·C1 ·C2  A−1−ρ , ρ ≥ A − 1 r1 + √ · r2 + √ = √ (27) 2+ρ A − 1 A − 1 ( A − 1)2 Note that lim L(A − 1) = 0. √ √ A→1 where 0 ≤ r1 ≤ C1 · ( A + 1) and 0 ≤ r2 ≤ C2 · ( A + 1). 3) Balancer: b) Exchange rate: a) Conservation function: Balancer implements a con- servation function with a weighted-product invariant (Fig- r + √ C1 1 A−1 ure 3b). Specifically, the product of reserve quantities each 1E2 = (28) C2 raised to the power of its weight stays constant with swapping: r2 + √ A−1 Y C = rwk (36) Note that when token is depleted, i.e. r = 0, then k 1 1 k r + √ C2 = √A·C2 b) Spot exchange rate: Given the quantity ratio r1 : r2 2 A−1 A−1 between token1 and 2 and the implicit assumption on their C1 1E2 = C2·A value ratio w1 : w2, the price of token2 denominated by token1 can be expressed as: Similarly, when token2 is depleted, i.e. r2 = 0, then 1E2 = C1 r · w C2·A 1 2 1E2 = (37) c) Swap amount: The swap amount can be derived from r2 · w1 the conservation function Equation 27: c) Swap amount: We investigate the case when a user 0 swaps token1 for token2, while the reserves of all other r1 = r1 + x1 .   assets remain untouched in the pool. Based on the Balancer r0 = C1C2 r0 + √ C1 − √ C2 2 (1− √1 )2 1 conservation function (Equation 36), the amount of token2 A A−1 A−1 0 received x2 (spent when x2 < 0) given amount of token1 x2 = r2 − r2 (29) spent x1 (received when x1 < 0) can be calculated following d) Slippage: The slippage should have the same magni- the steps described in III-C3: tude as in Uniswap V2, but with r amplified by an increase 0 1 r1 = r1 + x1 C1 of √ : w1 A−1   w 0 r1 2 r2 = r2 0 x1/x2 x1 r1 S(x1) = − 1 = (30) C1 0 1E2 r + √ x2 = r2 − r (38) 1 A−1 2 d) Slippage: The slippage that a Balancer user expe- essentially a constant-sum one with constant exchange rate riences when swapping x1 token1 with x2 token2 can be equal to 1 (Figure 3c). expressed as: P  rk  C n x1 w1 k ( n ) · A − 1 = Q − 1 (44) x1/x2 r1 w2 C rk S(x1) = − 1 = w1 − 1 (39) k E   w 1 2 r1 2 1 − r0 1 b) Spot exchange rate: Rearrange Equation 44 and let Figure 4b illustrates the relationship between Uniswap slip- r +r + P r ! x1 C n 1 2 k page and normalized token1 reserve change . ( n ) k6=1,2 r1 Z(r1, r2) = Q − 1 − A − 1 r1r2 rk C e) Divergence loss: Given the constant value ratio as- k6=1,2 sumption with Balancer, the value of the entire pool V can be expressed by the reserve quantity of token 1, r1 divided by its Following III-C, the spot exchange rate can be calculated weight w1 (token1 being numeraire):´ as:   V1 V2 Vk r1 Q C n V = = = = (40) r1· A·r2· rk+C·( n ) ∂Z(r1,r2)/∂r2 k w1 w2 wk w1 1E2 = =   (45) ∂Z(r1,r2)/∂r1 Q C n r2· A·r1· rk+C·( n ) If token2 appreciates by ρ (depreciates when ρ < 0) while k all other tokens’ prices remain unchanged, the total value of the original reserve composition, when held outside of the c) Swap amount: We investigate the case when a user swaps token1 for token2, while the reserves of all other pool, Vheld becomes: assets remain untouched in the pool. Based on the Curve Vheld = V + V2 · ρ = V · (1 + w2 · ρ) (41) conservation function (Equation 44), the amount of token2 received x2 (spent when x2 < 0) given amount of token1 With r1 token1 and r2 token2 locked in a liquidity pool from spent x1 (received when x1 < 0) can be calculated following the beginning, their quantity ratio would have been updated the steps below: through users’ swapping to result in token2’s price change of ρ. The value ratio between the pool, token1 and token2, 0 r = r1 + x1 remains 1 : w : w , and the updated pool value V 0 becomes: 1 1 2 v n " #2 u 4C( C ) 0 0 0 0 w u n + 1− 1 C− P + 1− 1 C− P V r r · (1 + ρ) 2 u 0 ( A ) ( A ) 0 1 1 1 w2 t A· Q k6=2 k6=2 V = = = = V · (1 + ρ) (42) 0 k6=2 w1 w1 w1 r2 = 2 0 The exchange rate range corresponds the liquidity provider’s x2 = r2 − r2 (46) r0 = r2 range requirement. Specifically, when 2 (1+ρ)1−w2 and 0 w2 where rk = rk · (1 + ρ) for k 6= 2, reflecting the assumed scenario that only the value of token2 appreciates by ρ, while the value 0 0 of all other tokens against token1 remains unchanged. Y 0 Y X 0 X = r1 · rk and = r1 + rk (47) As illustrated in Figure 5b, the divergence loss due to k6=2 k6=1,2 k6=2 k6=1,2 liquidity provision as opposed to holding can thus be expressed as a function of price change: d) Slippage: As illustrated in Figure 4c, the slippage that a Curve user experiences when swapping x token with x V 0 (1 + ρ)w2 1 1 2 L(ρ) = − 1 = − 1 (43) token2 can be expressed as: Vheld 1 + w2 · ρ

x1/x2 4) Curve: S(x1) = − 1 (48) 1E2 " # a) Conservation function: As assets from the same pool n x · A·r ·Q r +C· C 1 1 k ( n ) k are connected to the same peg by design, the ideal exchange " # n r · A·r ·Q r +C· C 1 2 k ( n ) rate between them should always equal 1. Theoretically, this k v = u C n  2 − 1 u 4C 0 0 could be achieved by a constant-sum invariant. Nevertheless, u ( n ) 1 P 1 P u +(1− )C−  +(1− )C− u 0 a a Curve seeks to allow an exchange rate to deviate from 1, in t a· Q k6=2 k6=2 1− k6=2 order to reflect the supply-demand dynamic, while simultane- 2r2 ously keeping the slippage low. Curve achieves this by interpolating between two invariants, e) Divergence loss: Curve’s divergence loss in full form constant sum and constant product [10], with hyperparameter cannot be easily presented in a concise and comprehensible A as the interpolating factor (Equation 44).8 When A → 0, the fashion. Therefore, for Curve, we use the generalized method conservation function boils down to a constant-product one, as to calculate its divergence loss as described in III-C. The with Uniswap; when A → +∞, the conservation function is divergence loss in the case of a 2-asset pool is presented in Figure 5c. 8Note that A here is equivalent to A · nn in Curve’s white paper [10]. 5) DODO: a) Spot exchange rate: As presented in the previous sec- d) Slippage: As illustrated in Figure 4d, the slippage that tions, conventional AMMs derive the exchange rate between a DODO user experiences when swapping x1 token1 with x2 two assets in a pool purely from the conservation function. token2 can be expressed as: DODO does it the other way around: resorting to external market data as a major determinant of the exchange rate, S(x ) = (53) DODO has its conservation function derived from its exchange 1  2·(1−A)·x1 0 rate formula. r0 −C +C ·P − − 1, r1 ≥ C1  √ 1 1 2  0 2 2 The exchange rate between the two assets in a DODO pool [C1−r1+P ·C2·(1−2A)] +4A·(1−A)·(P ·C2) x1 0 is set by the market rate with an adjustment based on the     − 1, r1 ≤ C1  0 C1  (r1−C1)· 1+A· 0 −1 pool composition. We denote the market exchange rate as P , r1 namely 1 token2 = P token1, and the initial reserve for token1 e) Divergence loss: DODO eliminates the kind of di- and token2 as C1 and C2 respectively. The formula Equation 49 vergence loss seen in previously discussed protocols by not sets the exchange rate 1E2 higher than the market rate P — forcing liquidity providers to deposit tokens in pre-defined i.e. token2 exhibits higher price in the pool than in the market, ratios. This is achieved by leveraging price oracles, which when the reserve of token1 r1 exceeds its initial state C1, and allow liquidity providers to deposit an arbitrary combination of sets 1E2 lower than P —i.e. token1 more expensive than its base and quote tokens, unlocking single-token exposure. The market value, when r1 falls short of C1. Formally, price oracle is used to protect LPs against heavy arbitrage.    2  C2 EFERENCES P 1 + A − 1 , r1 ≥ C1 R  r2 E = , [1] L. Zhou, K. Qin, C. Ferreira Torres, D. V. Le, A. Gervais, C. F. 1 2   2  (49) C1 Torres, D. V. Le, and A. Gervais, “High-Frequency Trading on P 1 + A − 1 , r1 ≤ C1  r1 Decentralized On-Chain Exchanges,” 9 2020. [Online]. Available: http://arxiv.org/abs/2009.14021 [2] A. Evans, “Liquidity Provider Returns in Geometric Mean Markets,” 6 b) Conservation function: DODO’s conservation func- 2020. [Online]. Available: http://arxiv.org/abs/2006.08806 tion can be derived from its exchange formula Equation 49. [3] F. Martinelli and N. Mushegian, “Balancer: A non-custodial portfolio In particular, the initial state of token1 and token2 reserves, C1 manager, liquidity provider, and price sensor,” 2019. [Online]. Available: https://balancer.finance/whitepaper/ and C2 can be regarded as the two invariants of the conserva- [4] Bancor, “Bancor V2.1 Technical Explainer,” 2020. [Online]. Available: tion function. This aligns with the definition according to our https://drive.google.com/file/d/16EY7FUeS4MXnFjSf-KCgdE-Xyj4re framework (Section III), as C1 and C2 remain constant with 27G/view [5] CryptoLocally, “GIV Balancer Listing and Staking Rewards Updates,” swapping activities, but get updated with liquidity provision 2020. [Online]. Available: https://cryptolocally.medium.com/giv-balan or withdrawal. cer-listing-and-staking-rewards-updates-81ebb5843e58 C [6] L. De Giglio, “Geyser: Staking Rewards For Uniswap Liquidity Z 2 h  2 i r − C = P 1 + A C2  − 1 dδ Providers,” 2021. [Online]. Available: https://medium.com/trips-commu 1 1 δ nity/geyser-staking-rewards-for-uniswap-liquidity-providers-115afc6f r2 h  i 5c07 C2 = P · (C2 − r2) · 1 + A· − 1 , r1 ≥ C1 (50) [7] DODO Team, “DODO – A Next-Generation On-Chain Liquidity r2 Provider Powered by Pro-active Market Maker Algorithm,” 2020.  2  [Online]. Available: https://dodoex.github.io/docs/docs/whitepaper/ C C1  Z 1 1 + A δ − 1 [8] H. Andersson, “mStable — Introducing Constant Sum Bonding r − C = dδ 2 2 P Curves for Tokenised Assets,” 2020. [Online]. Available: https: r1 //medium.com/mstable/introducing-constant-sum-bonding-curves-for-t h  i C1 okenised-assets-6e18879cdc5b (C1 − r1) · 1 + A· r − 1 = 1 , r ≤ C (51) [9] Uniswap, “Flash Swaps,” 2020. [Online]. Available: https://uniswap.or P 1 1 g/docs/v2/core-concepts/flash-swaps/ [10] M. Egorov, “StableSwap-efficient mechanism for liquidity,” In the special case of A = 1, when C1 = P · C2, i.e. 2019. liquidity provided on both assets are of equal value, then [11] D. Senchenko, “Impermanent Losses in Uniswap-Like Markets,” 2020. [Online]. Available: https://dsenchenko.medium.com/impermanent-loss DODO’s conservation function is equivalent to Uniswap, with es-in-uniswap-like-markets-4315359ea9b1 r1 · r2 = C1 · P · C2. This can be observed from Figure 3, [12] Ethereum, “Types,” 2020. [Online]. Available: https://docs.soliditylang. where the DODO’s conservation function curve with A → 1 org/en/latest/types.html [13] G. Angeris, A. Evans, and T. Chitra, “Replicating Market Makers,” 3 appears identical to that of Uniswap. 2021. [Online]. Available: http://arxiv.org/abs/2103.14769 c) Swap amount: The swap amount can be derived [14] Sushiswap, “The SushiSwap Project,” 9 2020. [Online]. Available: https: directly from the DODO conservation function (Equation 50): //sushiswapchef.medium.com/the-sushiswap-project-dd6eb80c6ba2 [15] QuickSwap, “QuickSwap,” 2021. [Online]. Available: https://quickswa 0 p.exchange/#/swap r = r1 + x1 1 [16] Polygon, “Polygon — Ethereum’s Internet of Blockchains,” 2021. 0  √ C1−r1+P ·C2·(1−2A)+ [Online]. Available: https://polygon.technology/  [C −r0 +P ·C ·(1−2A)]2+4A·(1−A)·(P ·C )2  1 1 2 2 , r0 ≥ C [17] QuickSwap, “QuickSwap Info,” 4 2021. [Online]. Available: https: 0 2P ·(1−A) 1 1 //info.quickswap.exchange/home r2 =    0 C1 [18] E. Hertzog, G. G. G. Benartzi, and G. G. G. Benartzi, “Bancor Protocol  (C1−r1)· 1+A· 0 −1  r1 0 Continuous Liquidity for Cryptographic Tokens through their Smart C2 + , r1 ≤ C1 P Contracts,” 2018. [Online]. Available: https://storage.googleapis.com/w 0 x2 = r2 − r2 (52) ebsite-bancor/2018/04/01ba8253-bancor protocol whitepaper en.pdf [19] Bancor, “Announcing Bancor V2,” 4 2020. [Online]. Available: [48] Blank, “Blank features beyond basic privacy (#2): Protecting your IP https://blog.bancor.network/announcing-bancor-v2-2f56b515e9d8 in DeFi,” 2021. [Online]. Available: https://blankwallet.medium.com/b [20] Bancor Network, “FAQs - Bancor Network,” 2021. [Online]. Available: lank-features-beyond-basic-privacy-2-protecting-your-ip-in-defi-11bc https://docs.bancor.network/faqs#how-does-impermanent-loss-insuran 76f2d67b ce-work [49] C. Kisagun, “Preventing DEX Front-running with Enigma,” 2019. [21] H. Adams, “Uniswap Whitepaper (v1),” 2018. [Online]. Available: [Online]. Available: https://blog.enigma.co/preventing-dex-front-runnin https://hackmd.io/C-DvwDSfSxuh-Gd4WKE ig g-with-enigma-df3f0b5b9e78 [22] P. Baker, “DeFi Project bZx Exploited for Second Time in [50] K. Qin, L. Zhou, and A. Gervais, “Quantifying Blockchain Extractable a Week, Loses $630K in Ether,” 2 2020. [Online]. Available: Value: How dark is the forest?” 1 2021. [Online]. Available: https://www.coindesk.com/defi-project-bzx-exploited-for-second-time- http://arxiv.org/abs/2101.05511 in-a-week-loses-630k-in-ether [51] K. Qin, L. Zhou, B. Livshits, and A. Gervais, “Attacking the DeFi [23] H. Adams, N. Zinsmeister, and D. Robinson, “Uniswap v2 Core,” 2020. Ecosystem with Flash Loans for Fun and Profit,” Tech. Rep., 2020. [24] Harvest Finance, “Harvest Flashloan Economic Attack Post-Mortem ,” [Online]. Available: http://arxiv.org/abs/2003.03810 10 2020. [Online]. Available: https://medium.com/harvest-finance/har [52] Y. Cao, C. Zou, and X. Cheng, “Flashot: A Snapshot of Flash vest-flashloan-economic-attack-post-mortem-3cf900d65217 Loan Attack on DeFi Ecosystem,” 1 2021. [Online]. Available: [25] B. Pirus, “Cheese Bank’s multi-million-dollar hack explained by security http://arxiv.org/abs/2102.00626 firm,” 11 2020. [Online]. Available: https://cointelegraph.com/news/che [53] D. Perez, S. M. Werner, J. Xu, and B. Livshits, “Liquidations: DeFi on ese-bank-s-multi-million-dollar-hack-explained-by-security-firm a Knife-edge,” 2020. [26] PeckShield, “Value DeFi Incident: Root Cause Analysis,” 11 2020. [54] D. Wang, S. Wu, Z. Lin, L. Wu, X. Yuan, Y. Zhou, H. Wang, and [Online]. Available: https://peckshield.medium.com/value-defi-incident K. Ren, “Towards understanding flash loan and its applications in defi -root-cause-analysis-fbab71faf373 ecosystem,” 10 2020. [Online]. Available: http://arxiv.org/abs/2010.122 [27] M. Young, “Warp Finance reportedly loses up to $8M in flash loan 52 attack,” 12 2020. [Online]. Available: https://cointelegraph.com/news/w [55] F. Victor and A. M. Weintraud, “Detecting and Quantifying Wash arp-finance-reportedly-loses-up-to-8m-in-flash-loan-attack Trading on Decentralized Cryptocurrency Exchanges,” p. 10, 2 2021. [28] H. Adams, N. Zinsmeister, M. Salem moody, u. River Keefer, and [Online]. Available: http://dx.doi.org/10.1145/3442381.3449824 D. Robinson, “Uniswap v3 Core,” 2021. [56] L. Gudgeon, D. Perez, D. Harz, B. Livshits, and A. Gervais, [29] 1inch Network, “Balancer Pool with STA Deflationary Token Incident,” “The Decentralized Financial Crisis,” in Crypto Valley Conference on 2020. [Online]. Available: https://blog.1inch.io/balancer-hack-2020-a8f Blockchain Technology (CVCBT). IEEE, 6 2020, pp. 1–15. [Online]. 7131c980e Available: https://ieeexplore.ieee.org/document/9150192/ [30] F. Martinelli, “Introducing Balancer V2: Generalized AMMs,” 2 2021. [57] G. Angeris, A. Evans, and T. Chitra, “A Note on Privacy in [Online]. Available: https://medium.com/balancer-protocol/balancer-v2 Constant Function Market Makers,” 3 2021. [Online]. Available: -generalizing-amms-16343c4563ff http://arxiv.org/abs/2103.01193 [31] B. Dale, “SushiSwap Will Withdraw Up to $830M From Uniswap [58] D. Stone, “Trustless, privacy-preserving blockchain bridges,” 2021. Today: Why It Matters for DeFi,” 9 2020. [Online]. Available: https: [Online]. Available: http://arxiv.org/abs/2102.04660 //www.coindesk.com/sushiswap-uniswap-migration-defi-amm-wars [59] G. Angeris, H.-T. Kao, R. Chiang, C. Noyes, and T. Chitra, “An analysis [32] A. Bukov and M. Melnik, “Mooniswap by 1inch.exchange,” 2020. of Uniswap markets,” 2019. [33] Kyber Network, “Kyber 3.0: Architecture Revamp, Dynamic MM, [60] Y. Lo and F. Medda, “Uniswap and the rise of the decentralized and KNC Migration Proposal,” 2021. [Online]. Available: https: exchange,” 11 2020. //blog.kyber.network/kyber-3-0-architecture-revamp-dynamic-mm-an [61] G. Angeris and T. Chitra, “Improved Price Oracles: Constant Function d-knc-migration-proposal-acae41046513 Market Makers,” in Advances in Financial Technologies. New [34] michaelhly, macalinao, and joncinque, “michaelhly/stable-swap- York, NY, USA: ACM, 10 2020, pp. 80–91. [Online]. Available: program: StableSwap program for the Solana blockchain,” 2021. https://dl.acm.org/doi/10.1145/3419614.3423251 [Online]. Available: https://github.com/michaelhly/stable-swap-program [62] M. B. Garman, “Market microstructure,” Journal of Financial [35] TrueSwap, “Introducing Trueswap,” 3 2021. [Online]. Available: https: Economics, vol. 3, no. 3, pp. 257–275, 6 1976. [Online]. Available: //trueswapfinance.medium.com/introducing-trueswap-f3438e32b568 https://linkinghub.elsevier.com/retrieve/pii/0304405X76900064 [36] HydraDX, “Intro — HydraDX Docs,” 2021. [Online]. Available: [63] W. Perraudin and P. Vitale, “Interdealer Trade and Information Flows https://docs.hydradx.io/ in a Decentralized Foreign Exchange Market,” in The Microstructure of [37] Gyroscope Finance, “Gyroscope, the new all-weather stablecoin — Foreign Exchange Markets. University of Chicago Press, 1996, pp. Gyroscope Protocol,” 2021. [Online]. Available: https://gyro.finance/ 73–106. [38] ——, “Gyroscope AMMs - Gyroscope Protocol,” 2021. [Online]. [64] F. Nava, “Efficiency in decentralized oligopolistic markets,” Journal of Available: https://docs.gyro.finance/learn/gyro-amms Economic Theory, vol. 157, pp. 315–348, 5 2015. [Online]. Available: [39] EulerBeats, “EulerBeats — About,” 2021. [Online]. Available: www.sciencedirect.comwww.elsevier.com/locate/jet https://eulerbeats.com/about [65] S. Malamud and M. Rostek, “Decentralized Exchange,” American [40] Pods Finance, “Pods Finance — The easiest way to hedge crypto,” Economic Review, vol. 107, no. 11, pp. 3320–3362, 11 2017. [Online]. 2021. [Online]. Available: https://www.pods.finance/ Available: https://pubs.aeaweb.org/doi/10.1257/aer.20140759http: [41] Balancer, “Liquidity Bootstrapping Pool - Balancer,” 2021. [Online]. //pubs.aeaweb.org/doi/10.1257/aer.20140759 Available: https://docs.balancer.finance/guides/smart-pool-templates-gui [66] R. Hanson, “Combinatorial Information Market Design,” Information /liquidity-bootstrapping-pool Systems Frontiers, vol. 5, no. 1, pp. 107–119, 2003. [Online]. Available: [42] A. Niemerg, D. Robinson, and L. Livnev, “YieldSpace: An Automated http://hanson.gmu.edu Liquidity Provider for Fixed Yield Tokens,” 2020. [Online]. Available: [67] ——, “Logarithmic Markets Scoring Rules for Modular Combinatorial https://yield.is/Yield.pdf Information Aggregation,” The Journal of Prediction Markets, vol. 1, [43] D. Robinson and A. Niemerg, “The Yield Protocol: On-Chain Lending no. 1, pp. 3–15, 12 2012. [Online]. Available: http://www.bjll.org/ind With Interest Rate Discovery,” Tech. Rep., 2020. ex.php/jpm/article/view/417 [44] Notional Finance, “Notional Finance,” 2021. [Online]. Available: [68] A. Othman, D. M. Pennock, D. M. Reeves, and T. Sandholm, https://notional.finance/ “A Practical Liquidity-Sensitive Automated Market Maker,” ACM [45] ——, “Notional AMM,” 2020. [Online]. Available: https://docs.notiona Transactions on Economics and Computation, vol. 1, no. 3, pp. 1–25, l.finance/traders/technical-topics/notional-amm 9 2013. [Online]. Available: https://dl.acm.org/doi/10.1145/2509413.2 [46] Gnosis, “Custom Market Maker · Gnosis Developer Portal Gnosis 509414 Protocol,” 2020. [Online]. Available: https://docs.gnosis.io/protocol/do [69] A. Brahma, M. Chakraborty, S. Das, A. Lavoie, and M. Magdon-Ismail, cs/intro-cmm/ “A bayesian market maker,” in Proceedings of the ACM Conference [47] jakub, “What is a Vampire Attack? SushiSwap Saga Explained,” 2020. on Electronic Commerce. New York, New York, USA: ACM Press, [Online]. Available: https://finematics.com/vampire-attack-sushiswap-e 2012, p. 215. [Online]. Available: http://dl.acm.org/citation.cfm?doid= xplained/ 2229012.2229031 [70] J. Jumadinova and P. Dasgupta, “A Comparison of Different Automated Market-Maker Strategies,” 2012, pp. 2009–2012. [Online]. Available: http://www.cs.allegheny.edu/∼jjumadinova/market-maker AMEC.pdf [71] C. Slamka, B. Skiera, and M. Spann, “ Performance and Market Liquidity: A Comparison of Automated Market Makers,” IEEE Transactions on Engineering Management, vol. 60, no. 1, pp. 169–185, 2 2013. [Online]. Available: http://ieeexplore.ieee.org/docu ment/6189381/ [72] Y. Wang, “Automated market makers for decentralized finance (DeFi),” 9 2020. [Online]. Available: http://arxiv.org/abs/2009.01676 [73] J. Peterson and J. Krug, “Augur: a decentralized, open-source platform for prediction markets,” 2015. [74] A. Capponi and R. JIA, “The Adoption of Blockchain-based Decentralized Exchanges: A Market Microstructure Analysis of the Automated Market Maker,” 2021. [Online]. Available: https: //ssrn.com/abstract=3805095