Skip to main content

Decentralized Exchanges

An exchange is a marketplace where coins and tokens are traded. The core function of an exchange is to ensure fair, orderly trading and the efficient dissemination of price information for everyone trading on the exchange. Exchanges give companies, traders, and crypto-enthusiasts a platform from which to sell and buy crypto-currencies publicly.

Centralized Exchanges and Order Book#

Apart from the DeFi movement, the order book model is the usual way of organising exchanges. All centralized crypto-currency exchanges like Coinbase and Binance still use this model. This is also the way traditional stock exchanges such as NYSE or Nasdaq work.

Simply put, traders set buy and sell orders for an asset, and the order book orders them by their prices. You can therefore trade any asset as long as there is a supply and a demand for it.

The order book model puts buyers and sellers in contact. Buyers try to buy the asset for the lowest possible price, whereas sellers try to sell the asset for the highest possible price.

Note that order books have existed for centuries in paper form and are now based on fully automated software.

For a trade to happen, both buyers and sellers have to converge on a price. This can happen by either a buyer bidding higher or a seller lowering their asking price.

For instance: Alice has a sell order at $5.0, and Bob has a buy order at $4.6. Their orders don't meet. We call the mid-market price the average point between buyers and sellers, here it's at $4.8 (see Fig. 1). For a trade to happen, Alice has to lower its offer to $4.6, or Bob has to increase his demand to $5.0. Another solution would be to wait for another trader to bid or sell at these prices. As exchanges normally have thousands of orders in and out the mid-market price move constantly.

FIGURE 1: Illustration of an Order Book. Here buyers and sellers are meeting at the $4.80 price point.

But what happens if the gap between sellers and buyers is too large and no one wants to compromise? Or if not enough coins are on sale to meet the demand? This is where market makers come into play.

Market makers provide liquidity to the exchange by buying or selling at the mid-market price minus a spread. A spread is a slight difference between their buying and selling offers. In our example, the mid-market price is at $4.80; a market maker would typically buy at $4.79 and sell at $4.81, making profits from the $0.02 spread.

Note that market makers need a lot of liquidity on both sides of the market to be effective. In our example, a market maker would need a lot of XTZ and a lot of USDtz to keep the market liquid even when demand is high on one side. Market makers essentially act as wholesalers to satisfy the market.

Spread is traditionally kept low by setting the market makers in competition with each other. Market makers also earn commissions from the exchange for providing liquidity.

Decentralized Exchanges#

Attempts at replicating the order book model#

Following the hacks of multiple centralized exchanges [1], investors started to look for alternatives. If blockchain is built around the concept of decentralization, shouldn't exchanges be decentralized as well?

At first, developers tried to reproduce the order book model into smart contracts [2], but this proved to be very inefficient. Indeed, the model relies heavily on market makers, and they require to constantly adjust their buy and sell prices to meet the market. Supply and demand constantly evolve on an exchange, making the mid-market price move. When that happens, market makers have to cancel their offers and create new orders at the new mid-market price. This results in a vast number of orders and order cancellations being sent to the exchange.

With blockchains such as Ethereum or Tezos, with a throughput of 10 transactions per second (respectively 40) and a 15 seconds block time (respectively 60) they can not be a viable option for an order book exchange. Binance, for instance, handles thousands of order book operations per second.

On top of that, every interaction with a smart contract costs a gas fee, so market makers would go bankrupt just updating their orders.

If exchanges were to thrive on the blockchain, there was a need for a new model.

Creating a new model: Liquidity Pools and Automated Market Makers (AMM)#

Uniswap was the first to propose a new model of exchange based on Liquidity Pools. In essence, a liquidity pool holds 2 tokens. For instance, XTZ/USDtz is a pool holding both XTZ tokens and USDtz tokens, where traders swap (exchange) one for the other. Each pool represents additional pairs that can be traded, e.g., tzBTC/XTZ, wXTZ/USDtz, etc.

The most important property of a liquidity pool is to respect the notion of constant product, ruled by the following equation:

Rxโˆ—Ry=kR_x * R_y = k

where:

  • RxR_x is the reserve quantity of the xx token in the pool (e.g., USDtz)
  • RyR_y is the reserve quantity of the yy token in the pool (e.g., XTZ)
  • kk is a constant

For instance, if a pool hold 20 XTZ and 100 USDtz, its constant product is k=2,000k=2,000. If someone wants to swap some XTZ against some USDtz, they have to provide tokens in a manner such that kk remains constant. For instance, Fig. 2 illustrates a swap where a trader provides 5 XTZ to the pool. For kk to stay constant at 2000 considering the addition of 5 XTZ, but the pool needs to keep 2000/(20+5)=802000 / ( 20 + 5 ) = 80 USDtz in reserve, meaning the trader will receive 20 USDtz.

The trader just got 20 USDtz for 5 XTZ, meaning an effective swap price of 4 USDtz per XTZ.

The effective swap price is not to be mistaken with the marginal price, i.e., the price of an infinitesimal small trade that doesn't effectively change the amount of tokens in the pool. The following equation defines the marginal price:

p=Rx/Ryp = R_x / R_y

where:

  • pp is the marginal price of asset yy in the xx currency
  • RxR_x is the reserve quantity of the xx token in the pool (e.g., USDtz)
  • RyR_y is the reserve quantity of the yy token in the pool (e.g., XTZ)

For instance, for a pool with 20 XTZ and 100 USDtz, the marginal price of XTZ would be 100/20=5100 / 20 = 5 USDtz.

The difference between the effective swap price and the marginal price is referred to as slippage, i.e., the tendency of prices to move against a trader's actions as the trader absorbs liquidity โ€” the larger the trade relative to the pool size, the greater the possible slippage.

FIGURE 2: Illustration of a token Swap. The trader first sends his input tokens, then the pool computes the effective swap price by maintaining a constant product, and finally sends the output of tokens.

From this, you can deduce two things:

  1. You can never empty all the liquidity from a pool. As you withdraw more and more tokens from one side of the pool, the effective swap price will shift toward the other side of the curve in an asymptotically manner toward infinity.

  2. The more liquidity a pool has, the closest the marginal price will be from the effective swap price (i.e., the lowest the slippage). Imagine a pool with 1,000,000 USDtz and 200,000 XTZ, and thus constant kk equal to 200,000,000,000. The marginal price of XTZ is 1000000/200000=51000000 / 200000 = 5 USDtz. If a trader inputs 5 XTZ, the pool needs to only keep 200000000000/(200000+5)=999975.00063200000000000 / ( 200000 + 5 ) = 999975.00063 USDtz in reserve, meaning the trader will receive 24.99937 USDtz. The effective swap price is 4.99987 USDtz and, therefore, very close to the 5 USDtz marginal price. The slippage is therefore very low.

Like centralized exchanges, liquidity providers (LP) play an essential role by providing liquidities to stabilize the price in pools.

This is why liquidity pools are also known as Automated Market Maker (AMM) their price is automatically set based on the number of tokens currently available in the pool (and not by some arbitrary order book that represents potential orders and not the actual liquidity).

FIGURE 3: Marginal price vs. effective swap price of two pools of different sizes.

From now on, let's consider only pools with enough liquidities, so that the effective swap price is almost the same as the marginal price, and only refer to it as the price.

Arbitrage#

Arbitrage happens when the price offered by the pool diverges from the price shown for the same pair on other platforms. In our example, the price of XTZ is 5 USDtz. Now suppose that XTZ is being traded everywhere else at 10 USDtz. Arbitrageurs will, therefore, immediately buy XTZ from the pool at 5 USDtz and resell it on other platforms at 10 USDtz, making profits in the process. This process will keep going until the reserves in our pool shift sufficiently to align with the rest of the market at 5 USDtz per XTZ.

LP tokens#

When liquidity is supplied to a pool, the liquidity provider (or LP for short) receives unique tokens called LP tokens in proportion to how much liquidity they provided to the pool. When a swap occurs in the pool, a 0.3% fee is proportionally distributed amongst all the LP token holders. If a liquidity provider wants to get his underlying liquidity back and any accrued fees, he must burn his LP tokens.

FIGURE 4: How liquidity providers are rewarded

Different types of AMM#

Contrary to popular belief, Uniswap did not invent the AMM. The concept had actually been studied extensively in academic literature for over a decade [5], the majority of which were primarily designed for information aggregation and implemented in markets where the payoffs depend on some future state of the world (e.g., prediction markets).

The most popular AMM is the Logarithmic Market Scoring Rule, developed in 2002 and used in most prediction markets.

While it is true that Uniswap is an AMM, we could refer to it more specifically as a constant function market makers or CFMMs. CFMMs are the first class of AMMs to be applied explicitly to real-world financial markets. There are multiple types of CFMMs:

Constant Product Market Makers#

This type is the one used by Uniswap and the one we studied so far in this chapter. A constant product function will form a curve with the desirable property of always having liquidity as prices approach infinity on both sides of the spectrum.

It is represented by Rxโˆ—Ry=kR_x * R_y = k for two assets, or more generally in tri-assets (or more) pools by:

โˆi=1nRi=k\prod_{i=1}^n R_i = k

Constant Sum Market Makers#

A constant sum market maker is a relatively straightforward implementation of a constant function market maker, satisfying the equation Rx+Ry=kR_x + R_y = k for 2 assets, or more, generally in tri-assets (or more) pools by:

โˆ‘i=1nRi=k\sum_{i=1}^{n} R_i = k

While this function produces "zero slippage", it does not provide infinite liquidity and thus is unlikely to be used as a standalone implementation for a decentralized exchange use case. In practice, what would happen is, any arbitrageur would always drain one of the reserves, if the relative reference price of the reserve tokens was not one.

Others#

There are also Constant Mean Market Makers with weighted reserves, Hybrid CFMMs, and so on, each trying to find specific and innovative use-cases.

The risks of liquidity pools#

Although DEXs are decentralized and trustless, keep in mind that there are always risks with smart contracts. There have been countless cases of malicious code or fatal errors in smart contracts. In 2018, decentralized exchange Bancor was hacked and suffered a loss of $13.5M in assets before freezing the funds.

When you deposit funds into a liquidity pool, they are in the smart contract, so while there are technically no middlemen holding your funds, the contract itself can be thought of as the custodian of those funds. If for example, there is a bug, your funds could be lost forever.

Also, be wary of projects where the developers have permission to change the rules governing the pool. Sometimes, developers can have an admin key or some other privileged access within the smart contract code. This can enable them to potentially act malicious, like taking control of the funds in the pool.

If you want to provide liquidity to an AMM, make sure to become familiar with the notion of impermanent loss. In short, it's a loss in dollar value when providing liquidity to an AMM rather than keeping the tokens themselves as they are in your wallet (a.k.a. HODLing) during times of bull market. More on this here.

Conclusion#

The concepts behind liquidity pools and automated market-making are pretty simple yet extremely powerful. They alleviate the need for centralized order books. The only obstacle to the further development of liquidity pools are the sometimes high gas fees and the execution time. Still, as gas fees are reduced and transactions made faster with each amendment of Tezos, liquidity pools could soon become the primary way of trading on Tezos.

Liquidity pools on Tezos#

References#

[1] https://selfkey.org/list-of-cryptocurrency-exchange-hacks/

[2] https://thecontrol.co/a-comparison-of-decentralized-exchange-designs-1deef249f56a

[3] https://finematics.com/liquidity-pools-explained/

[4] http://fiquant.mas.ecp.fr/wp-content/uploads/2015/10/Limit-Order-Book-modelling.pdf

[5] http://reports-archive.adm.cs.cmu.edu/anon/2012/CMU-CS-12-123.pdf

Last updated on by Aymeric BETHENCOURT