Published 20th July 2022
DEXs: A Complete Guide
Decentralised exchanges (DEXs) have been a staple of the DeFi space for quite some time now, but what are they? Here's our complete guide to DEXs.
DEX: Decentralised Exchange
DeFi: Decentralised Finance
LP: Liquidity Provider
IL: Impermanent Loss
KYC: Know Your Customer
AMM: Automated Market Maker
EVM: Ethereum Virtual Machine
What is a DEX?
A DEX, which stands for a ‘decentralised exchange’, is one of the most used DeFi (decentralised finance) tools currently available in the web3 space. Before we delve deeper into what a DEX is, it’s first useful to understand how more traditional/centralised exchanges function to see the comparisons with a DEX.
CEX vs DEX
As an example, let’s look at Coinbase, a very widely known and used centralised cryptocurrency exchange. Coinbase provides many different markets that users can buy/sell (including BTC, ETH, XRP and LTC to name a few) and charge a fee for providing this service.
The user trades the assets by setting buy/sell orders within the exchange’s ecosystem and Coinbase can control all aspects of the user’s activity (lock your account, cancel a trade, disable withdrawing, choose what tokens they provide an exchange for). However, centralised exchanges like Coinbase are also responsible for the users actions if they are laundering money or using the service in other illegal ways (which Binance is currently being investigated for, although they refute the claim).
To help them reduce the chances of their services being used for illicit purposes, all exchanges implement a know your customer (KYC) system which requires users to submit personal documents for review.
On the other hand, DEXs remove the requirement of a centralised company providing the service which means that users can bypass restrictions that traditional exchanges face; any token can be added and exchanged, there is no KYC, no single central party controls the exchange process and users aren’t paying a company for the service.
Very simply, a DEX functions by providers putting up both sides of a token’s trading pair in a smart contract (e.g. ETH & USDC) and then other users can exchange one token for the other by using the smart contract.
Whilst the idea of a DEX initially spawned in 2015 following the launch of Ethereum and their smart contracts, it was in 2017 when DEXs really came to fruition as DeFi started to emerge with the introduction of liquidity protocols and ICOs.
Currently, there are 3 forms of DEXs:
Automated Market Makers (AMM) – an AMM automatically swaps tokens at current market price, the most well known AMM being Uniswap.
Orderbook DEX – platforms like dYdX where users can set buy/sell orders similar to traditional exchanges.
DEX aggregators – these combine all available DEXs to get the best price for users as on 1inch.
Swapping tokens (AMM)
Going into details about how swapping one token for another works on an AMM DEX like Uniswap is a bit more complex, but follows on from our explanation in the previous section. We’ll use ETH-USDC as an example trading pair:
Firstly, there needs to be a smart contract capable of swapping tokens. This contract holds both of the tokens which make up the trading pair, ETH & USDC, which is provided by liquidity providers (LPs) and contained in a liquidity pool in which the smart contract can access.
The contract also needs to get information from an oracle about what the current market value of each asset is, essentially how many USDC tokens is an ETH token worth at the time the swap is being executed? Uniswap uses their own custom oracle which weights the price over the last few blocks, instead of an oracle provider like Chainlink.
Finally, when the user hits swap they need to approve that the tokens in their wallet can be accessed by Uniswap’s smart contract as well as generating their own transaction to interact with the smart contract.
The transaction will contain information about their slippage tolerance (how far the price can move from the time they confirmed an amount to the time the swap actually happens), timeout information (if the transaction takes too long it automatically cancels) and other info such as which pool they want to swap with.
Once the transaction has been processed onto the blockchain, the smart contract calculates the swap, and the wallet which initiated the transaction receives the correct amount of swapped tokens back.
Liquidity is one of the major factors in a DEX for it to operate. For users to swap, they need to have liquidity to swap with. If there aren’t enough tokens in the pool, the users swapping might not receive the fair market value for the tokens as their swap will drastically change the pool’s token ratio.
This is the reason why new token launches use rewards as an incentive for users to provide liquidity. Sometimes the project provides a large number of tokens into the pool themselves as they need to have the pool filled with enough tokens on both sides to allow users to easily swap without impacting the price too much.
‘LPers’ must also provide a 1:1 ratio at current market value. If you want to deposit 1 ETH into the ETH/USDC pool, you’ll need to also deposit the equivalent value of ETH in USDC. This is to stop the pools being unbalanced which might impact swapping in one direction, although some protocols such as Bancor have found novel solutions which allow users to provide single sided liquidity.
Liquidity providers provide the tokens to the pool for a fee, similar to how traditional exchanges work. Whenever someone swaps between the pairs they are providing tokens for, they receive a small fee (0.3% of the trade on Uniswap currently) to incentivize them to keep providing liquidity others can use.
Providing liquidity for users to swap in return for a fee seems like a risk free way of accruing interest. Whenever someone trades, liquidity providers receive 0.3% ÷ total pool size, what’s not to like?
However, as with everything there are still risks and other factors which need to be assessed. The main issue with providing liquidity is something known as impermanent loss (IL). When one token is much more volatile (goes up or down quicker) than the other asset, LPers will lose to impermanent loss.
Essentially, whenever someone trades a token that you are providing liquidity for, they are giving you some more of one token (USDC) in order to take the other token (ETH). This means you end up with more USDC and less ETH, and if ETH goes up in price you are effectively selling ETH as you now have less ETH but more USDC stablecoins.
To put numbers to it, if ETH was valued at $1,000 and you supplied $500 worth of ETH and $500 worth of USDC, but then the price of ETH goes up by $100 (or 10%) the liquidity providers total value of their holdings would go up to $1,048.81, whilst the person who simply held the 500$ worth of ETH and 500$ worth of USDC holdings would be valued at 1050$. The liquidity provider would’ve suffered a 0.11% IL.
Over time, these constant price changes stack up and can cause a larger amount of impermanent loss. It’s known as impermanent loss as the providers will likely gain back their lost funds and more if they provide to the pool for long enough through fees, so long as one of the tokens doesn’t drastically decrease in value.
If a liquidity provider wants to withdraw from the pool, they won’t get back the exact same amount they deposited. Instead, they’ll get the new ratio. If ETH has gone down in value and USDC has stayed the same, you’ll end up with more ETH and less USDC.
If you’d like some further reading, there are some more complex methods that DEXs are now implementing to help reduce IL that we won’t touch upon in this guide.
One of the most common issues new DEX users will experience when simply swapping is something called ‘front running’ (also known as a sandwich attack). This occurs when a user submits a swap with a large slippage tolerance. This happens regularly if a user is attempting to swap into a token with a price that is fluctuating drastically in a short period of time.
The user might find that their swap is constantly reverting (cancelling) because the price moves past their slippage tolerance, which is by default 0.5% on Uniswap. They then increase the slippage to 5%+ and resubmit the transaction, maybe with slightly higher gas to help it execute quickly.
In the period where the transaction is submitted to when it can execute, a bot detects the slippage tolerance based on the transactions data whilst it’s stored in the mempool (where transactions get stored while waiting to be assigned to a block).
The bot then queues up a transaction with higher gas than the user’s transaction (so the bots transaction is processed first) to buy the token to just below their slippage threshold (maybe 4.5% for a 5% slippage tolerance) which means the users transaction goes through, but the user gets back less tokens than expected.
The bot then proceeds to sell the same amount it bought for a profit immediately after the user’s transaction has processed, which gives it an instant profit and returns the market price back to expected level. As long as the bot makes more than it pays for in gas, it’s a successful front run attack.
You should always try to use as low as possible slippage tolerance in order to stop this happening to you.
Let’s have a look at the biggest DEX of them all, Uniswap. It’s an AMM DEX with a simple UI that is very user friendly. The only fee is one which goes to the liquidity providers, the Uniswap UI code is open source and their smart contract code is also available for all to view on blockchain explorers (for example, you can view the Uniswap swap router). This means that anyone can come along and make a copy of it.
The UNI token
So how does Hayden Adams—the creator of Uniswap—make money? It may seem like the entire platform is non monetised but of course no one does all that work for free. Instead, Uniswap came up with a different revenue model which fits the current crypto markets very aptly: The creation of the ‘UNI’ token.
Uniswap airdropped 400 UNI tokens to all Uniswap users who had used the DEX before September 1st, 2020. At current value that is worth around $2,062 (at its peak of $42 the airdrop was worth a whopping $16,800).
The idea behind this token was multipronged: It allowed the company to have a reserve of tokens they could sell in order to make money (~20% of supply), the UNI token acted as a governance token with access to a UNI treasury, and they also claim (but have yet to implement) that the UNI token can be staked to then earn fees from across the entire DEX to help incentivise people to buy and hold UNI.
The main aspect Uniswap focused on was the governance utility. Users could submit proposals around issues such as launching on other chains, distributing governance controlled treasury funds, changing the fee and many other initiatives. This process required 1% of token supply to be delegated to submit a governance proposal, then 4% of supply had to vote ‘yes’ on the proposal before it was passed.
How Uniswap has led the way for other DEXs
Following Uniswap’s booming success, many other projects started to copy the open-source code that Uniswap’s UI and smart contracts ran on. The main competitor which arrived on the scene was SushiSwap.
SushiSwap’s main sales point was that they were ‘a more user friendly fork of Uniswap’ as well as distributing the SUSHI token which they used to incentivise users to provide liquidity and stake tokens on their platform. SushiSwap was also one of the first Uniswap forks to move onto multiple chains, deploying a SushiSwap fork onto Polygon, Avalanche, Fantom and many more.
SushiSwap kick started their platform by performing a ‘vampire attack’ on Uniswap. They offered rewards for providing your Uniswap generated LP to SushiSwap. Their masterchef contract then had access to these LP tokens and could migrate all liquidity by redeeming the Uniswap LP tokens for their base tokens and then staking on SushiSwap.
In less than a week, they managed to migrate $1billion worth of assets on their platform from Uniswap, showing just how competitive the environment can be.
Most newly created layer 1 and 2 EVM chains also quickly get their own Uniswap clone, such as Quickswap on Polygon, Pangolin on Avalanche and PancakeSwap on Binance Smart Chain. These clones can copy over Uniswaps UI and convert the contract to be chain compatible. Most of the time, users might not even realise they are using a Uniswap clone as the forked version is heavily modified like PancakeSwap.
Understandably, DEXs have incredible potential. From the benefits gained by being decentralised, to the immutable and open-source aspect of the blockchain. They allow users to regain some of the benefits and control lost with centralised exchanges and provide an entirely new financial instrument – the likes of which have never been seen before in the financial sector.
We may be seeing the first iterations of DEXs, however it’s highly likely that the innovation going on within the sector will expand. Most importantly though, due to their open-source nature, development is unhindered by the usual restraints seen in traditional finance.
This piece of work does not contain investment advice. None of the information above should be considered as advice or recommendation. Readers looking to invest should carry out their own research and make sure they are aware of the risks associated with trading.