Basics of Crypto: Distributed Exchanges Explained

Financial chart of crypto assets

Crypto exchanges have been in the news lately, but many people don’t know that there are different types of exchanges. There are tradeoffs to using each type–and understanding their differences will help you make informed decisions.

To start at the beginning, it’s a common activity with cryptocurrencies to exchange one coin for another. For example, you might have a certain amount of ether (ETH) and want to exchange it for bitcoin (BTC). The most common way to do this is on a market created for this purpose, which is called a cryptocurrency exchange.

There are two broad categories of cryptocurrency exchanges: centralized and decentralized.

What is a centralized exchange (CEX)?

A centralized exchange (CEX) is usually run by a company or similar third party and operates largely off-chain, with only the final purchases or sales of coins made on-chain. The CEX acts as an intermediary between the parties in the transaction, usually by managing an order book, similar to the way stock exchanges like the Nasdaq facilitate stock trades.

Popular CEXs include Binance and Coinbase. FTX was also a centralized exchange.

CEXs usually support a conventional, web2 user interface. As a result, they have the advantage of familiarity and user friendliness. They may also offer more advanced kinds of transactions, such as margin trades or setting limit orders.

What is a distributed exchange (DEX)?

In a DEX, there is no intermediary operating the market. Instead, the market is operated by a set of smart contracts running directly on a blockchain. The result is a peer-to-peer marketplace that allows users to trade cryptocurrencies directly, with strong execution guarantees.

DEXs are aligned with the crypto goal of disintermediation, or removal of trusted third parties. They are usually built on open-source code that can be freely inspected. This is one of the reasons they’re growing in popularity, with the most popular DEXs running on Ethereum. Uniswap is an example of a popular DEX.

DEXs allow users to hold their private keys in non-custodial wallets and trade directly from them. The only requirement for users is that their wallet be compatible. DEXs do not impose KYC (know your customer) or AML (anti-money laundering) requirements or require any other personal information. That enables DEXs to offer greater privacy than CEXs.

Fees for DEX usage usually fall into two categories:

  1. Blockchain fees, which are the transaction fees of the underlying blockchain (e.g., gas fees on Ethereum), and
  2. Protocol fees, which are determined by the DEX protocol and are used in part to reward passive investors who stake coins to provide liquidity.

During a transaction on a DEX, the user’s funds are not held by any third party’s wallet. Therefore, DEXs reduce counterparty risk–namely, the possibility that a third party involved in your transaction may default in some way, causing loss of funds.

The centralized party running a CEX is an example of such a third party. The importance of reducing systemic risk stemming from centralization has been illustrated by the collapse of FTX. Funds held by FTX are alleged to have been used inappropriately by the company, rather than held in trust for the crypto owners as promised.

Limitations of DEXs

Because they are implemented on-chain by smart contracts, DEXs face certain limitations in comparison with more centralized architectures, which can be easier to optimize for performance:

  • DEXs may have limited transaction speed, so they are not usually suitable for high-frequency trading.
  • DEXs also compete with each other for liquidity. Liquidity providers will often move funds from one DEX to another in search of higher short-term returns.
  • As a result, a DEX may have lower liquidity at a given point, resulting in higher price impact (see below). “Liquidity” is the ease with which an investor can buy or sell an asset without changing its price. It’s a function of the amount of buyer and seller activity on an exchange.

In terms of user experience, a DEX may offer a minimal user interface. The UX may require that you hunt up tutorials to learn how to operate on the platform.

Finally, DEXs don’t allow exchange between fiat currency and cryptocurrency. They exclusively trade cryptocurrency tokens for other cryptocurrency tokens. Funds held in a non-custodial wallet are a prerequisite.

Types of DEXs

There are two broad categories of DEXs: those that use order books, as CEXs also do, and those that use automated market makers (AMMs). There are also aggregation tools that draw on multiple DEXs to improve liquidity.

Order Books

The first generation of DEXs used order books, as do most CEXs. An order book is a real-time collection of all open buy and sell orders of a particular asset. The number of bids and offers at different prices determines the depth of the order book.

The most straightforward design for a DEX would be to hold the order book on-chain, while the funds remain in users’ non-custodial wallets. However, this design requires every modification of the order book to be committed on-chain, which poses a performance problem. As a result, the DeFi field has shifted away from order books.

Recent innovations involving Layer 2s may make order books more attractive for DEXs again. For example, Loopring uses an order book based on zk-rollups, which validates transactions using zk-SNARKs (more about this design here).

There are also hybrid designs in which the order book is partially centralized. For example, the management and matching for the order book may take place off-chain, with the settlement of trades taking place on-chain.

One limitation of order books is that an order execution is not guaranteed. Execution failure may occur when there is a lack of liquidity.

Automated Market Makers (AMMs)

Due to the performance limitations of order books, DEXs have largely shifted to Automated Market Makers (AMMs). These are protocols that employ “liquidity pools” to determine asset prices.

Liquidity pools are collections of funds supplied by investors. Users can swap their tokens against the liquidity pool for a price computed by the protocol. More precisely, the liquidity pool is a smart contract that holds reserves of two or more tokens.

The smart contract allows users to deposit or withdraw from the reserves according to specific rules determined by the protocol. Investors in the liquidity pool, called liquidity providers, usually receive interest-like passive income in the form of a fraction of the transaction fees and/or payments in the protocol’s token.

As a result, an AMM is like a bot that can always quote a price between any pair of support tokens. It creates a peer-to-peer market that immediately executes trades between user’s wallets, allowing transactions to always occur.

Another advantage of AMMs is that, unlike order books, they are largely “path independent.” This means that the prices of tokens are fully determined by their present quantities in the exchange, not by the prior state of the exchange.

An AMM does not update its prices in response to other exchanges. It has no automated function to consult prices on other exchanges. A price updates only when the amounts of the tokens in the AMM’s liquidity pools change. Nevertheless, in practice, the price of a token will tend to converge to a broader market price due to arbitrage by traders. As a result, larger DEXs like Uniswap can actually be used as an on-chain source for prices.

AMM Price Formulas

AMM protocols use a formula that determines how assets are priced. There are a variety of such formulas, each with different properties. One of the older AMM formulas, used in prediction markets, is the Logarithmic Market Scoring Rule.

However, cryptocurrency DEXs usually use some kind of “constant function” formula. These formulas are so-called because they hold some function of the amount of the tokens being traded equal to a constant.

The most popular type of constant function is constant product. (Product in this context refers to multiplication.) Uniswap, for example, uses a constant product formula. For simplicity of explanation, let’s assume we have two tokens A and B.

Let \(x = amount_A\).
Let \(y = amount_B\).

Ignoring fees, the constant product formula is just \(x \times y = k\) , for a constant \(k\). What this means is that, to withdraw an amount of token A, one must deposit an amount of token B that maintains the constant \(k\) before fees. To do so, the price of token A in token B must be set by: \[price(A) = {amount_B \over amount_A}.\]

The constant product formula has the desirable property of always having liquidity as prices approach infinity for either token. Other formulas have other properties with advantages and disadvantages.

For example, the constant sum formula, \(x + y = k\), is used by mStable and other DEXs that focus on stablecoins. Constant sum minimizes slippage, but does not guarantee liquidity.

The constant mean formula is a generalization of constant product that allows for more than two assets, which may also be weighted. It holds a weighted geometric mean of the asset amounts to be constant. It is used by Balancer for tokens on Ethereum.

Finally, there are hybrid functions that, for example, approximate constant sum and constant product in different ranges, aiming to support both stablecoins and other tokens in the same AMM.

Costs of Trading on an AMM

The cost of a trade on an AMM can be broken down into four parts: price impact, slippage, protocol fees, and blockchain fees.

Price impact

Price impact is the impact of one’s trade on the price of the token being traded. A trader will often buy or sell many tokens in a single trade. All other things being equal, the tendency will be for each token to cost more than the previous one, because the trader’s own purchases are driving up the price. Price impact is a function of the size of the trade, relative to the size of the liquidity pool and the AMM formula in use.

Slippage

Slippage is the difference between an expected price quoted at the beginning of the trade and the actual price received upon execution. Whereas price impact is caused by the trade itself, slippage is caused by broader market movements, i.e., other parties’ trades. Slippage can occur either upward or downward.

Protocol fees and blockchain fees

Protocol fees are simply the trading fees defined by the AMM protocol. Blockchain fees are the fees required by the underlying blockchain, i.e., Ethereum gas fees.

Minimizing AMM trading costs

You can minimize price impact by finding the exchange with the most liquidity for the tokens you want to trade. Analysis tools like Coingecko are helpful here.

Sophisticated investors sometimes split a large trade among multiple exchanges, which reduces total price impact, but at the cost of higher blockchain fees. Another option is to break the trade into a sequence of trades using a third token as a “bridge,” if there is greater liquidity for the resulting sequence of trades.

Finally, traders can use a DEX aggregator, which allows trades to be split automatically among DEXs. In public equity markets, a stock often has a single exchange on which it is traded, such as the Nasdaq. In contrast, a token is often traded on many exchanges, which splits their liquidity across them. DEX aggregators read from multiple DEXs to find the best token price and/or the lowest fees for a trade.  Aggregating liquidity across exchanges creates a deeper liquidity pool with lower price impact.

Other AMM features

Many AMM protocols issue their own tokens, but this practice is more for competitive reasons than operational reasons. AMM protocols don’t require their own tokens to operate.

Uniswap, for example, originally had no native token. Its first issuance of its UNI token was made retroactively as a defensive step against competition from Sushiswap. Sushiswap had forked the Uniswap codebase and modified it to introduce the SUSHI token as a yield-farming reward for liquidity providers.

Because they offer immediate trades, AMMs are amenable to trading by automated software or bots. Developers can create bots to automatically execute their trades. Just as in traditional finance, bots can facilitate trading with much greater speed than a human, by operating according to pre-specified rules.

A bot on a DEX can use two basic kinds of strategy. It can execute on a single DEX using an algorithm based on data for past and present token prices and/or volumes. Alternatively, a bot can look at prices on multiple DEXs and take advantage of price discrepancies via arbitrage.

Risks for traders on a DEX

There are a number of risks that traders face when using a DEX. Here are some of the larger categories.

Centralization: In spite of their aim for decentralization, some DEXs–particularly those that use order books–still have centralized elements. Order books may be implemented with some components that run on centralized servers. Those centralized components will be subject to the same possibilities of manipulation or intervention as any centralized system.

Smart contracts: DEXs are implemented via smart contracts. Smart contracts are manually written code that are subject to bugs and have other possibilities for exploitation.

Liquidity: If a DEX has low liquidity for a given token pair, it will have a higher price impact for that pair.

Sandwich attacks: Front-running is a form of transaction manipulation well-known from traditional finance. DEXs are vulnerable to a form of front-running known as a sandwich attack.

The vulnerability stems from the fact that transactions on a public blockchain are visible to third parties. Trades on a DEX are therefore visible as well. This visibility enables developers to create bots to front-run trades by executing a similar trade more quickly. When the original trade executes, the price will be raised enough for the bot to sell at a profit immediately afterwards. Meanwhile, the original trader has experienced unfavorable slippage and possibly higher fees.

Blockchain: A DEX is subject to the risks of its underlying blockchain. Blockchain fees may become prohibitively high if the blockchain experiences higher usage than it can handle. The DEX may become completely inaccessible if the blockchain has an outage, as Solana has experienced.

Traders can minimize their risks by carefully selecting the DEX on which they trade a given token.

Risks for DEX liquidity providers

There are also risks that liquidity providers face when using a DEX.

Impermanent loss: Impermanent loss is the loss experienced by liquidity providers when the price of a token decreases after the provider deposits their tokens in a liquidity pool. The loss is called “impermanent” because the price of the token in the pool could rise again, depending on market movements.

Of course, it’s also possible for liquidity providers to experience gains due to price movements. It’s also possible for liquidity providers to make a net profit due to protocol fees and token rewards even if they experience impermanent loss. A more sophisticated analysis of a liquidity provider’s potential loss is provided by Loss-Versus-Rebalancing (LVR).

Sybil attacks on airdrops: Many DEXs award tokens to liquidity providers. These tokens may be awarded in a large airdrop. In order to be more “democratic” and avoid concentrating the reward on large liquidity providers, the development team may choose to award tokens by wallet rather than by amount of liquidity provided. These airdrops are then subject to Sybil attacks, in which a single provider may create many different wallets in order to be awarded more tokens.

The future of exchanges

We are at an early phase of exchange design. There are known tradeoffs between centralized and decentralized designs. Centralized designs can be more efficient in regard to performance but require more trust. On the other hand, decentralized designs are often less efficient and have weaker privacy due to blockchain visibility.

One challenge that DEXs face is their vulnerability to user error. For example, users can lose their private keys, seed phrases, or hardware wallets. But decentralization is not an all-or-nothing property. There is a spectrum of designs differing in their degree of decentralization. Some of the most promising new designs use cryptographic techniques, including zk-SNARKs, to prevent abuses in partially centralized designs.

Subscribe to updates from the Dragonscale Newsletter

Don't miss out on the latest posts. Sign up now to get new posts sent directly to your inbox.
jamie@example.com
Subscribe