Centralized Exchanges and Order Book
Apart from the DeFi movement, the order book model is the usual way of organising 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.
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 her 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.
Attempts at replicating the order book model
Following the hacks of multiple centralized exchanges, 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, 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 roughly 50 transactions per second and a 15 seconds block time, 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 has 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:
- 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 hold 20 XTZ and 100 USDtz, its constant product is $k=2,000$. If someone wants to swap some XTZ against some USDtz, they have to provide tokens in a manner such that $k$ remains constant. For instance, Fig. 2 illustrates a swap where a trader provides 5 XTZ to the pool. For $k$ to stay constant at 2000 considering the addition of 5 XTZ, the pool needs to keep $2000 / ( 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:
- 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 $100 / 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:
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 asymptotic manner toward infinity.
The more liquidity a pool has, the closest the marginal price will be to 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 $k$ equal to 200,000,000,000. The marginal price of XTZ is $1000000 / 200000 = 5$ USDtz. If a trader inputs 5 XTZ, the pool needs to only keep $200000000000 / ( 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 liquidity to stabilize the price in pools.
This is why liquidity pools are also known as Automated Market Makers (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 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 10 USDtz per XTZ.
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, 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 maker or CFMM. 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.
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 maliciously, 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 a bull market. More on this here.
Liquidity pools on Tezos
Liquidity Baking is a tez/tzBTC single pair AMM introduced on Tezos with the Granada protocol.
The motivation behind such a contract (brought for the ﬁrst 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 speciﬁc to tzBTC and can be used for any arbitrary tez/token Tezos pool.
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 is the execution time. Still, as transactions are made faster with each amendment of Tezos, liquidity pools could soon become the primary way of trading on Tezos.