0 minsPublished on 1/22/2024

What is a decentralized exchange (DEX)?

Read our primer on decentralized exchanges, their advantages over centralized exchanges, and how they benefit the crypto ecosystem.

By Mrig P

What is decentralized exchange

Disclaimer: The following is for informational purposes only and should not be construed as financial advice.

Centralized exchanges (CEXs) make it easy to buy and sell crypto using fiat currency. But despite their ease of use and convenience, CEXs have a few downsides including vulnerability to hacks, technical failures, and lack of transparency. This is where decentralized exchanges (DEXs) come in.

But what are DEXs and how do they work?

In this article, we’ll discuss everything you need to know about DEXs and how to use them.

What is a DEX? 

A DEX is an application built on top of one or more blockchains that enable peer-to-peer transactions. DEXs allow users to trade and exchange cryptocurrencies without a centralized financial intermediary. 

Unlike CEXs, these crypto exchanges are non-custodial, meaning the user retains ownership of their assets and controls what happens to them. Some of the most popular DEXs include Uniswap, dYdX, Serum, Curve and PancakeSwap.

How do decentralized exchanges work?

On DEXs, traders interact with self-executing smart contracts (codes that trigger various outputs when given certain inputs) to store funds and conduct trades.

A picture showing the different types of decentralized exchanges.

There are three types of DEXs: order book DEXs, automated market makers (AMMs), and DEX aggregators. All of them allow users to trade tokens through their smart contracts but they’re based on slightly different principles. We’ll dive into how each of these work below.

Order book DEXs

Both crypto and fiat CEXs operate based on the order book model. An order book consists of an electronic ledger that compiles all the buy (“bid”) and sell (“ask”) orders and a “matching engine” to connect buyers with sellers based on the bid price. 

Order books also enable users to place limit and stop orders, which are trading terms for being able to buy or sell an asset at a specified price.

There are two kinds of order book DEXs:

On-chain order books

On-chain order books like Stellar are directly hosted on the underlying blockchain network and automatically execute an order when two orders intersect in price.

Off-chain order books

Off-chain order book DEXs like IDEX host order books on a centralized entity outside of a distributed ledger and update the blockchain for each transaction almost instantaneously with reduced gas fees.

The biggest downside to the order book model is that it’s ideal for highly liquid markets. There should be enough buyers and sellers who are willing to execute a trade at a certain price, otherwise the order won’t be executed.

Automated Market Makers (AMMs)

Automated Market Makers (AMMs) are systems that allow users to execute trades without relying on buy/sell requests. 

They do this using liquidity pools—collections of crypto tokens—and an algorithm that sets token prices based on the ratio of tokens supplied to the pool. 

But where do these tokens come from?

The tokens are provided by the platform’s users, also known as liquidity providers (LPs) or market makers, in exchange for rewards that are proportional to the number of tokens they contribute.

Anyone can contribute tokens to these pools, but to ensure the exchange doesn’t have an excess of one token and too few of another, LPs must deposit an equal value of two tokens. 

A picture showing how Automated Market Makers work.

If you want to contribute $100 worth of ETH to an ETH/DAI pool, for example, you also need to contribute $100 worth of DAI

A majority of the AMMs derive this ratio using the constant product yield formula (k), which states the product of the two liquidity pool tokens (x*y) should be the same before and after the trade to maintain a balanced pool.

In the above example, k = 100, which means that the AMM should buy more DAI if it loses ETH and vice versa. If this doesn’t happen, the token value will change, creating an arbitrage opportunity and a loss for the liquidity provider. 

Most AMMs, such as Uniswap and Bancor, use this constant yield formula to maintain a fair price that can’t be influenced by a centralized entity. 

The only caveat is that such AMMs are prone to “impermanent loss”, so other AMMs like Curve adopt better mathematical models to maintain liquidity and prevent this loss. 

For a full explanation of impermanent loss, see our article Yield farming vs staking.

DEX aggregators 

DEX aggregators, also called liquidity aggregators, have exploded in growth since 2020 as they solve a unique but prevalent problem that other DEXs encounter. 

Decentralized exchanges can’t handle a higher order volume as large trades may cause slippage—a difference in price when the order is placed vs when the order is executed—as the purchased crypto asset drops in volume against its pair. 

DEX aggregators vet all connected DEXs to find the best possible prices and give the option of split trading—splitting a single trade across all multiple platforms—to reduce slippage risk. 

Let’s say you want to exchange token A for token B. Instead of manually working out the best way to split a trade, you can use a DEX aggregator like 1inch to split a large volume trade into multiple chunks and reroute them through multiple exchanges to arrive at the best price.

How to use decentralized exchanges

Here are a few simple steps to get started with a DEX.

1. Choose a wallet

The main thing you need to get started is a crypto wallet that’s compatible with the decentralized exchange you want to use.

For example, if you’re using Uniswap, you need a Metamask wallet, which is compatible with Uniswap and most decentralized exchanges that run on Ethereum and Ethereum-compatible blockchains like Polygon and Binance Smart Chain.

But if you’re using a DEX that’s built on top of other standalone blockchain networks like Solana, you’ll need to use a SOL wallet like Phantom.

Need help choosing a cryptocurrency wallet? See our article How to choose a crypto wallet.

2. Buy cryptocurrency

Once you set up your wallet, you can use MoonPay to buy Ethereum as your base currency. Ensure that you enter the correct wallet address before transferring funds.

3. Connect wallet

Go to the DEX that you want to use and connect your wallet.

A picture showing a DEX interface on rhino.fi

4. Execute trade

Trade Ethereum for the coin you want to get. You’ll have to indicate the price you’re willing to pay if you’re using an order book DEX. If you’re using an Automated Market Maker, then just choose the crypto you want to buy.

5. Sign wallet transaction 

Lastly, authorize your wallet transaction. When the trade is successful your balance will be updated.

There are a lot of DEXs out there, but you should find the one that best suits your requirements and risk appetite. 

DeFi Swap

DeFi Swap is built atop the Binance Smart Chain. With its upcoming interoperability feature, users will soon be able to swap tokens on BSC with tokens on other blockchains. 

DeFI Swap also offers opportunities to earn passive income from yield farming and staking the platform’s native DeFi coin.

Uniswap

Uniswap, the ETH-based DEX, has solved the liquidity problem—the ease with which one token can be swapped for another—that other DEXs have failed to grapple with.

As we saw earlier, most DEXs rely on buyers and sellers to swap tokens, determine their price, and create liquidity. 

Uniswap, on the other hand, uses a constant equation (k=x*y) to solve the same problem, eliminating the need to rely on buyers and sellers to create liquidity. 

Uniswap is currently the largest DEX, with a market share of over 64% and more than $3.7 billion TVL. Its main downside, however, is that sometimes gas fees can be quite high since it runs on Ethereum.

PancakeSwap

PancakeSwap is a Uniswap clone, but it runs on the Ethereum-compatible Binance Smart Chain and focuses on BEP-20 tokens: Binance’s token standard that specifies how the tokens can be used and who can use them. 

Since BEP-20 tokens are similar to ERC-20 and Binance’s BEP-2, they’re compatible with both Ethereum and Binance. 

PancakeSwap offers some investment opportunities apart from the usual yield farming and staking. Plus, users get the benefits of using Uniswap without having to pay exorbitant gas fees. 

For example, users can participate in a lottery on Pancake swap and win exciting rewards if their ticket matches the four-digit lotto number in the exact order. 

Apart from lotteries, users can also take part in Prediction, a game that gives users rewards if they correctly predict whether a token value will go up or down. 

In short, Pancake swap can be a great choice if you want to lower your transaction fees and win rewards from taking calculated risks.

Curve

Curve was launched in 2020 to create stable liquidity pools consisting of only stablecoins like USDC and DAI to reduce volatility. 

The exchange also rebalances its liquidity pools by selling excess tokens at discounted prices so its assets won’t be subject to slippage risks. 

For instance, if there was more DAI in its liquidity pools than USDC, the pool would sell DAI at a slight discount to incentivize purchases and restore balance. 

Another important feature that attracts users to Curve is its composability. That means users can use Curve’s assets to gain rewards outside of its ecosystem. 

For example, if you lend ETH, DAI or USDC on Compound from the Curve platform, you’ll receive cTokens — cETH, cDAI or cUSDC — which automatically generate interest over a period of time.

1inch

1inch is an aggregator that enables crypto traders to access a wide range of trading pools so users can find the best deal for the token pair they’re looking to trade. 

Instead of manually working out the best price for a trade, users can use 1inch to work out the hard part and profit from the price difference. 

Think of it as a service like Google Flights, which automatically fetches data from numerous airlines to get users the best price on their flight tickets. 

If a trade involves exchanging more than one pair of tokens, the 1inch protocol will split the transaction across multiple DEXs to get its users the best price.

But its functionality doesn’t end there. The platform also has a limit order protocol that automatically closes a trading position if the trade value falls below a certain set limit.

What are the benefits of decentralized exchanges?

Although DEXs are non-custodial and give users full control over their assets, that’s not the only reason they’re popular. 

Here are some other significant benefits of trading crypto on DEXs.

Token availability 

Since there are no limitations regarding which tokens can be listed on exchanges, DEXs can include any token minted on the blockchain they’re built upon.

Anonymity 

Unlike centralized exchanges, which collect users’ personal information, DEXs don’t have Know Your Customer requirements. This allows users to execute trades without disclosing their personal information. 

Reduced counterparty risk

Counterparty risk is the probability that one of the parties involved in the trade may default on their obligation. 

Since assets are directly transferred between digital wallets based on smart contract execution, DEXs aren’t prone to this risk.

DEX risks and considerations

While most DEXs eliminate centralization and KYC, they’re still vulnerable to risk as they’re built using code. 

Smart contract risk 

Smart contract risk can take the form of an economic exploit in which the attacker profits from manipulating market conditions or logic errors in the code. 

The latter is when there’s a logical loophole that adversaries can profit from. 

The best example of this is a reentrancy attack in which the attacker drains funds from the DEX as it doesn’t update its state before transferring crypto to the user’s wallet

Imagine there are two contracts, A and B, in which B is the malicious contract, and A has 10 ETH in it. 

B asks A to transfer 1 ETH to its wallet. Since A doesn’t update its balance before transferring funds, B exploits this to call another function and restart the process. 

When A checks B’s balance before the transfer, it finds that B still has only 0 ETH and transfers 1 ETH again, when in reality, B has 1 ETH. 

The same process repeats until an exchange is completely drained of funds. Famous exchanges like Uniswap and Lendf.me have fallen prey to this attack and lost about $25 million in 2020. 

Economic exploits are more subtle than logical errors. There aren’t any loopholes to exploit here, but if the attacker possesses enough economic knowledge they can use this to unfairly profit at the expense of the contract. 

The bZx attack is one such example. The attacker used a flash loan to borrow ETH and used a portion of it as collateral for a Wrapped Bitcoin (WBTC) loan. This maneuver reduced ETH’s price and inflated WBTC’s price. (The reason for the inflation is that the high volume of currency trades or purchases implies more demand).

Then, hackers took advantage of this inflated price to exchange WBTC for more ETH than they initially borrowed, leaving them with higher ETH than before.

Liquidity risk 

Liquidity refers to the ease with which one token can be swapped for another. It’s directly proportional to the number of crypto liquidity providers—users who pool their assets in the DEX’s liquidity pool to facilitate the execution of a trade.

If a DEX doesn’t have a significant amount of these liquidity providers, users can’t easily trade token pairs, which negatively impacts trading volume. 

This is called “liquidity risk”, and one of the main reasons for its occurrence is the possibility of “divergence loss” or impermanent loss (explained above).

What is divergence loss?

Simply put, it’s the difference in a token’s value between when it’s being held in a liquidity pool vs simply being held on the blockchain (HODLing).

When you HODL, your tokens remain at market value. When you put your tokens in a liquidity pool, however, you can also get returns. 

Due to market fluctuations, this difference may turn out to be a negative value, which means the user would have been better off HODLing their tokens instead of locking them in a liquidity pool. 

Front-running risk 

In the centralized exchange world, front-running refers to the process of gaining an unfair market advantage with prior knowledge of upcoming transactions. 

While this activity involves insider information similar to what you might find in the centralized finance (CeFi) world, it’s slightly different in DeFi

In DEXs, front-running is done by slipping in two attacks between a normal trade using bots that read and interact with the mempool—the place where unverified transactions sit on the blockchain. 

The result is a slippage loss for the unsuspecting trader and an arbitrage opportunity that helps an attacker profit off the trade. 

Typically, this is done by setting higher gas fees on the attack trade so the blockchain would mine the transaction right before the normal trade. 

Centralization risk 

Centralization risks refer to single points of failure within a system that can become a lucrative attack for hackers. 

One of the most prominent centralization attacks are cross-chain bridge attacks. 

Cross-chain bridges, as the name suggests, are protocols that connect different blockchains and allow users to move funds from one blockchain to another easily. 

These work by freezing the crypto on one side of the chain and unfreezing them on the other. Naturally, this means they carry liquidity, making them a prime target for hacker attacks. 

Other attacks include manipulating the matching engines which connect buyers with sellers, also called front-running attacks and rug pulls.

Network risk

Since DEXs are built atop a blockchain, they take on the properties of the underlying blockchain itself. 

Solana has been plagued with downtime issues so when it goes down, so do the DEXs operating on it. 

Ethereum has network congestion and scalability issues, so DEXs built on it will also be slow.

Token risk 

As DEXs allow anyone to create a market for any token online, they have also become a cesspool for malicious tokens and rug pulls. 

A rug pull is when the project developers empty the pool of exchanged currency once a significant amount of investors have exchanged their cryptocurrency for a malicious token. This causes the value of the token to plummet to zero. 

One of the most significant rug pull attacks is the squid token attack in 2021, in which scammers stole $3.3 million.

Final thoughts on DEXs

DEXs are popular primarily because they give users complete control over their assets. 

While the older generation of order-book DEXs were limited by liquidity issues, newer generation of DEXs called AMMs solve that problem through liquidity pools. 

These DEXs also provide the opportunity for users to earn passive income by contributing to these pools, which also contributes to DEXs’ growing popularity.

Begin your DeFi journey with MoonPay

DeFi can help you earn interest and grow your crypto portfolio. To get started, simply buy Bitcoin, Ethereum, or any other cryptocurrency via MoonPay using your credit card or your preferred payment method.

MoonPay also makes it easy to sell crypto when you decide it's time to cash out. Simply enter the amount of the token you'd like to sell and enter the details where you want to receive your funds.

Mrig P
Written byMrig P

You might also like