- Published on
Exploring AMMs
- Authors
- Name
- Infect3d
- @InfectedCrypto
This blog post is heavily inspired by this research paper and primarily summarizes its content. Minor modifications and additions have been made to improve its accessibility.
Table of Content
- Introduction
- Fundamental AMM Economics
- Formalization of mechanisms
- Generalized Formulas
- Comparison of AMM protocols
- AMM Security Considerations
Introduction
AMMs stand for Automated Market Makers and are an underlying brick of Decentralized Exchanges (DEXs).
They revolutionized the way people trade assets by employing a peer-to-pool method that determines prices algorithmically rather than matching buy and sell sides through a traditional order book. This makes AMMs easily decentralized, automated, and continuously running.
Besides those qualities, AMMs have some drawbacks: possible high slippage for traders, and impermanent loss for liquidity providers.
Slippage is defined as the difference between the spot price and the realized price of a trade. The larger the quantity of assets withdrawn from the pool relative to its available liquidity, the greater the slippage.
Impermanent loss is defined as the difference in value of the assets in the pool compared to their value if they were held outside of the pool. This comes from the fact that the pool constantly rebalances the quantity of its assets to keep the value of each one equivalent. If asset A depreciates relative to asset B, the pool will "automatically" increase the amount of A while decreasing the amount of B until their values are matched.
These drawbacks come from the nature of the implemented algorithm of AMMs: price moves along predefined trajectories conditioned by the number of assets in the pool.
Uniswap, which is the most used AMM, introduced the constant product formula as the foundation of the protocol: the pool, composed of two distinct assets A and B, is initialized with a quantity and of tokens, such that is equal to the price relation A/B. Then, every action in the pool must always satisfy a set of conservation function invariants. The simplest and most renowned is the Uniswap constant-product formula , where and equal and .
Fundamental AMM Economics
Actors
4 key participants interact within the AMM ecosystem:
- Liquidity Providers (LPs): Provide liquidity to a pool, allowing other users to trade. They receive shares representing the value of their deposit, which they can surrender to get back the equivalent amount of liquidity at the time of the action.
- Traders: these users trade with the pools, and pay fees that are directed to LPs and the protocol.
- Arbitrageurs: Compare price assets over different platforms (DEX, CEX, and others) to find profit opportunities through price discrepancy. This mechanism ensures consistency of asset prices.
- Protocol/Governance: Usually paid through the fees, and thus is financially incentivized to provide the best experience to each party.
Assets
We can also find 4 types of assets:
- Risk assets: Primary types of assets; these are the assets that the AMM provides liquidity for traders, thanks to liquidity providers.
- Base assets: Rarely seen nowadays, but some protocols had pools of Risk/Base assets.
E.g., every Uniswap V1 pool had as a base asset ETH, Bancor had its own token BNC as base asset. But nowadays, many AMMs still follow a similar pattern, with pools having either a stablecoin (USDC/USDT/DAI) or ETH/WETH as one side of the pool. - LP shares: Minted to liquidity providers when depositing into a pool. Shares represent the ownership of a portion of the pool.
- Protocol tokens: Usually distributed as rewards to incentivize users to perform certain actions benefiting the protocol. Sometimes serve as a governance token, or gives advantages to holders. Most can be openly tradeable.
Rewards
AMMs often use those rewards as incentives to encourage participation and contribution:
- Liquidity rewards: These come from trading fees and are distributed to liquidity providers. They are a way to compensate for the immobilization of assets.
- Governance right: Protocol tokens are often distributed to incentivize actions in the protocol (e.g. trading, liquidity provisioning, staking)
- Staking rewards: Staking protocol tokens to receive another reward (e.g. lesser fees for traders, more fees for LPs)
Explicit costs
Interacting with AMMs incurs various costs, either as a way to generate revenue, or to incentivize specific behaviors:
- Swap fees: Charged to traders interacting with liquidity pools to compensate liquidity providers for supplying assets. A small portion of the fees can also be charged as protocol revenue.
- Liquidity withdrawal penalty: AMMs wants to incentivize long-term and balanced liquidity, for that reason, penalties in the form of reduced rewards, or even fees can be applied.
- Gas fees: Inherent to the chain on which the protocol is hosted.
Implicit costs
These costs are considered implicit as they emerge from the design itself rather than being purposefully implemented.
- Slippage: Difference between realized price on swap execution and expected price. Emerge from the non linearity of conservation function invariants. Constant-sum AMM do not suffer slippage.
- Impermanent loss: Difference between value of assets when held outside and inside of the pool. Also emerge from the conservation function invariants, automatically rebalancing assets to keep their relative value to each others.
Formalization of mechanisms
Blockchains are usually modeled as state transition systems. In this representation, a pool has a state that can be described by the following parameters:
- : the quantity (reserve) of token , for , where each represents a different token
- : the price of token
- : conservation function invariants. Mathematical rule that governs how trades can occur, such as Uniswap's famous constant product formula.
- : a set of protocol hyperparameters (e.g., buy/sell fees)
Some protocols will implement the same or for every pool (e.g Uniswap V2), while others will allow more granularity in the configuration of the pools (Uniswap V3/4, Curve, Balancer, …)
While and changes with almost every actions in a pool (swap, liquidity provision), is usually fixed at pool creation, and by definition is to remain constant over the life of the pool (even though trading fees can change it)
We can still get these general rules from AMMs:
- The price of token stays constant for pure liquidity provision/withdrawal
- The invariants stays constant for pure swapping activities
Pure means that we are not factoring in fees, as they imply an additional operation:
- First a swap - given amount , we calculate an amount that must be returned while preserving the pool invariant.
- Then fees - which are deducted from , the trader receiving , while remains in the pool. While the first action do preserves the invariant equality, the second do not.
Finally, the price of a token can only stay constant when assets are deposited proportionate to the current reserve ratio (), as the price is directly derived from these parameters.
Generalized Formulas
Swap
A swap of tokens for tokens in a pool with a reserve of tokens can be decomposed as the following steps:
- The pool receives and update the reserve quantities:
- Using the conservation function invariants compute the new reserve
- Send to the user the difference:
Slippage
Slippage measure the deviation between the realized price and the spot price before the swap occurred
Impermanent loss
Impermanent loss measure the difference in value of the assets in the pool compared to their value if they were held outside of the pool.
Where are the amount of assets deposited at deposit time, and the amount of assets in the pool at measurement time
Comparison of AMM protocols
Uniswap V2
- Liquidity pools are always composed of exactly two assets
- Protocol assumes that the reserves of the two assets always have the same value:
- Conservation function invariants:
- This invariant function is only verified for pure swap, the deduction of fees changes this invariant, which become:
Uniswap V3
- Uniswap V3 enhances V2 by allowing the liquidity provision to be concentrated on a fraction of the bonding curve, between two chosen prices (also called ticks). This means that every segment of the bonding curve have its own .
- Increasing the liquidity on a specific segment of the curve (price range) allows to reduce the slippage on that range.
- The conservation function invariant for the entire bonding curve is merely complex.
- But if we look at C for the active tick range, its the same as Uniswap V2.
- For all other tick ranges, liquidity is one-sided (only one asset available)
Uniswap V4
- Uniswap V4 AMM is inherited from Uniswap V3 and is equivalent.
- But a new concept has been added: Hooks.
- Hooks are functions that can be called before and after specific actions: liquidity update, swap, and more.
- Hooks can overwrite the entire logic of the AMM, allowing custom invariants to be implemented by the developers.
Balancer
- Balancer allow each pool to have more than two assets. Each asset reserve is assigned with a weight at pool creation where
- Weights is an hyperparameter that do not change with swap/deposits, they represent the percentage of value that the reserve of that asset must maintain in the pool.
- Balancer propose different kind of pools
- One of these called the Liquidity Bootstraping Pool allow to configure changing weights over time
- Uniswap is a special case of this with
- Conservation function invariants:
Curve
- In Curve, liquidity pools support two ore more assets with a similar peg
- Similarly to Balancer, Curve propose different type of pools, which is controlled with an hyperparameter called the Amplification Coefficient , basically defining if the if the bonding curve will behave like a constant-product or constant-sum.
- When the constant-sum term disappear compared to the constant-product term
- When the constant-sum take over the formula.
- Conservation function invariants:
AMM Security Considerations
This chapter from the research paper explores different exploit situations but is far from exhaustive. If you want to go further in AMM vulnerabilities, I suggest you this great good article.
Flashloan funded attacks
The example below differs from the original as there was a mistake in step 2 regarding the new price
In a pool composed of 2 tokens, and with reserves and
- Borrow from a CDP protocol of such as (where is the token price in numéraire, or dollars for simplicity) at market price.
- Swap of for of in the AMM.
- this will push the price ( in term of ) lower, to
- Borrow, from another CDP protocol using the AMM as sole price oracle, of with of obtained in step (2)
- Because has been pushed down, now is worth less, making it possible to borrow more than in step (1)
- Repay the flash loan with of
- The profit is equal to (minus fees)
This type of attack can be solved using a TWAP or a decentralized network of oracles (e.g., Chainlink, Pyth)
Rug pull
- Mint a new token XYZ
- Create a pool with XYZ and ETH (could be another one)
- There's now a pool with reserves
- Receiving LP tokens for the deposited liquidity
- Attract people into buying the XYZ token
- This will change the pool reserve to
- Where and
- So there will be less XYZ in the pool, and more ETH as people buy XYZ
- Withdraw liquidity by surrending LP tokens and receiving:
- and
- where
- Swap the remaining XYZ tokens for more ETH
AMMs and launchpad protocols can mitigate this by forcing a period during which liquidity is locked and cannot be withdrawn
Price Sandwich Attack
- User A wishes to purchase XYZ whose spot price is on an AMM with gas fee
- User B sees the transaction in the mempool and front-runs by buying XYZ with a higher gas fee
- User B and A's transactions are executed sequentially at a respective average price of and , pushing XYZ's spot price to where due to slippage
- User B back-run by selling XYZ at an average price of where because of slippage
- User B made a profit of , minus fees
There are multiple way to mitigate this type of attack:
- allow user A to set a slippage parameter, although this will only reduce the harm, but the maximum loss will be configurable
- Some protocols, like CoW Swap create alternative mempools incentivizing block builders to redistribute most of the slippage to the trader
- Some L2s have private mempools, making this attack near to impossible
Sandwich LP attack
- User want to buy of with of in an AMM pool containing and tokens
- LP sees the User's transaction and front-run it by withdrawing and tokens with
- the pool has less liquidity than before, increasing effects of slippage
- the reserves are and
- User's transaction is then executed with a worse execution price than expected
- the pool reserves are now and
- LP back-run and re-provide liquidity to the pool:
- for he provides
- for he provides , which is computed from the new AMM price
- LP still has of and swap this for some , securing a profit
Thank you for reading this blog post.
If you liked this article, you'll probably want to check the original paper available at the top which provides a lot more details about the equations