Unraveling DEXs

For a first encounter with UNISWAP’s Automated Market Maker

Mariana Carmona
Immutable Oasis Labs

--

Decentralized Exchanges (DEXs)allow the exchange of cryptocurrencies in a permissionless, censorship-resistant, and automated manner [1] with a very interesting design such that it merits a deep dive. In this attempt, I try to make this encounter as smooth as possible. The case I take is UNISWAP V2 (and some changes in Uniswap V3), the biggest DEX so far in terms of its Market Cap.

DEXs are decentralized applications (dApps) that use smart contracts to enable token swaps. At a high level, the type of DEX described here is integrated by liquidity pools holding digital assets that act as reserves. UNISWAP’s liquidity pools hold two tokens while other DEXs, such as Balancer, hold more than two assets within a liquidity pool. In DEXs liquidity providers deposit digital assets into a pool, whose share is proportionate to their liquidity contribution, expressed as a fraction of the entire pool. Traders coming to a DEX exchange one asset for another. The exchange rate at which the tokens are traded is determined by an Automated Market Maker (AMM).

Automated Market Makers (AMMs)

AMMs substitute the need for order books. In fact, an order book in a DEX is not practical and expensive to run in a smart contract environment because of the large sets of outstanding orders paying for space and computing power. Some other DEXs tried to combine order books with on-chain and off-chain execution. This scheme has different drawbacks such as front-running, latency arbitrage and staled orders [4]. Conversely, AMMs allow high-frequency trading through algorithms that determine how the liquidity becomes available for trades, based on a deterministic function called Bonding Curve or Conservation Function [2].

Let’s start digging !

A bonding curve allows swapping tokens while keeping invariant their total value in the liquidity pool, that is, each trade has to be made in a way that the value removed in one digital asset equals the value added in the other [2]. The geniality of bonding curves used in DEXs is that they encode a desired invariant property while keeping two mechanisms in operation: the swapping of digital assets and the liquidity provision or withdrawal. Nonetheless, choosing a mathematical function as a bonding curve is not trivial. Bonding curves have certain properties, for instance, the function must be concave, nonnegative and nondecreasing [2]. Not all DEXs are designed upon the invariant properties of a bonding curve, for instance, dYdX or Binance DEX utilize order books.

The function used by UNISWAP is the Constant Product Market Maker (CPMM) :

The CPMM (1) means that the product of the reserves of two tokens in a liquidity pool has to be equal to a constant value ‘k’ regardless the token swap activity. k changes when liquidity is added or withdrawn from the pool. Following with a pool composed by ETH and DAI, the the token swaps in a CPMM look like:

How’s the exchange price determined?

When a trading occurs, the exchange rate is determined by the relative price of the traded asset pair, that is, the price of ETH is expressed in units of DAI, which means ETH is valued in its capacity to buy DAI. The price is the best exchange rate a trader can obtain by swapping arbitrarily small quantities. In mathematical terms, this is the limit when both traded assets tend to zero thus the negative first derivative of the function in that state. In the CPMM function, this is the ratio of the two reserves:

The first liquidity provider sets the initial exchange rate of tokens. Note that the initial provision must be equal in value. Perhaps you would like to see a practical example. Suppose the pool is composed by 20 ETH with a market value of US 1,000 each (ha ! old times for ETH). To equalize the value in the pool, the stable coin DAI provision must be 20,000.

The constant k is 20 x 20,000 = 400,000 and the price of ETH in units of DAI is: 20,000/20= 1000

Suppose a trade of 3 ETH from the pool. For now we are assuming that the transaction fee is zero (γ=(1+fee)). The rate at which the exchange occurs is determined by extracting 3 ETH from the pool and adding the equivalent value in DAI keeping the constant value k=400,000:

In this example, the trader has to pay on average 1,176.47 DAI for each ETH. The pool ends with 17 ETH and 23,529.41 DAI. Arbitrageurs will profit from the price difference adding ETH to the pool and that action will reduce the price again. Note that this is a simplified static example, now scale this operations in an unstoppable high-frequency trading 24/7 !

The CPMM function has some nice properties, for example, it is easy to recover the protocol’s price by dividing the quantity of reserves of the two tokens in the pool; the price is strictly positive whatever the reserves available in the pool might be, and one cannot exhaust the stock of one asset as the relative price increases sufficiently fast [3] as you could see with the first trade in the example.

The devil’s in the details: impermanent loss and price slippage

DEXs are not free from risks and costs. Herein, I address the main risk for liquidity providers (impermanent loss) and for traders (price slippage).

Slippage

Trading in DEXs includes costs that the trader has to bear in mind. The first one is the gas fee for using the blockchain (in Uniswap, it is the gas fee to the Ethereum network), the second cost is the fee paid in every transaction (0.3% in Uniswap) and the slippage cost. The price slippage is defined as the difference between the effective exchange rate obtained by the trader and the market price. In absence of slippage, a trader would pay the market price (p) regardless of the volume traded:

The slippage cost that a Uniswap V2 user experiences when swapping token ‘x’ for token ‘y’ can be calculated as the ratio of the effective exchange rate (token swap) and the pre swap spot exchange rate (the ratio of the reserve quantities) [2] :

Notice in the slippage calculation that tokens with higher liquidity (reserves) have less slippage cost and also that small swaps have lower slippage. If you want to make a big trade of tokens with low liquidity, you would be increasing the slippage to yourself !. Uniswap sets a default slippage tolerance (0.5%), however in the transaction settings it is possible to change it. A slippage above the tolerance level makes the swap’s execution to fail.

Screenshot from uniswap.org

In Uniswap V3, the liquidity is limited to a range in price [P low, P high]. It is the same bonding curve moved left and down. With this change to the CPMM, as long as there is liquidity for both assets, the range in exchange rates restrains the slippage — specially important for small market cap tokens twith less liquidity.

Impermanent Loss

Liquidity providers generate revenues via the transaction fees paid by traders in every exchange performed — often called liquidity mining. In Uniswap, the 0.3% fee charged in every trade is distributed to liquidity providers in the proportion of their contribution to the pool. Nonetheless, liquidity providers have to lock the funds (moreover some DEXs contemplate a withdrawal penalty). One of the risks associated to locking funds is called impermanent loss (IL) which occurs when a price movement results in less value of providing tokens to a liquidity pool than just holding. The loss is ‘impermanent’ because the price of the digital asset can recuperate thus neutralizing it. It becomes a permanent loss if the funds are effectively withdrawn. The higher the volatility of the asset, the bigger the exposure to impermanent loss.

Impermanent loss can be obtained by comparing the value of the portfolio vis-à-vis the value of holding the assets out of the pool (stake vs hodl).

From the previous example, suppose that ETH now trades at US 1,300 and a liquidity provider staked 10% of the pool (2 ETH, 2000 DAI). After the trade in the example, the pool ended with 17 ETH and 23,529.41 DAI. Had the liquidity provider simply held his assets, at the new price, his portfolio would be worthing US 4,600 whereas staking in the pool gives a portfolio value of: US 4,562.94

Holding:

Staking:

The Impermanent Loss is the ratio of the value of staking vs holding in US:

You can use Defi Lab or similar calculators to simulate Uniswap asset value of holding vs staking, helping in your strategy as a liquidity provider. In the figure below, using an initial investment of 1000 DAI in a pool with WETH (wrapped ETH) the orange line represents holding the two assets and not staking whereas the green one is the value of staked assets in the unbounded Uniswap V2 and the dark blue uses the price range (Uniswap V3). The gaps between hodling and staking represent the impermanent loss. There is a price interval where holding vs. staking has no IL. However, note that the simulation is excluding the fees, therefore, for small impermanent losses, the attractiveness of providing liquidity is precisely the revenue from fees.

Source: Impermanent Loss simulation for a DAI / WETH pool using Defi Lab

AMMs and liquidity pools are essential for the operation of DEXs, moreover, they enable functionalities for other DeFi products such as yield farming, lending and borrowing, synthetic assets. Moreover, AMMs can be used to replicate payoffs of financial derivatives pushing their scope even further in the DeFi space.

Stay tuned for more about Unraveling DEXs !

References

[1] Aigner A. A. and Dhaliwal G. (2021). UNISWAP: Impermanent Loss and Risk Profile of a Liquidity Provider. TradeFlags, Vienna, Austria, +Fuel Ventures, London, United Kingdom

[2] Xu J., Paruch K., Cousaert S. and Fent Y. (2021). SoK: Decentralized Exchanges (DEX) with Automated Market Maker (AMM) Protocols.

[3] Direr Alexis. (2020). A primer on constant product matching markets

[4] Angeris G., Kao H.T., Chiang R., Noyes C. and Chitra T. (2019). An Analysis of UNISWAP markets.

[5] https://chainbulletin.com/impermanent-loss-explained-with-examples-math/

--

--