A Comprehensive Deep Dive to AMMs

81Fe...wDFZ
30 Dec 2023
68

This exhaustive Medium post delves into the intricacies of an Automated Market Maker (AMM) pool created with the constant product formula. In our deep dive, we’ll unravel a series of critical aspects, addressing a variety of questions that hold significant relevance to understanding AMMs, their design, and their functionality in the ever-evolving landscape of digital asset exchange. We will address:

  1. The necessity of AMMs
  2. What we expect from AMMs
  3. The formula used to determine the price and the rationale behind it
  4. How to ensure price consistency
  5. What is slippage and why does it exist
  6. How to improve the efficiency of an AMM
  7. The role of liquidity providers and the nature of LP tokens
  8. The concept of impermanent loss


Automated market makers (AMMs) were developed to enable trades to occur anytime we desire. In traditional exchange setups, purchasing asset A with asset B requires finding a trader who wants to exchange asset B for asset A at a mutually agreeable price. However, smart contracts have paved the way for a system that permits trades without the need for a counterparty.

The core idea revolves around creating a pool containing both assets A and B. Whenever we want to buy asset A in exchange for asset B, the system executes the transaction using a predetermined formula. But how do we settle on the right formula? This formula must adhere to certain rules. For instance, the quantity of assets A and B in the pool should be inversely proportional, implying that purchasing asset A necessitates a corresponding increase in asset B. Additionally, the price and quantity of an asset must be inversely proportional, signifying that if the quantity of an asset diminishes, its value increases. Let’s examine some possible formulas.

Formula 1: X — Y = K

Here, X denotes the quantity of asset A in the pool, Y denotes the quantity of asset B in the pool, and K is a constant derived from these quantities. The system enables trades through the pool while keeping K constant. For example, if Alice wishes to buy ‘p’ units of asset A from the pool, the quantity of asset B she has to give, ‘q’, is calculated using the equation (X — p) — (Y + q) = K. This equation implies that q=-p, which is nonsensical because if q is negative, once Alice buys ‘p’ units of asset A from the pool, she would also receive ‘p’ units of asset B from the pool. Thus, we should certainly avoid this formula!

Formula 2: X + Y = K

As before, X and Y represent the quantities of assets A and B in the pool, respectively, while K is a constant. The system’s primary objective is to maintain as constant while X and Y fluctuate. For example, if Alice wants to buy ‘p’ units of asset A from the pool, the quantity of asset B she has to give, ‘q’, is calculated using the equation (X — p) + (Y + q) = K. As we can easily see, q has to equal p to maintain the constant K. Let’s say Alice wants to buy 1 ETH from our pool which contains 10 ETH and 10,000 DAI. Since K=10+10,000=10,010=(10–1)+(10,000+q), the amount of DAI she has to give is q=1.
As we’ve observed, in this formula, ‘p’ (the quantity of taken assets) always equals ‘q’ (the quantity of given assets). However, this approach is inefficient as the price would remain constant, which is not ideal. We require a dynamic pricing system that can adapt to market conditions.

Formula 3: X * Y = K

Once again, X and Y denote the quantities of assets A and B in the pool, respectively, and K is a constant. The system’s main goal is to keep K constant while X and Y vary. For example, if Alice desires to buy ‘p’ units of asset A from the pool, the quantity of asset B she has to give, ‘q’, is calculated using the equation (X — p) * (Y + q) = K. Thus, q=(K/X-p)-Y, which is a positive value since X-p<X, implying that K/X-p > K/X = Y. Therefore, we don’t encounter a problem like in Formula 1. Also, the quantity of q per p, i.e., the price, is calculated by q/p=(K/X-p)/p-Y/p=K/(p*(X–p))-Y*(X-p)/p*(X-p)=(K-YX+Yp)/p*(X-p)=Yp/p*(X-p)=Y/X-p. Hence, as p increases, the price also increases. This results in a dynamic system capable of adapting to market conditions and prevents the complete draining of one of the assets from the pool. Thus, this formula meets our needs.

As we discussed above, the price of a pool depends solely on the amount of the desired asset to be bought and the rates of the assets in the pool. One might wonder how we can ensure price consistency between such a pool and other pools created with the same pairs, as well as with centralized exchanges. The answer is simple: we don’t do anything. However, this doesn’t mean that price fluctuations are inevitable. The key mechanism at work here is arbitrage.

Arbitrageurs perform arbitrage by buying an asset from a cheaper pool (or exchange) and selling it to a more expensive one. This process has the effect of increasing the price in the cheaper pool by reducing its supply, while simultaneously decreasing the price in the more expensive pool by increasing its supply. By the end of this process, the arbitrageur is guaranteed a profit as a result of their actions.

From the above discussion, we can infer that Formula 3 could be adopted as the rule of exchange. It’s important to note, however, that this isn’t the only formula that works (see the StableSwap formula of Curve, for example). Let’s take a look at the graph for it:


This is a generic graph for the formula x*y=k, where k is a constant. The x and y axes represent the quantities of tokens A and B, respectively. Upon close observation, it is evident that the correlation between tokens spent and tokens gained is non-linear.

Hence, if the quantity of tokens spent is doubled, the quantity of tokens gained does not correspondingly double; in fact, the gain is less than twice the original amount. The table below illustrates the substantial increase in the cost per token gained as the pool depletes.


The table above demonstrates how the prices change in an ETH/DAI pool, initially set up with 100 ETH and 100,000 DAI. The premium indicated in the table is a natural consequence of the constant product formula and is known as slippage. While slippage can create inefficiencies, it also serves to protect the pool from potential attacks. However, it’s important to note that slippage is directly related to the total liquidity of the pool; greater liquidity results in more efficient swaps.

For instance, as we saw above, if Alice attempts to buy 5 ETH from a pool that contains 100 ETH and 100,000 DAI, she would face a slippage of 5.26%. But what if she attempted the same swap on a pool that was ten times more liquid, containing 1000 ETH and 1,000,000 DAI? In this scenario, the constant product is 1000*1,000,000 = 1,000,000,000. So, if she wants to buy 5 ETH, she would have to pay (1,000,000,000/995)-1,000,000=5025.13, resulting in a slippage rate of approximately 0.5%.

As demonstrated above, enhancing the liquidity in the pool leads to more efficient trades. Therefore, we need to devise a method to increase the liquidity of the pool. While we could add more assets at the beginning, a more effective approach would be to encourage individuals to contribute liquidity to the pool. The question then arises: “Why would they do this?” Naturally, they wouldn’t lock up their tokens purely out of goodwill. However, if they see a potentially profitable situation, they might be inclined to do so. To facilitate this, we could introduce a fee mechanism to the pool, where all fees are distributed to liquidity providers (or LPs). Some protocols even distribute their tokens to LPs as an additional incentive. It’s important to note that when Alice adds liquidity to a pool, she must contribute an equal amount of both assets to maintain the balance of the pool. If she only has one of the assets, she would need to sell half of it for the other asset before becoming an LP. Fortunately, many platforms can handle this step on behalf of Alice, enhancing the user experience.

When Alice becomes an LP of a pool, newly minted LP tokens are sent to her. These tokens represent her share in the pool. For instance, if Alice holds 3% of the pool’s total liquidity, i.e., 3% of both assets in the pool, she possesses 3% of the total circulation of LP tokens. Thus, owning 3% of LP tokens gives her a right to 3% of the fees generated by the pool. It’s worth noting that some protocols operate without an LP token system and distribute fees regularly without any claim process.

However, LP tokens serve functions beyond claiming fees. They represent the holder’s share in the pool, so transferring them to another address confers the rights of those tokens to the new address. This offers flexibility for the assets in the pool, rather than simply being locked. For example, a user could borrow an asset by using their LP tokens as collateral or stake them in another protocol to earn additional incentives (see Curve-Convex relationship).

The revenue of Liquidity Providers (LPs) is directly correlated with the volume of the pool. This means that during periods of high trading volume, LPs can reap significant profits. A prime example of this can be observed in the ARB/ETH pool of Uniswap on the Arbitrum network. After the ARB airdrop became available for claiming, people hurried to swap their ARB tokens for ETH. In just three days, one of the ARB/ETH pools processed over $378.5M in volume, and the total fee generated during this period exceeded $1.135M. The screenshot below was taken a day after a position was created on the first day the airdrop was available for claim. A user established a position worth approximately $5k and earned more than $6.3k in fees in a single day.


Being a Liquidity Provider (LP) might seem like the best gig in the DeFi world, but is it as good as it sounds? Despite the many advantages, being an LP does come with its own risk, known as “impermanent loss”. To understand what impermanent loss is, we need to examine the swap mechanism in an Automated Market Maker (AMM) pool.

Essentially, when a trader buys Asset A in exchange for Asset B, they take Asset A from the pool and contribute an equivalent value of Asset B. Since LPs provide the liquidity for the pool, one could view this as the trader selling their Asset A to the LPs in exchange for Asset B. If the price of Asset A increases relative to Asset B after this trade, the LPs would have incurred a loss compared to simply holding the same amount of assets instead of providing liquidity.

Let’s illustrate this with an example. Consider a standard ETH/DAI pool that starts with 90 ETH and 90,000 DAI. Let’s say Alice and Bob each have 10 ETH and 10,000 DAI. Alice decides to add all of her assets to the pool, while Bob holds onto his. Now, imagine someone buys 10 ETH from the pool. They would have to pay 11,111.11 DAI (as per the table above), leaving the pool with 90 ETH and 111,111.11 DAI.

Alice’s share of the pool is now 9 ETH and 11,111.11 DAI, meaning she effectively sold 1 ETH for 1,111.11 DAI. If the price of ETH were to rise after this point, Alice would make less profit than Bob because she sold one of her ETH. Moreover, as the price of ETH rises, arbitrageurs would continue buying ETH from the pool, decreasing Alice’s ETH balance over time.

However, this loss isn’t permanent. If the price of ETH falls back to 1,000 DAI, Alice would regain all her ETH, and in the meantime, she would also earn some trading fees. But there is no guarantee that the price of ETH will fall back to its original level. This is the risk that LPs assume.

In upcoming posts, we will delve into the mathematics behind impermanent loss. Meanwhile, you can utilize tools like CoinGecko’s impermanent loss calculator to test strategies for being a Liquidity Provider (LP). Additionally, UniSwap’s version 3 introduces a clever solution to limit impermanent loss, but we’ll explore that in another blog post.

To summarize, this blog post dissected the anatomy of Automated Market Makers (AMMs), focusing on elements like the constant product rule pioneered by UniSwap (with a future discussion on Curve’s stableswap formula), the LP token mechanism, slippage, and impermanent loss.By better understanding these principles and mechanics, we can navigate the landscape of decentralized finance more effectively, making informed decisions about providing liquidity, managing risk, and optimizing returns. Stay tuned for our upcoming posts, where we delve deeper into these complex, yet fascinating aspects of the DeFi world.

BTW don't forget to follow me https://twitter.com/arbnom

Write & Read to Earn with BULB

Learn More

Enjoy this blog? Subscribe to arbnom

16 Comments

B
No comments yet.
Most relevant comments are displayed, so some may have been filtered out.