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 cryptocurrencies publicly.
Centralized Exchanges and Order Book
Apart from the DeFi movement, the order book model is the usual way of organizing exchanges. All centralized cryptocurrency 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 moves 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 either?
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 10) they cannot 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[3] was the first to propose a new model of exchange based on Liquidity Pools[4]. 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:
where:
- is the reserve quantity of the token in the pool (e.g. USDtz)
- is the reserve quantity of the token in the pool (e.g. XTZ)
- is a constant
For instance, if a pool holds 20 XTZ and 100 USDtz, its constant product is . If someone wants to swap some XTZ against some USDtz, they have to provide tokens in a manner such that remains constant. For instance, Fig. 2 illustrates a swap where a trader provides 5 XTZ to the pool. For to stay constant at 2000 considering the addition of 5 XTZ, but the pool needs to keep 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:
where:
- is the marginal price of asset in the currency
- is the reserve quantity of the token in the pool (e.g., USDtz)
- is the reserve quantity of the 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 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:
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.
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 equal to 200,000,000,000. The marginal price of XTZ is USDtz. If a trader inputs 5 XTZ, the pool needs to only keep 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 liquidity 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 liquidity, 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. The 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 rewardedDifferent types of AMM
Contrary to popular belief, Uniswap[3] 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 for two assets, or more generally in tri-assets (or more) pools by:
Constant Sum Market Makers
A constant sum market maker is a relatively straightforward implementation of a constant function market maker, satisfying the equation for 2 assets, or more, generally in tri-assets (or more) pools by:
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.
Liquidity pools on Tezos
Liquidity Baking
Liquidity Baking[6] is a tez/tzBTC single pair AMM voted through the Granada amendment.
The motivation behind such a contract—brought for the first time by an amendment instead of an independent set of smart contracts built separately from the protocol—is to increase the overall tez liquidity along with tzBTC, a wrapped version of Bitcoin (BTC) on Tezos.
How this DEX works is quite innovative:
- A subsidy of 2.5 tez is minted and brought to the tez/tzBTC pool at each block. It increases tez volume in the Liquidity Baking contract over time
- Liquidity providers receive fees plus freshly minted tez proportionally to their share of the liquidity pool
- Bakers can vote to stop the Liquidity Baking contract from a protocol point of view
- An emergency escape hatch is provided if something goes wrong
The smart contract used for Liquidity Baking is not specific to tzBTC and can be used for any arbitrary tez/token Tezos pool.
This project has been reviewed and formally verified by Nomadic Labs[7] and Runtime Verification[8].
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.
References
[1]. List of cryptocurrency exchange hacks.
[2]. A comparison of decentralized exchange designs.
[3]. Uniswap Protocol.
[4]. Liquidity pools explained.
[5]. Automated Market Making: Theory and Practice.
[6]. Liquidity Baking DEX on TzKT.
[7]. Follow up on the verification of Liquidity Baking smart contracts.