Decentralized Exchanges (DEX) are a key foundation for the DeFi ecosystem. They give you the ability to trade and swap one cryptocurrency for another peer-to-peer, without the need for third parties such as a centralized exchange or traditional financial institutions.
Still, we have to ask: Why worry about implementing decentralized exchanges if we already have their centralized counterparts? How do DEXes actually work, and more importantly, why are they important for the DeFi space?
Decentralizing exchanges
If you are familiar with centralized exchanges (CEX), you will have no trouble understanding how decentralized exchanges work. In a centralized exchange, a central entity or corporation (see Coinbase) facilitates the trades between their users through a centralized order book which tracks every order in the platform. CEXes are responsible for aggregating these orders, matching them, and executing the actual buy and sell transactions on behalf of users.
The fact that users need to delegate the execution of transactions to the exchange translates into them not having full ownership of their keys, as CEXes need to be able send transactions on traders’ behalf to execute their orders. In practice, what CEXes do is pool users’ cryptocurrencies in a number of “hot” wallets controlled by the exchange which are used to execute the actual orders. In many cases, if the order can be matched within users in the platform, the exchange doesn’t need to execute a transaction in the blockchain at all.
What they do instead is update the balance allowances of the corresponding cryptocurrency for the users involved in the exchange on their centralized platform’s database. In the end, CEXes can be seen as traditional stock exchange brokers, but for cryptocurrencies. They serve as gateways between users and the underlying asset, offering them an interface to interact with them. This makes them really convenient to use, especially for newcomers. But they also have their drawbacks and risks, as we’ll describe in a moment.
Decentralized exchanges, on the other hand, do not rely on any centralized platform or third party to execute user orders. DEXes are able to perform the core operations of a centralized exchange and leverage a set of smart contracts to do it in a decentralized way. DEXes and their underlying infrastructure are also responsible for: receiving user orders, keeping the order book updated, matching orders, and executing them. In the case of DEXes, token exchanges are not done through a third party. Instead they are performed 1-to-1 on-chain between individuals, i.e. a full peer-to-peer exchange. Transactions are triggered by users in the corresponding blockchain, so they remain in full control of their credentials at all times.
CEX vs. DEX, fight!
Both CEXes and DEXes have their own advantages and drawbacks that you should be aware of before choosing one or the other.
Ownership of credentials: This was briefly introduced above, and is the most obvious difference. While in CEXes the exchange is the custodian of your keys and your funds, in DEXes every order and every transaction is done directly by the user. Consequently, DEXes support the use of hardware wallets, and give you full control and responsibility over your keys. But with great power comes great responsibility, which means that if you lose control of your keys or your seed phrase, you immediately lose access to your funds without anyone being able to recover them.
Liquidity: Traditionally, CEXes have been more liquid than DEXes, although this is gradually changing. For now though, CEXes have more users than DEXes, which translates into them having more liquidity in their platforms. Also, when trading on a CEX you’re only allowed to trade the tokens listed by the platform, which makes it easier to match orders, and for the corporation behind the exchange to provision the system with additional liquidity if needed by adding funds for their hot wallets.
That said, the gap between CEX and DEX liquidity is narrowing, because increased interest in DeFi has resulted in a spike in DEX users. Also, many DEXes are becoming what we call “Automatic Money Makers”, which make use of liquidity pools, making liquidity less of a problem.
Token pairs: DEXes enable true peer-to-peer exchanges between their users. As long as two users are willing to exchange one asset for another, these token pairs will be supported by the exchange. On a CEX, however, tokens need to be explicitly listed for users to be able to trade them. CEXes need to implement the pair exchange to support these token trades, limiting the tokens that can be traded on them.
Ease of use: CEXes are full-fledged trading platforms. They are an interface between the different blockchains and their users. The fact that there is a single entity operating the platform and orchestrating orders and transactions with the market means that they can build features that are hard to code in a decentralized manner, using smart contracts (such as limit orders, stop losses, and other cool features from traditional financial markets).
Also, through their centralized platforms CEXes usually offer the direct purchase of tokens using fiat money. This is why they are so convenient for users looking to make their first crypto investment. In spite of there being ways to achieve this, DEXes in general do not support exchanges between crypto and fiat, which implies that someone looking to use a DEX needs to already own some crypto.
Security: This is a huge win for DEXes. It’s no secret that centralized exchanges have been hacked multiple times. Delegating the custody of your keys to the exchange lightens the burden of key management from you, but increases the risks (and the rewards) in the centralized exchange. While with DEXes an attacker needs to compromise the keys of every user to gain access to their funds, in centralized exchanges an attacker can gain access to all the funds in the exchange just by being able to hack the platform and compromise the keys of the hot wallets used to manage and guard users' funds.
Privacy and KYC: Regulators have an easier time regulating CEXes when compared to DEXes, because as their name implies they’re run by a single central entity. Regulators in almost every country in the world force CEXes to impement KYC (Know Your Customer) protocols for users to prevent money laundering and other illegal activities. Thus, in CEXes you are not trading privately anymore: the exchange knows each and every transaction you make, and may even need to inform the state of all your transactions. This is not the case for DEXes, where all you need to start trading is an identity in the blockchain and some tokens to exchange.
Fees: CEXes are significantly more expensive than DEXes. For DEXes the blockchain is their main infrastructure, while CEXes need to operate their own system which is also the one responsible for keeping your keys safe. These services need to be paid for in some way, which jacks up the size of the fees they charge,
How to build a DEX
You now have a clear view of the advantages and disadvantages of DEXes and CEXes. But there are also slight differences between different DEX platforms, depending on how they’re implemented. There are mainly three different approaches for implementing DEXes:
Using an on-chain order book. In this design, every transaction is written in the blockchain. Not just the actual purchase or exchange between user balances, but also user orders, i.e. user requests to buy or sell. It is the ultimate decentralization of exchange platforms. However, every operation needs to be completed on-chain, with its corresponding high cost and scalability limitations. Some examples of DEXes that use an on-chain order book are Bitshares and StellarTerm.
An alternative to this is to use off-chain order books. In this case, user orders are collected and matched off-chain, while the final transaction is settled on-chain. Since orders aren’t stored on-chain, this method can run into some of the security risks of centralized exchanges, but it doesn’t have the limitations of on-chain order books. In this approach, we trade performance and cost for decentralization (often a huge dilemma in the blockchain and crypto space). Examples of DEXes that use off-chain order books are Binance and EtherDelta.
Finally, we have the new sheriffs in town, Automated Market Makers (AMM), which forgo order books all along. With order books if someone wants to exchange token A for token B, there needs to be someone with A that is willing to trade B for an agreed-upon price. Without enough volume in the exchange this can be extremely hard. AMMs remove the need of counter-parties for orders to match, and introduce algorithms to set the price, letting you trade A for B regardless of whether there’s someone on the other end of the trade. This is facilitated through the liquidity pools we mentioned above. Briefly, platforms that use liquidity pools pay their users interest in exchange for keeping their funds in the smart contract that operates the exchange, so they can be tapped for trades. In this approach, individual users are playing the role of financial institutions in traditional markets, where they ensure that the market stays liquid at all times.
Cool, right? In practice, this is implemented in a smart contract that maintains user pools, pays them an interest rate for their funds, receives the trade orders from users, and automatically executes them against the pool if it has the required funds. AMMs also require every transaction to be performed on-chain in order to interact with the platform. This will have an impact in terms of performance and cost, as transactions need to be made in L1, which means slower throughput and higher feest. Some examples of AMMs in the Ethereum blockchain are Uniswap and Sushiswap.
DEXes in action!
The first premise of a DEX is that it’s easy to understand, but not the easiest DeFi service to use. Let’s illustrate this with a quick walk-through of how to perform a token exchange with Uniswap.The first thing that needs to be done is to get our hands on some Ether. Even if we don’t want to exchange Ether, we’ll need some to pay for the transactions required to place the order and execute the trade in the system.
Once we have our wallet full of Ether, we can go to Uniswap and connect our wallet, for instance Metamask.
With our wallet connected we can start swapping (i.e. trading or exchanging) tokens right away. Uniswap will find the most efficient swap to go from one asset to the other according to the liquidity available in the pool. To perform any trade we’ll have to pay a few fees: the basic fee to pay for gas to execute the transaction in Layer 1, and an additional fee to pay for liquidity providers, which are staking their tokens to add liquidity to the system and make our trades possible.
We sign and submit the transaction:
Then we just have to wait for the transaction to be executed in the smart contracts and for the swap to become effective, and we are good to go.
But there’s still more… L2 DEX
Uniswap is built on top of Ethereum’s L1. But what if we don’t want to pay for Ethereum’s large fees, and worry about whether our transactions are going through or not when the network is congested? To overcome this issue, different projects that build DEXes on Layer 2 are emerging.
A good example of this type of DEX is MetisSwap. MetisSwap is a Layer 2 Decentralized Exchange application built on Metis Layer 2 Beta Testnet.
If you recall from previous publications, Metis is a Layer 2 platform based on Optimistic rollups that connects to the Ethereum mainnet and adds numerous additional features to the standard L2 projects. The team behind Metis recently released the Beta version of its testnet, which includes an implementation of a Uniswap hard fork DEX called MetisSwap. As you can see in this post, using MetisSwap is quite straightforward if you know how to use other DEXes, such as Uniswap. So what exactly does MetisSwap give us when compared to other DEXes?
It’s built on Metis’s L2 platform, so instead of having to commit every swap transaction to the Ethereum mainnet and pay its corresponding fees, you can trade over L2 and pay Metis’s typical transaction fees of about 1 cent, with the enhanced performance and transaction throughput of a L2 platform. These transactions will eventually be committed on-chain through Metis’ Optimistic rollup, but this is transparent to us, which makes it really convenient to us.
Metis has built-in support for DACs (Decentralized Autonomous Companies), which are able to seamlessly create their own tokens. So if you are looking to launch your own crypto project and you want to allow your users to exchange your tokens, you don’t have to worry about creating your own ERC20, having your token listed on an exchange, or waiting for there to be enough liquidity for your token to be exchanged. With MetisSwap, you can create your own token in a few clicks, and start exchanging it for other tokens over L2 without having to write a single line of code.
In other words, MetisSwap offers all of the built-in features of Uniswap but with the advantage of using a L2 platform, and with the added bonus of allowing you to mint and swap your own token as desired.
Closing words
DEXes have seen an increase in interest since the surge of DeFi use cases. Users want to be able to swap their tokens seamlessly without having to rely on third parties, and there are multiple ways to do so. That includes the fully decentralized approach of an online order book and the innovative approach of a Layer 2 AMM, which removes all of the complexity and limitations of more traditional L2 approaches, providing the perfect setup for DeFi users without deep technical knowledge.
Layer 2 DEXes will be able to take DEXes much further when it comes to matching ease of use, convenience, and feature richness of CEXes...with the added security that comes with decentralization. Stay tuned, the future looks bright!