Author: Leo Liu, Guangwu Xie
Translated by: Vanessa Cao
Proofreading: Leo Liu, Guangwu Xie
Typesetting: Jane Hu
Thanks to: Fangyuan Zhao, Showen Peng, DW, Lianxuan Li, Dave White, Dan Robinson, Vanessa Cao, Jane Hu
This article is published by Interstellar Agents and Dachale Research strategic partner BTXCapital exclusively authorized by Interstellar Agents. In this article, we will first review the four automated market maker (AMM) algorithms implemented by Bancor, Uniswap, Balancer and Curve protocols. The latest developments, possible improvements and future of AMM algorithms will also be discussed.
Table of contents
Table of contents
UniswapCalculation of impermanence loss for
Positive return when the price change is between 2ρ
liquidity distribution, liquidity injection,Uniswap V3range order
BalancerThe market making function and trading formula of
Smart Order Routing (SOR) Algorithm
......
Bancor Networks bonding curve concept and transaction formula:
Bancor¹ utilizes the concept of bonding curves to determine prices. The bonding curve is the relationship between the price of a token and its total supply.
Bancor¹
Bancor Protocol Continuous Liquidity for Cryptographic Tokens through their Smart Contracts
https://storage.googleapis.com/website-bancor/2018/04/01ba8253-bancor_protocol_whitepaper_en.pdf
Bonding Curve:
The bonding curve model can be understood as describing the functional relationship between the token buying and selling price and the total amount of token issuance, which can be automatically executed by smart contracts in a decentralized manner.
https://medium.com/linum-labs/intro-to-bonding-curves-and-shapes-bf326bc4e11a
The invariant chosen by Bancor Network is F, called the connection weight. In the first expression, R refers to the number of reserve tokens in the liquidity pool, S is the total supply of BNT outside the liquidity pool, and P is the relative price of BNT and reserve tokens. We can substitute in the equation for P and integrate ² on both sides to get the relationship between P and S. This is an exponential expression where the exponent α is related to the connection weight F (F is between 0 and 1). The smaller F, the larger α, which means that the price changes faster relative to the total supply of BNT.
Integral on both sides²
Formulas for Bancor system
https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view?resourcekey=0-mbIgrdd0B9H8dPNRaeB_TA
Using this expression and a simple integral, we can derive the relationship between T (BNT tokens purchased) and E (reserve tokens paid for), where R0, S0 are the current values of R and S.
If we want to swap between Token A and Token B, we sell Token A to Token B. We first need to buy BNT tokens from pool A using token A (note: if we dont have BNT tokens). Next, we need to buy Token B from Pool B using BNT. Below is the exact formula needed to calculate how many tokens we will receive. The relative price between token A and token B can be represented by the relative price between BNT token and token A/B.
Advantages: Bancor allows unilateral liquidity injection in certain pools, which is determined by Bancor governance. There is a limit to how much unilateral liquidity can be deposited, which is also determined by Bancor governance. Within the limit, when users deposit unilateral liquidity in the form of other tokens, Bancor will replenish the equivalent BNT tokens. This doubles the effective liquidity provided by users. If the limit is reached, if people want to deposit unilateral liquidity, they have to wait for someone to withdraw unilateral liquidity, or someone to inject BNT as unilateral liquidity.
The Bancor protocol compensates users for impermanent losses when depositing unilateral liquidity with the service fees earned by BNT (to be discussed later). If transaction fees do not fully compensate impermanence loss, Bancor will mint BNT to ensure impermanence loss is zero. Therefore, liquidity providers can enjoy stable income if they deposit liquidity for a certain period of time (full compensation for deposits of 100 days).
Cons: As mentioned above, all transactions require the BNT token as an intermediary. Therefore, we will experience slippage twice. For the same reason, all liquidity pools consist of BNT and another token, thus lacking diversity. The BNT token price may also be affected due to the need for elastic supply to enable impermanent loss compensation and unilateral liquidity deposits.
Bancor introduces the concept of a connected token BNT, which is connected to all tokens with different connection weights, corresponding to different bonding curves that determine prices.
Uniswaps impermanent loss calculation:
Uniswap uses constant product market makers (CPMMs) to determine prices. Before we delve into the algorithm used by Uniswap V2 and V3, lets understand what impermanence loss (IL) is and how to calculate it.
Constant Product Market Maker (CPMM)
Constant Product Market Maker
impermanent loss
https://ethresear.ch/t/improving-front-running-resistance-of-x-y-k-market-makers/1281
impermanent loss
Impermanent Loss
It refers to the loss faced by funds in the liquidity pool.
https://finematics.com/impermanent-loss-explained/
If the AMM function is convex (note: price increases as we buy / price decreases as we sell), then a single trade without transaction fee compensation will always cause the liquidity provider to lose money. Suppose a transaction causes the AMM function to move from point 1 to point 2. The spot prices (absolute value of the derivative of the function) at points 1 and 2 are P1 and P2. P3 is the actual transaction price. Due to the nature of convex functions, P1 > P3 > P2. The impermanent loss is defined as the difference between the current value of the liquidity providers tokens in the pool after the transaction and the current value of the liquidity providers tokens, if he just holds his tokens and does not use them for liquidity provided, it is denoted as V and Vheld. For convenience, the impermanent loss and price will be expressed in token Y (the price of 1 token Y is unit 1). After some simple derivations, it is easy to prove that the impermanent loss is always less than zero (x2 > x1, P2< P3)。
Uniswap³ V2 uses a simple but powerful formula to determine trades. The product of the number of pool token reserves is a constant. Compared to Bancor, it gets rid of the dependency of connected tokens. Trading is entirely determined by the amount of tokens in the liquidity pool.
Uniswap³
Uniswap V2 Core
https://uniswap.org/whitepaper.pdf
Due to the nature of this function, the value of the two tokens in the pool will always be the same (the prices we use in this article will always be relative prices).
Using the same logic, it is not difficult to calculate the impermanent loss of a single transaction without transaction fee in Uniswap V2. Suppose a transaction changes the price from P to Pk. The impermanent loss, measured as a percentage, can be expressed as a function of k alone.
Not surprisingly, this function is always less than or equal to zero, as we can see from the above graph of impermanent loss without fees. If the horizontal axis is plotted in logarithmic space, IL(k) will be symmetric. The conclusion is: the greater the relative price change, the greater the impermanence loss. This can be explained by liquidity providers’ more valuable tokens being bought out of the pool, leaving them with more less valuable tokens.
Positive return when the price change is between 2ρ:
Next, lets see how IL(k) behaves if we add transaction fees:
The derived impermanent loss function IL(k, ρ) looks very similar to the feeless impermanent loss function. We can do a plausibility check by setting ρ to zero, yielding the same result. A typical Uniswap V2 fee percentage is ρ = 0.3%. When plotting the impermanent loss function, we can see that there is a section above zero between approximately k = 0.994 and 1 (approximately 2ρ span). In this region, impermanent losses are positive, meaning that liquidity providers actually gain value (earning transaction fees outperforms losses in this region). By introducing transaction fees, liquidity providers will earn positive returns when prices fluctuate within a certain range.
Liquidity providers always seem to lose money when price movements are more volatile. However, this is not the case in reality. We know that Dave White4 (Note: Paradim venture capital fund researcher) and others have solved this problem. Unfortunately, it is beyond the scope of this introductory paper. We intend to investigate this issue further in the future.
Dave White4
Uniswap’s Financial Alchemy
https://research.paradigm.xyz/uniswaps-alchemy
As for the derivation of impermanent loss for other popular AMM algorithms (including Uniswap V3), we refer readers to this paper by Jiahua Xu⁵ et al. These derivations will be the subject of next time.
Jiahua Xu⁵
SoK: Decentralized Exchanges (DEX) with Automated Market Maker (AMM) protocols
https://arxiv.org/abs/2103.12732
Pros: The first to use a convex function of the number of tokens in the pool to determine the price.
Cons: Liquidity supply is evenly distributed across all price ranges, meaning less capital efficient.
Liquidity Distribution, Liquidity Injection, Uniswap V3 Range Orders:
To improve liquidity utility and reduce the risk of impermanent losses, Uniswap⁶ V3 allows users to provide liquidity only within a specific price range.
Uniswap⁶
Uniswap V3 Core
https://uniswap.org/whitepaper-v3.pdf
From Uniswap V3 whitepaper
This is achieved by translating the Uniswap V2 function:
From Uniswap V3 whitepaper
Translating the function down the y value of point a and to the left the x value of point b as shown in the diagram and equation above ensures a valid trade outcome between a and b as we use the green curve for our price decisions function. When the price falls outside this range, one of the token reserves will be sold out, effectively pooling liquidity into this price range.
Dan Robinson⁷ (Note: Paradim Venture Capital Fund Research Director) published an excellent paper on calculating the liquidity distribution of multiple AMMs.
Dan Robinson⁷
Uniswap V3: The Universal AMM
https://www.paradigm.xyz/2021/06/uniswap-v3-the-universal-amm/
It can also be simply proved that the liquidity of two liquidity providers in the same price range can be simply added together.
When depositing liquidity, as shown above, the value of each asset in Uniswap V3 is not necessarily equal. The value of each asset is equal only when P is equal to the geometric mean of Pa and Pb. Asset X is worth more than asset Y when P is less than the geometric mean. Asset X is worth less than asset Y when P is greater than the geometric mean.
When the current price completely exceeds the price range set by the liquidity provider, Uniswap V3 counts the input of the liquidity provider as a range order (Range Order), and only allows it to deposit one token (the type depends on whether the price range is completely above or below the current price). For example, consider a liquidity pool composed of ETH and Dai. Users are only allowed to deposit ETH if the set price range is well above the current price of ETH. Users will only be allowed to deposit Dai if the price range is well below the current price of ETH. When the price completely crosses the price range set by the liquidity provider, all the assets he deposits will be converted into another token. Since users can only deposit one token, range orders can only fulfill 2/4 of the orders (take profit orders, buy limit orders) of traditional limit orders. On the other hand, buy stop orders and stop loss orders cannot be fulfilled. As of now, we dont know what the purpose of the scoped order token type is.
range order
Range Orders
In essence, it is not a real order, but the aggregate liquidity provided by LP to a certain price point of the fund pool. Although not a real order, the characteristics exhibited by the range order are a good simulation of the basic functions of a limit order.
https://docs.uniswap.org/protocol/concepts/V3-overview/range-orders
Pros: Uniswap V3 introduces the concept of liquidity distribution, allowing its users to deposit liquidity across price ranges. Improve capital efficiency by pooling liquidity. Gain higher liquidity and lower slippage when depositing assets of the same value. Providing liquidity within a certain price range also somewhat reduces the risk of impermanent losses.
Cons: Users can only deposit certain types of tokens when placing range orders. Therefore buy stop orders and stop loss orders cannot be implemented.
Uniswap V2 and V3 introduced CPMM and liquidity distribution in their AMM algorithm. Providing liquidity across price ranges essentially makes Uniswap V3 a universal AMM, capable of becoming any possible AMM by changing its liquidity distribution.
Balancers market making function and trading formula:
Balancer⁸ extends Uniswap V2s dual-token pool to a multi-token pool. The value of each asset in the Balancer pool holds a constant weight that adds up to 1. It is not difficult to prove that this is equivalent to the power product of the reserve quantity of each asset is a constant. The price of asset n relative to asset t can also be derived as the ratio between the reserve quantities of assets t and n, normalized by their weights.
Balancer⁸
A non-custodial portfolio manager, liquidity provider, and price sensor
https://balancer.fi/whitepaper.pdf
Based on the constant invariant, we can derive the transaction formula (transaction between asset o and asset i) with different input values. In this notational standard, asset o is always the asset bought. Asset i is the asset sold. A and B are tokens credited/received and current token reserve amount. We can also calculate the incoming tokens or the number of tokens bought based on the price change.
Smart Order Routing (SOR) Algorithm:
Balancer also introduces the Smart Order Routing (SOR⁹) algorithm.
SOR⁹
Smart Order Router V2
https://docs.balancer.fi/developers/smart-order-router
Source: https://docs.balancer.fi/v/v1/smart-contracts/sor/
The general idea of the algorithm is to divide an order into several small blocks and trade in different Balancer pools to obtain better trading results. Suppose we want to trade in token pool 1 and token pool 2, if the total amount N we want to trade is lower than A in the above figure, we will only trade in token pool 1, because the price of token pool 1 Always better than token pool 2 price. If the total amount exceeds A, we trade part of the order in token pool 1 and part in token pool 2. The amount traded in each token pool will equalize the price in each pool (B + C = N).
It is easy to prove that the optimal strategy is always the one that makes the prices equal in each pool (if the prices are not equal, we can always find a pool with a better price to improve our trading results).
The price function, relative to the volume, is usually a non-linear function. Balancer simplifies the price function to a linear function. If there are n token pools, the optimal strategy can be expressed as:
If there is a remaining price function that is always larger or smaller than the range (0, N), then that price function and the corresponding pool should be removed from the above calculations to ensure valid results. If the price function is always smaller, then the obvious best strategy would be to swap all tokens in that pool.
Gas costs are not considered in this calculation. In fact, the optimal strategy should be to maintain a balance between routing gains and gas cost losses.
The SOR algorithm, we believe, can be used in a wider context. For example, the price function could be a function of a pool of other AMM protocols. Due to the limitations of our current knowledge, we are not sure whether actual AMM aggregators use the same logic to achieve better prices. A more general solution without any price function approximation will be discussed later in this paper.
Pros: Balancer promotes 2 token pools to multiple token pools and introduces SOR algorithm to achieve better prices for its users.
Cons: A liquidity pool is only as strong as its weakest asset. The more token types in a pool, the higher the risk.
Balancer is a multi-token portfolio management tool that allows flexible token value allocation, featuring a price optimization algorithm.
Due to the length of this paper, the discussion and subsequent content of Curve will be published in the second and second parts.