Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Understanding DEXs and AMMs: A Uniswap Example

Hello! Welcome to the tenth module of our course. You've come a long way, from blockchain fundamentals to building and deploying a full-stack dApp with a token sale and staking features. Your token is "live" on the testnet, but right now, it exists in a silo. The only way to get it is through your crowdsale contract.

To make your token truly part of the decentralized economy, people need a place to trade it freely. In the traditional financial world, this would be a stock exchange. In crypto, the centralized equivalent would be exchanges like Coinbase or Binance. However, the true spirit of DeFi lies in Decentralized Exchanges (DEXs).

This lesson will introduce you to the function of DEXs and the brilliant innovation that powers them: the Automated Market Maker (AMM). We will use Uniswap, the most popular DEX on Ethereum, as our primary example. Understanding how these platforms work is the first crucial step to integrating your token into the wider DeFi ecosystem.

1. Centralized vs. Decentralized Exchanges

Before diving into how DEXs work, it's essential to understand how they differ from the centralized exchanges you might be more familiar with.

A centralized exchange (CEX) is operated by a single company. They use a traditional order book system, which matches buy orders with sell orders. To use a CEX, you must create an account, complete identity verification (KYC), and deposit your crypto into a wallet controlled by the exchange.

A decentralized exchange (DEX), on the other hand, is not a company. It's a set of smart contracts running on the blockchain. This fundamental difference leads to several key distinctions.

To get a clear overview of these differences, let's watch a segment from 99Bitcoins.

What is Uniswap - A Beginner's Guide (2024 Updated)

This video provides a great introduction to Uniswap by first contrasting it with traditional, centralized exchanges.

Watch the section from 00:51 to 03:48. As you watch, focus on the key differences highlighted between a traditional exchange and a DEX regarding: Control (who runs it) Permissions (who can use it) Custody (who holds the funds)

To summarize the key distinctions:

Feature Centralized Exchange (CEX) Decentralized Exchange (DEX)
Control Run by a single company (e.g., Coinbase, Binance). Run by code (smart contracts) on a blockchain.
Custody Custodial: You deposit funds into their control. Non-custodial: You trade directly from your own wallet.
Permissions Permissioned: Requires account creation and KYC. Permissionless: Anyone with a wallet can interact.
Listing Companies decide which tokens to list. Anyone can create a market for any ERC-20 token.
Mechanism Order Book Automated Market Maker (AMM)

Given your backend experience, you can think of a CEX as a traditional web application with a central database managing user accounts and orders. A DEX, in contrast, is like a public API defined by smart contracts, where the "backend" is the decentralized and transparent Ethereum blockchain itself.

2. The Rise of the Automated Market Maker (AMM)

So, if DEXs don't use order books, how do they facilitate trading? The initial answer might seem to be "just put the order book on the blockchain." However, this is extremely inefficient. Every action—placing an order, canceling an order, matching an order—would require a separate gas-paying transaction, making it slow and expensive.

The solution was a paradigm shift in how we think about exchanges: the Automated Market Maker (AMM).

What is an Automated Market Maker? (Liquidity Pool Algorithm)

Let's get a quick, concise definition of an AMM from Whiteboard Crypto.

Watch the first 33 seconds of this video. It perfectly encapsulates the core idea of an AMM: using an algorithm to determine price based on supply and demand within a pool of assets.

Instead of matching individual buyers and sellers, an AMM allows users to trade against a pool of tokens held in a smart contract. This pool is known as a liquidity pool.

How Uniswap Works: Liquidity Provision and Token Swapping
This diagram shows the relationship between a Liquidity Provider (who supplies tokens to the pool), a Trader (who swaps tokens using the pool), and the Uniswap Pool (the smart contract holding the tokens).

As the diagram shows, trading on an AMM is a two-sided affair:

  • Traders swap one token for another, paying a small fee.
  • Liquidity Providers (LPs) supply pairs of tokens to the liquidity pool and earn the trading fees generated from it.

3. The Magic Formula: Constant Product Market Maker

How does the AMM determine the price? Most early and popular AMMs, like Uniswap V2, use a simple but powerful algorithm called the Constant Product Market Maker.

The formula is:

Where:

  • x is the quantity of Token A in the liquidity pool.
  • y is the quantity of Token B in the liquidity pool.
  • k is a constant value (the "invariant").

The rule is that after any trade, the product of the two token quantities in the pool must remain constant. This creates a supply-and-demand dynamic. As the supply of one token in the pool decreases, its price relative to the other token increases, and vice-versa.

Let's watch a detailed explanation with a great analogy to solidify this concept.

What is an Automated Market Maker? (Liquidity Pool Algorithm)

The Whiteboard Crypto video uses a simple analogy of apples and potatoes to explain the x * y = k formula without any complex jargon. This will help build a strong intuition for the mechanics.

Watch from 01:40 to 04:29. Follow the example of the potato farmer trading potatoes for apples. Pay attention to how each trade changes the quantities of assets in the pool and, as a result, the price of the next trade.

As the video demonstrates, when a trader sells a large number of potatoes (Token A) into the pool to buy apples (Token B), the supply of potatoes increases and the supply of apples decreases. According to the formula, the price of potatoes will go down, and the price of apples will go up for the next trade.

This constant product formula is what is visualized by the iconic hyperbolic curve associated with AMMs.

Automated Market Maker (AMM) Constant Product Formula
This graph illustrates the x * y = k relationship. Each trade moves the pool's state along the curve. As you move far to the left (removing lots of Token B), the curve becomes very steep, meaning Token B becomes exponentially more expensive. The pool can therefore never run out of either asset.
Test your understanding!

Imagine a liquidity pool on Uniswap contains 1,000 of your MyToken (Token X) and 10 ETH (Token Y).

  1. What is the value of the constant, k?
  2. Based on the ratio of assets, what is the current "spot price" of 1 MyToken in ETH?
  3. A trader wants to buy 100 MyToken. They will add ETH to the pool and remove MyToken.
    • After the trade, how many MyToken will be left in the pool?
    • To keep k constant, how much ETH must be in the pool after the trade?
    • How much ETH did the trader have to pay for the 100 MyToken?
Show answer
  1. k = x * y = 1000 * 10 = 10,000.
  2. The price is the ratio of the assets: price(X) = y / x = 10 ETH / 1000 MyToken = 0.01 ETH per MyToken.
    • New x = 1000 - 100 = 900 MyToken.
    • To find the new y, we use k: New y = k / New x = 10,000 / 900 ≈ 11.11 ETH.
    • The trader paid the difference between the new and old ETH amounts: 11.11 - 10 = 1.11 ETH. Notice the trader paid an average price of 1.11 / 100 = 0.0111 ETH per token, which is higher than the initial spot price. This price impact is called slippage.

4. Keeping Prices in Sync: The Role of Arbitrage

A common question is: what keeps the AMM's price aligned with the price on other exchanges, like Binance? The answer is arbitrage.

If the price of ETH in an AMM pool is cheaper than on Binance, traders (often bots) will immediately buy the cheaper ETH from the AMM and sell it on Binance for a profit. This action has a powerful side effect.

Chapter 3 Automated Market Making

This chapter from the 'Concentrated Liquidity Provision' book gives a clear, step-by-step description of how swaps and arbitrage affect the pool.

Read the two short sections: 'What happens after a swap?' and 'What happens when there’s a big movement in the market price of ETH?'. These explain the self-correcting nature of AMM prices driven by profit-seeking arbitrageurs.

By buying ETH from the pool, arbitrageurs reduce the pool's ETH supply, causing its price to rise until it matches the external market price, eliminating the arbitrage opportunity. This constant, decentralized process ensures that AMM prices generally reflect the broader market.

5. Uniswap's Architecture: Core and Periphery

Finally, it's useful to understand Uniswap's high-level architecture, as it employs a design pattern that may be familiar to you from your software development experience. Uniswap uses a core-periphery model.

Uniswap V2 Architecture: An Introduction to Automated ...

The Rareskills article on Uniswap V2's architecture provides a great overview of its key contracts and design philosophy.

Read the section 'Architecture of Uniswap V2'. Pay attention to the three main contracts (Factory, Pair, Router) and the purpose of the 'core-periphery' pattern.

  • Core: These are the essential, minimal, and highly audited smart contracts. For Uniswap V2, this includes the Factory (which deploys new pair contracts) and the Pair contract (the liquidity pool itself). The goal is to keep the core as simple and secure as possible.
  • Periphery: These are contracts that provide user-friendly methods to interact with the core. The Router contract is the primary example. It provides functions to handle complex swaps (e.g., trading Token A for Token C by routing through Token B) and abstracts away some of the direct interactions with the Pair contracts.

Most users and dApps interact with the Periphery (the Router), not the Core contracts directly. This separation of concerns makes the system both secure and extensible.

Conclusion

In this lesson, we've unpacked the fundamental concepts behind decentralized exchanges and the automated market makers that power them. You've gone from understanding the limitations of centralized systems to grasping the elegant mechanics of Uniswap.

Key Takeaways:

  • DEXs are permissionless, non-custodial exchanges built from smart contracts, contrasting with company-run CEXs.
  • AMMs solve the problem of on-chain order books by allowing users to trade against a liquidity pool.
  • The Constant Product Formula (x * y = k) is the core algorithm that determines prices based on the ratio of assets in the pool.
  • Arbitrage is the economic force that keeps AMM prices in line with the broader market.
  • Uniswap uses a core-periphery architecture to separate its essential, secure logic from its user-facing helper functions.

Preview of the Next Lesson:
Now that you understand how AMMs work, our next lesson will focus on the people who make them possible: Liquidity Providers (LPs). We will explore what a liquidity pool is in more detail, why someone would provide liquidity to a pool containing your token, and what LP tokens are. We will also introduce the primary risk that LPs face, known as impermanent loss.

Can't find a good explanation? Sign up and we'll make it for you

Sign up