The Evolution of Trading: Decentralized Exchanges (DEX) in the Web3 World

This article serves as a guide for those new to the DeFi space, offering insights into the inner workings of decentralized exchanges (DEXs) and the nuances of these platforms.

Decentralized exchanges (DEXs) represent a revolutionary platform for cryptocurrency trading, operating without the need for third-party intervention. These exchanges are either community-managed or operate autonomously, epitomizing the peer-to-peer (P2P) trading ethos. Smart contracts on blockchain networks monitor transactions, significantly reducing operation fees by eliminating intermediaries.

Understanding the Basics

Liquidity

In traditional terms, liquidity refers to how quickly an asset can be traded at its market value. High liquidity indicates a strong buyer interest at the seller's price, while low liquidity suggests a lack of buyers.

Consider the scenario of selling a vintage, somewhat rusty Dodge Charger. Weeks pass with no buyers, highlighting the car's low liquidity. However, if it sells on the first day, that indicates high liquidity. Fear not for the Dodge Charger; there's always someone who appreciates the value of an American muscle car legend.

A liquid market is characterized by the ability to easily buy and sell assets at fair prices, supported by strong demand and sufficient supply.

Market Makers and Market Takers

A market achieves liquidity when token exchanges are swift and efficient. For any exchange, sellers must be matched with buyers and vice versa. Absence of a match makes the transaction impossible.

Exchange users fall into two categories:

  • Market Makers: Users who offer to buy or sell a token.

  • Market Takers: Users who accept these buy or sell offers.

For a transaction to occur, a maker must list an asset for exchange, essentially creating market liquidity.

An offer by itself does not guarantee a successful transaction; a taker must accept and complete the offer by exchanging their own asset for the maker's.

Thus, market makers provide liquidity, while market takers consume it.

Large market players or even the exchanges themselves often take on the role of market makers, contributing significantly to the trading ecosystem's liquidity.

This streamlined introduction aims to demystify decentralized exchanges for budding IT entrepreneurs venturing into the DeFi arena. With a focus on community-driven operations and the elimination of middlemen, DEXs offer a more accessible and equitable trading environment, essential for anyone looking to navigate the complexities of the cryptocurrency market.

Liquidity providers

Liquidity providers are crucial participants in the decentralized exchange (DEX) ecosystem, offering their assets to the exchange's reserves. This reserve is pivotal for facilitating swift token transactions. In return for their services, liquidity providers earn transaction fees, a process often referred to as liquidity mining or market making. These fees are calculated as a percentage of the transaction value and vary based on the available liquidity and transaction volume.

It's important to note that market makers also serve as liquidity providers. Their contributions are essential for enhancing the platform's appeal as a trading venue. Consequently, market makers often benefit from lower transaction fees.

Market takers leverage the liquidity provided by the exchange for quick and efficient asset exchanges, for which they pay a higher transaction fee.

DEX vs. CEX

The advent of DEXs marked a significant shift from centralized exchanges (CEXs). CEXs are managed and administered by a single organization acting as the intermediary in fund exchanges between users.

Most CEXs resemble traditional financial services, like the New York Stock Exchange, making their interfaces more familiar and user-friendly for beginners. They primarily operate on an OrderBook model, where all transaction and balance information is stored within the exchange's database.

CEXs enable the exchange of fiat currencies for cryptocurrencies (and vice versa) or the trading of one cryptocurrency for another, such as BTC for ETH. They support more complex trading instruments, like margin trading and limit orders, thanks to the OrderBook model, which maintains all transaction data internally.

However, CEXs require separate processes for various asset operations, often imposing fees for deposits, withdrawals, trades, and storage. They also have the authority to restrict user actions, such as imposing withdrawal bans or deposit limits.

DEXs, based on Automated Market Maker (AMM) models, address issues related to transparency, security, and high fees inherent in CEXs. Without a centralized intermediary to collect fees, DEXs enhance overall liquidity through collective pooling, offering a more secure and transparent trading environment for users. This innovation not only democratizes trading but also aligns with the ethos of decentralized finance, providing a more accessible platform for IT startups navigating the complex world of cryptocurrency trading.

Types of DEXs

Decentralized exchanges (DEXs) can be broadly classified into two types based on their underlying mechanisms:

  1. AMM (Automated Market Maker) or Liquidity Pool-Based Exchanges: These platforms automate the trading and pricing process. They utilize liquidity pools to facilitate trades, allowing for instant transactions without the need for traditional market makers.

  2. Order Book-Based Exchanges: Similar to centralized exchanges (CEXs), these platforms allow users to place buy or sell orders. The key difference lies in the fact that all transactions are processed on the blockchain network. The order book can be implemented entirely on-chain using smart contracts, or through a hybrid approach where computations are done off-chain but transactions are recorded on-chain. The hybrid model aims to minimize blockchain entries to reduce gas fees.

Challenges in Decentralized Trading

Decentralized trading faces a few significant challenges:

  • Price Slippage: This occurs because transactions are not instantaneous; they are processed sequentially. By the time a transaction is executed, the actual price of an asset may have changed due to the actions of other traders.

  • Impermanent Loss: Liquidity providers can experience a loss in potential profit if the price of an asset increases significantly more than the earnings provided by the exchange for supplying liquidity. Essentially, if liquidity providers had sold their assets directly in the market, they might have earned more than what the exchange offers for participating in the liquidity pool.

  • Arbitrage: While arbitrage can have a positive effect by equalizing asset prices across exchanges, it can also introduce negative effects that impact token exchanges among regular users.

Overview of DEX Types

Order Book DEXs

An example of this type of exchange is dYdX, which operates similarly to CEXs. Users can place orders at specific price limits or at market prices, and user assets are stored in the exchange's wallet. This type allows users to deposit and withdraw assets. However, order book DEXs are rare due to liquidity challenges and the difficulty of ensuring fast order execution. To overcome slow order execution, these exchanges often need a large user base creating liquidity through their orders. Some exchanges simulate activity at launch to give the appearance of liquidity and order fulfillment, encouraging real user participation.

AMM DEXs

Examples include Uniswap, Balancer, and Bancor. Each platform offers unique features to address specific issues or multiple challenges simultaneously. These platforms employ various DeFi protocols to solve their unique set of problems, enhancing user experience and efficiency in decentralized finance.

This breakdown provides a glimpse into the innovative world of DEXs, offering startup entrepreneurs in the IT sector insights into the opportunities and challenges of decentralized trading. As the landscape continues to evolve, understanding these mechanisms becomes critical for navigating and succeeding in the DeFi ecosystem.

How Real Protocols Implemented AMM-Based DEX. Uniswap V2

Uniswap stands as one of the most successful Automated Market Maker (AMM) protocols in the DeFi ecosystem. It's a decentralized protocol on Ethereum that enables direct token swaps without holding users' funds in the exchange. Utilizing Uniswap is straightforward: users send their tokens to a Uniswap smart contract and receive the desired tokens back directly from the contract.

The protocol was first introduced by Hayden Adams in November 2018 as a proof of concept for AMM. Its foundation rests on user-friendliness, gas efficiency, censorship resistance, and security.

Though Bancor initially applied the AMM concept on Ethereum, Uniswap was among the first to popularize the constant product market maker formula on an AMM-based DEX.

Uniswap appeals to both traders and casual users alike. Blockchain developers can easily integrate Uniswap swaps into their contracts, benefiting from guaranteed on-chain liquidity.

The first version of Uniswap allowed for exchanges between ETH and ERC-20 tokens. The second iteration introduced the capability to swap between ERC-20 tokens directly.

Adding Liquidity

Under this system, a liquidity provider contributes three tokens of type A and one token of type B, receiving 12.4 LP tokens from the pool in return. These LP tokens represent the provider's share of the assets in the pool.

The token pair then operates on the AMM principle, accepting one token and providing another based on the constant product formula. Importantly, creating a pair sets its initial price, as the ratio of tokens provided will serve as the baseline for future liquidity providers.

A liquidity pair is essentially a reserve of two token types, A and B, from which token prices are calculated.

Any user can create a liquidity pool and set an initial price to earn a percentage from each exchange. Uniswap charges no fees for pool creation.

Architecture

Uniswap V2 is structured around a core (Uniswap Core) and peripheral contracts (Uniswap Periphery).

  • UniswapV2Pair.sol: This core protocol contract manages the liquidity pair, holding the reserves of both tokens.

  • UniswapV2Factory.sol: This factory contract oversees the creation and storage of liquidity pairs.

  • UniswapV2Router01.sol and UniswapV2Router02.sol: These contracts facilitate user interactions with the protocol, such as adding or removing liquidity and making swaps.

Token Swaps

What if you need to swap tokens without an existing liquidity pair? This is where UniswapV2Router02.sol comes in, allowing interactions across all pairs to construct a swap route.

For example, to swap DAI for LINK without a direct pair, the protocol uses the DAI → ETH and ETH → LINK pairs to facilitate the exchange: DAI is swapped for ETH, which is then swapped for LINK.

Router02 is preferred over Router01 because routers don't hold state or token balances, allowing for safe replacement if flaws are detected or new functionality is needed. This was the case with Uniswap V2, where Router01 was upgraded to address deficiencies.

Router02's role isn't limited to constructing swap routes; it also provides methods for direct token swaps, exchange calculations, and liquidity management.

Adding Liquidity in Uniswap V2

Each UniswapV2Pair.sol smart contract manages a liquidity pair consisting of two ERC20 token reserves. Liquidity providers create a market by depositing an equivalent value of two tokens, which are then automatically locked in the smart contract. This could be a pair of ERC-20 tokens or an ETH-ERC20 pair.

For instance, Alice has USDT and 1INCH tokens and notices there isn't a liquidity pool for this pair yet. She sees an opportunity to set the exchange rate for these tokens. Deciding on a rate of 1,500 1INCH for 1 USDT, Alice creates a pool by depositing 15,000 1INCH and 10 USDT. As the pool's initial creator, Alice has the prerogative to determine the token ratio within the pool, effectively setting the price.

Now, Alice becomes a liquidity provider, with her funds locked in the smart contract. But how can she prove these funds are hers and withdraw them? This is where LP (liquidity pool) tokens come in. On Uniswap, these are referred to as UNI-V2 tokens. To identify which two tokens can be exchanged for an LP token, one can simply visit Etherscan, access the contract's reading functions, and check the addresses of token0 and token1.

When a liquidity pool is created, LP tokens are minted to represent the provider's share in the pool. Initially, Alice holds 100% of the LP tokens, also known as shares. Suppose I want to add liquidity to the same pair after Alice. I can't create an identical pair; I can only add liquidity to Alice's pair at the current rate. For instance, to add 1,500 1INCH, I'd need to contribute 1 USDT. Afterward, Alice holds 91% of the LP tokens, and I hold 9%.

Withdrawing Liquidity

LP tokens can always be exchanged back for the pool's reserves.

Uniswap V2 Adapter

An adapter is a contract facilitating interaction with Uniswap V2 contracts. It demonstrates how to engage with Uniswap V2's contracts, encompassing:

  • Adding and removing liquidity.

  • Swapping 1INCH for USDT.

The adapter's code is available for review.

Uniswap V3

Built on the same AMM principles and constant product formula as its predecessors, Uniswap V3 introduces several innovations. This third iteration promises enhanced capital efficiency, improved price oracle accuracy, and a more flexible fee structure, aiming to further optimize the decentralized exchange experience for both liquidity providers and traders. This evolution reflects the continuous improvement and sophistication of the DeFi ecosystem, offering IT startups in the sector opportunities to engage with cutting-edge financial technologies.

Concentrated Liquidity

In Uniswap v2, when LPs provide liquidity, it is distributed evenly across the price curve, covering all price ranges from zero to infinity. While this approach ensures trades can be executed at any price level, it results in capital inefficiency.

The inefficiency stems from the fact that most assets trade within specific ranges, especially noticeable in stablecoin pools with very narrow trading bands.

For instance, in a DAI/USDC pair, only about 0.5% of the pool's liquidity might be utilized within the $0.99 to $1.01 range, leaving 99.5% of the capital dormant.

Imagine depositing $100 into a liquidity pool by purchasing $50 worth of DAI and $50 worth of USDC, only for $0.5 to be actively used in trades while the remaining $95.5 sits idle. This represents a highly inefficient use of capital. However, Uniswap v3 allows liquidity providers to specify their preferred price ranges, enabling capital concentration where most trading occurs.

In v3, individual price curves are created for each liquidity provider. Overlapping ranges from different providers create a combined liquidity pool, with LPs earning fees proportional to their contribution within the specified range.

Example Scenario

Let's consider Alice and Bob wanting to add liquidity to the ETH/DAI pool on Uniswap v3, each with $10,000 at an ETH price of $1750.

Alice decides to invest her entire capital, buying both ETH and DAI to place across the full range, akin to Uniswap v2 pools. She ends up depositing 5000 DAI and 2.85 ETH.

Bob, however, opts to concentrate his liquidity within the $1500 to $2500 range, investing 600 DAI and 0.37 ETH, totaling $1200, and keeps the remaining $8800.

As long as the price fluctuates within $1500 to $2500, both Alice and Bob earn comparable fees from trades.

By investing only 12% of Alice's amount, Bob secures the same revenue potential, exposing less of his capital to risk.

It's crucial to note that as long as trades occur within this range, both Bob and Alice earn from transaction fees. However, if the price moves outside this range, only Alice continues to earn, as Bob's liquidity no longer participates in trades.

This mechanism incentivizes liquidity providers to cover a broad price spectrum with their positions. Theoretically, Bob could either spread his liquidity across more ranges for broader coverage or adjust his range as the market price shifts.

Curve: Optimizing Stablecoin Trades on DEX

One primary issue with DEXs utilizing the AMM formula, like Uniswap, is the fees and price slippage encountered during token exchanges, which isn’t ideal for stablecoin or similarly valued asset trading.

Curve Finance was the first to adapt AMM for stable token exchanges, aiming for low fees and minimal slippage. Its main objective is to simplify trades between assets of similar values, addressing a significant demand within the DeFi ecosystem due to the prevalence of wrapped and synthetic tokens that mirror the price of underlying assets.

Synthetic tokens are financial instruments representing the price movements of their underlying assets without providing ownership rights or guarantees of future delivery. Virtually any asset, including cryptocurrencies, tokens, commodities, stocks, exchange indices, or fiat currencies, can be synthesized.

Importantly, Curve Finance currently supports stablecoins pegged to the USD, Euro, wrapped/synthetic BTC (Bitcoin), and wrapped/synthetic ETH assets.

How Does Curve Work?

At its popularity peak in January 2022, Curve's Total Value Locked (TVL) exceeded $24 billion, with a monthly trading volume of over $6 billion. Despite the cryptocurrency market downturn by mid-2022, Curve remains a top five DeFi service, with more than $5.7 billion in locked funds.

Interestingly, the substantial liquidity provided by Curve enables numerous other DeFi services to leverage its pools within their ecosystems, integrating with liquidity aggregator 1inch, and major lending protocols Aave and Compound.

Curve’s innovative protocol consolidates a significant amount of stablecoins to minimize slippage and protect liquidity providers from impermanent loss.

Upon its introduction, competing with the first version of Uniswap, Curve addressed high slippage and the issue of LPs having to provide at least half of their liquidity in ETH—a volatile asset susceptible to impermanent loss.

Moreover, in its first iteration, tokens were traded solely through an ETH pool on Uniswap, requiring two transactions for an A to B token swap, thus doubling trading fees.

To enhance the liquidity of low-volume tokens, Curve introduced the concept of base pools and meta pools.

The 3pool, comprising DAI, USDT, and USDC, serves as the most liquid base pool. The allocation of these stablecoins within the pool adjusts according to market supply and demand, rewarding users who deposit the less represented coin with a higher percentage of the pool earnings.

Additionally, liquidity pools allow one token to trade against a base pool, known as meta pools. For instance, in the ARTH/3pool, exchanges occur between the ARTH token and the base pool of three different stablecoins.

For more details, refer to the official documentation.

Key Advantages of Curve

Upon launch, Curve rapidly grew, safeguarding the nascent stablecoin market. Previously, decentralized exchanges suffered from high fees, creating challenges for users wanting to swap between stablecoins.

As a result, Curve.fi became a sought-after protocol for stablecoin exchanges, thanks to its low fees and minimal slippage. Furthermore, the protocol offered liquidity providers various earning instruments, attracting even more liquidity.

Participants can deposit a single stablecoin into the pool, sacrificing a small portion of liquidity, or choose other strategies to deposit assets in equal proportions.

Thus, Curve offers flexibility in liquidity deposit methods. It allows for fund distribution across pools without specific pair constraints but at the cost of slippage, necessary for price balance within the pool.

In essence, Curve operates as an automated decentralized exchange akin to Uniswap, designed for stablecoins. Its user-friendly, retro-styled interface facilitates profitable transactions between stablecoins with low slippage.

Summarizing the Potential Pros and Cons of DEXs

In this overview, we've explored some of the most popular DEXs based on the AMM model. Each platform has its unique features: advancements in overcoming AMM "weaknesses" and their own shortcomings. Despite these functional differences, they share similar goals: to enable liquidity providers to earn and users to swap tokens as efficiently as possible.

With each passing day, the number of different protocols continues to grow, and existing ones are constantly updated. New concepts and tools are being developed to improve trading, enhance security, reduce fees, and mitigate risks. The DeFi sphere is growing rapidly, and DEXs are making strides in development. Opinions on such solutions vary, with some viewing them as utopian and others as the future of the financial system. Their merits, such as decentralization, transparency, and fault tolerance, can be seen both as advantages and disadvantages simultaneously.

Thus, I'll list the potential benefits of DEXs, allowing you to decide whether they outweigh the cons for users.

Potential Advantages:

  • Token Variety: DEXs offer a vast array of tokens for exchange. If the token you're looking for isn't available, you can initiate your own liquidity pool without needing exchange approval or token certification.

  • Lower Risk of Hacking: Since user funds remain in their personal wallets, exchanges don't have full access to these assets. This means control over funds stays with the user. The risk of hacking arises only if users grant third parties the right to manage their funds via approval. However, liquidity providers whose funds are stored in the exchange's smart contract face the risk of loss in the event of contract breaches.

  • Anonymity: DEXs don't require users' personal information, only a web3 wallet (e.g., Metamask, TrustWallet).

  • Transparency: Blockchain technology enables nearly all asset transfers to be tracked.

  • Decentralization: No one can prohibit a particular user from using a decentralized exchange. Even if it's blocked on the interface level, users can still interact directly with the contracts as long as the network has at least one node in operation.

However, no solution is without its flaws.

Potential Disadvantages:

  • Lack of Token Validation: Finding the original token and ensuring it's not a scam project can be challenging, as anyone can create and list a token on the blockchain. Some experience is needed here.

  • Smart Contract Vulnerabilities: While the risk of hacking a DEX is lower, it's still possible. A major downside is the immutability of smart contracts, making it impossible to correct vulnerabilities. While some approaches allow for smart contract updates, this can make them less secure due to the potential for changes, creating a paradox.

  • Pitfalls of Decentralized Trading: Impermanent loss, price slippage, arbitrage, etc.

  • More Complex Development Process: Blockchain imposes restrictions on the development, evolution, and support of DEXs.

  • Variety of Blockchain Networks: Before choosing a DEX, you need to decide on the network. Not all DEXs are supported across all networks.

Need assistance with your blockchain project or idea?

Feel free to schedule a complimentary call with our CTO or leave your contact details on our website, and we will surely address all your questions!

Last updated