The Hitchhiker’s Guide to DeFi (Part II) — DEXs & AMMs

Rahul Rai
8 min readOct 14, 2020

--

The ultimate vision for Decentralized Finance (DeFi) is to build a self-sovereign financial system allowing users to engage in a broad range of economic activities without the need to rely on centralization, trust, and accessibility.

In the previous post, we covered lending & borrowing protocols, the building blocks of DeFi. In this post, we’ll dive into Decentralized Exchanges (DEXs), which are peer-to-peer (p2p) electronic markets that are built on the blockchain, and that utilize Automated Market Maker (AMM) protocols to provide continuous liquidity with minimal slippage. We’ll highlight the three main types of DEXs, and highlight the underlying equations that drive their AMM protocols.

We’ll end by deriving an equation to quantify “impermanent loss”, an exotic financial risk that all DEX liquidity providers are exposed to, yet most are either unaware of or don’t mathematically model out.

AMMs are Dexy

Decentralized Exchanges (DEXs)

DEXs are decentralized exchanges for digital assets, allowing investors to seamlessly trade between cryptocurrencies, without the need for a traditional order book-based centralized exchange DEXs typically have three participants:

  • Traders: Use DEXs to swap assets in and out of the pool
  • Liquidity providers (LPs): Deposit their assets in liquidity pools, on which they earn returns by collecting trading fees
  • Arbitrageurs: Maintain the price of assets within that portfolio in accordance with the market price in exchange for a profit.

Automated Market Makers (AMMs)

AMMS are smart contracts that hold liquidity reserves (or liquidity pools) that traders can trade against. These reserves are funded by liquidity providers (LPs). AMM protocols use a formulaic approach to determine the price of an asset. Constant Function Market Makers (CFMMs) are a specific, and the most widely used, type of AMMs that were designed by the crypto community. The term ****“constant function” refers to the fact that any trade must change the reserves in such a way that the product of those reserves remains unchanged.

There are three main types of DEXs/CFMMs:

  1. Uniswap (Constant Product Market Maker)
  2. Balancer (Constant Mean Market Maker)
  3. Curve (Hybrid Function Market Maker)

Uniswap

Uniswap is one of the first ever open-source decentralized exchange protocols. It was launched in November 2018 by Hayden Adams (V2 was launched in May 2020) and it pioneered the implementation of a constant product market. A transaction in this market, swapping Δβ coins of β for Δ⍺w coins of ⍺ must satisfy:

The name “constant product market” comes from the fact that adding any amount of either asset must change the reserves in such a way that the product Rα * Rβ remains equal to the constant k* (assuming no fees). This is often simplified in the form of $x*y=k$, where x and y are the reserves of each asset.

Assuming no-arbitrage conditions, the marginal price of coin ⍺ in terms of coin β, which is defined as the price of an infinitesimally small trade (Δ⍺ → 0), can be determined by differentiating the constant product market equation as follows:

Hence marginal price offered by Uniswap (assuming no fees, i.e $γ=1$) can be represented as:

A constant product function forms a hyperbola when plotting two assets, which has a desirable property of always having liquidity as prices approach infinity on both sides of the spectrum.

Balancer

Balancer is a non-custodial automated market maker that was the first to implement a constant mean market. A constant mean market maker is a generalization of a constant product market maker, allowing for more than two assets and allowing for weights outside of 50/50.

Constant Mean Market Makers

A constant mean market maker is a generalization of a constant product market maker, allowing for more than two assets and allowing for weights outside of 50/50. First introduced by Balancer, constant mean markets satisfy the following equation in the absence of fees:

Where Ri​ is the reserve of each asset, w is the weights of each asset, and k is the invariant. In other words, in the absence of fees, constant mean markets ensure that the weighted geometric mean of the reserves remains constant.

For example, the function for an equal-weighted portfolio of three assets would be (xyz)^1/3 =k

Source: Balancer Whitepaper

Curve

Curve Finance, which focuses on stablecoin and wrapped asset liquidity, has seen a significant increase in trading volume.

The following figure shows the daily trading volume of each stablecoins on Curve. The figure shows that DAI, USDC & USDT have the highest trading volume among the stablecoins supported on the platform due to the direct demand from liquidity mining.

Hybrid CFMMs

Curve aimed to modify the AMM function to minimize slippage for assets that are relatively stable-priced. The protocol looked for an invariant that’s relatively flat near balance (price changes slowly), however, that shifts towards the constant-product invariant as the portfolio becomes more imbalanced. The hence came up with the following Stable Swap invariant.

Source: Curve Whitepaper

Impermanent Loss

One final, yet crucial, comment on DEXs — there is an exotic financial risk called impermanent loss that is not intuitive, and yet every liquidity provider (LPs) is exposed to it.

Many LPs are unaware of the fact that they are exposed to price risk, that can wipe out the profits they earned through fees by providing liquidity. This price risk is captured by the term “impermanent loss”. For eg, when liquidity providers look at the value of their stake in the liquidity pool, they may find that it’s worth less than what they put in. What’s going on here?

To understand why this can happen, let’s assume that the liquidity providers are using the Uniswap V2 protocol. As shown earlier, assuming no-arbitrage conditions, the price can be represented as:

Combining this with the constant product market function Rα*Rβ=k, we can work out the size of each liquidity pool at any given price as follows:

We can now compute Vt the value of the LP’s portfolio at time t (in units of coin β):

Hence the LP’s PnL (in units of token β) at any time t=T can be represented as:

Hence, the PnL from price movements increases non linearly with the change in price.

The value of a portfolio (HODL) that was bought at time t=0 and held to time t=T is:

We’re now ready to calculate the impermanent loss. Impermanent loss **is defined as the % difference between portfolio values if we bought and held the underlying coins (HODL) vs provided liquidity into the pool.

When we plot the impermanent loss as a function of the price ratio, we get the following graph that clearly exhibits negative convexity, which is never desirable for LPs! This means that no matter which direction the price moves in, LPs will always be taking a hit vs HODL because of the impermanent loss.

Source: Pintail

So the actual return for LPs is a balance between the impermanent loss caused by the price differential and the accumulated fees from trades on the exchange. Does this make intuitive sense? Absolutely! When price takers come in looking to trade or swap, the liquidity providers are forced to take the opposite side of the transaction. Hence The phrase “impermanent loss” is hence a misnomer, as the loss is very much permanent unless the exchange rate returns back to the original price.

If long term price movements are large, they could result in losses much greater than the yield generated from collecting fees. However, if Uniswap manages to gain enough traction it could be profitable for LPs, as long as price movements remain sufficiently rangebound.

Summary

Constant Function Market Makers is the brainchildren of the ingenious DeFi community. We can model out the returns LPs are expected to earn by using the following equations:

And finally, impermanent loss, which is defined as the % difference in portfolio values for providing liquidity vs buying & holding, can be represented as:

Appendix I: Incorporating Fees

Okay, I’m going to come clean. The equations that I derived in this post aren’t completely accurate. I made a few simplifying assumptions to make the math easier. They are still extremely useful to model out expected PnL, but in this appendix, we’ll derive an even more accurate approximation. So first question, what are we missing?

In the analyses above, we assumed zero transaction fees. What happens to the returns LPs can expect to make when we include transaction fees?

In the prior equations, we assumed that fees were just distributed out to LP providers as they were accrued. While this is a fair assumption, the actual mechanism for fee distribution is a little different. Instead of just directly distributing fees to LPs, the Uniswap protocol re-invests the fees into the pool. What this means is that the reserves of assets in the pool is constantly increasing, and hence k is constantly increasing.

In other words, if γ < 1, then k is always strictly increasing. It’s pretty easy to show why:

So now that we know that k is constantly increasing with time, a better way to calculate the expected returns for LPs at time t=T is:

Source: https://web.stanford.edu/~guillean/papers/uniswap_analysis.pdf

Appendix II: Balancer Equations

Source: https://medium.com/balancer-protocol/calculating-value-impermanent-loss-and-slippage-for-balancer-pools-4371a21f1a86

Sources

An Analysis of Uniswap Markets: https://web.stanford.edu/~guillean/papers/uniswap_analysis.pdf

Curve Whitepaper: https://www.curve.fi/stableswap-paper.pdf

Understadning Uniswap Returns: https://medium.com/@pintail/understanding-uniswap-returns-cc593f3499ef

What is Uniswap and How Does it Work: https://academy.binance.com/tutorials/what-is-uniswap-and-how-does-it-work

CFMMs DeFi’s Zero to One Innovation: https://medium.com/bollinger-investment-group/constant-function-market-makers-defis-zero-to-one-innovation-968f77022159

Building a Decentralized Exchange on Ethereum: https://blog.gnosis.pm/building-a-decentralized-exchange-in-ethereum-eea4e7452d6e

AMM Theory & Practice: http://reports-archive.adm.cs.cmu.edu/anon/2012/CMU-CS-12-123.pdf

Unbundling Uniswap: https://medium.com/dragonfly-research/unbundling-uniswap-the-future-of-on-chain-market-making-1c7d6948d570

--

--

Rahul Rai
Rahul Rai

Written by Rahul Rai

Crypto, Finance, Tech enthusiast

No responses yet