ChainScore Labs
All Guides

Introduction to Decentralized Exchanges (DEXs)

LABS

Introduction to Decentralized Exchanges (DEXs)

Chainscore © 2025

Core Concepts and Components

An overview of the fundamental building blocks that power decentralized exchanges, enabling peer-to-peer crypto trading without intermediaries.

Automated Market Makers (AMMs)

Automated Market Makers (AMMs) are smart contract-based protocols that replace traditional order books with liquidity pools to determine asset prices algorithmically. They allow users to trade assets directly against a pool of funds.

  • Key Feature: Uses a constant product formula (x*y=k), popularized by Uniswap, where the product of the quantities of two assets in a pool remains constant.
  • Real Example: Uniswap V2 and PancakeSwap are leading AMM DEXs where users provide liquidity to pools like ETH/USDC to earn fees from trades.
  • User Impact: Enables permissionless, 24/7 trading and liquidity provision, democratizing market making but introducing risks like impermanent loss for liquidity providers.

Liquidity Pools

Liquidity Pools are crowdsourced collections of crypto assets locked in a smart contract, forming the foundational reserves that facilitate trading, lending, and borrowing on DEXs and DeFi platforms.

  • Key Feature: Users, called Liquidity Providers (LPs), deposit equal values of two tokens (e.g., ETH and DAI) to create a trading pair and earn a share of the transaction fees.
  • Real Example: The Curve Finance protocol specializes in stablecoin pools (e.g., USDC/DAI/USDT) with low slippage, optimized for like-kind assets.
  • User Impact: Provides the essential capital depth for trades, allowing for instant swaps without a counterparty, but requires providers to manage exposure to asset volatility and smart contract risks.

Decentralized Order Books

Decentralized Order Books are systems that match buy and sell orders on-chain, similar to centralized exchanges, but executed through distributed networks without a central custodian holding user funds.

  • Key Feature: Orders are stored on the blockchain, enhancing transparency and security, though they can be slower and more expensive due to on-chain computation and storage costs.
  • Real Example: dYdX and Loopring utilize layer-2 scaling solutions to offer order book trading with lower fees and higher throughput than mainnet alternatives.
  • User Impact: Offers familiar trading interfaces for advanced users, supporting limit and stop orders, while maintaining self-custody of assets throughout the trading process.

Governance Tokens

Governance Tokens are crypto assets that grant holders voting rights and influence over the development, parameters, and treasury of a decentralized protocol, aligning incentives between users and the platform's future.

  • Key Feature: Token holders can propose and vote on changes such as fee structures, new feature implementations, or treasury fund allocations through on-chain governance.
  • Real Example: UNI (Uniswap) and SUSHI (SushiSwap) tokens allow holders to vote on protocol upgrades and community grants, decentralizing control away from a core development team.
  • User Impact: Empowers the community to steer the protocol democratically, but participation often requires significant token holdings, which can lead to governance centralization among large holders (whales).

Cross-Chain Swaps

Cross-Chain Swaps enable the direct exchange of assets that natively exist on different blockchain networks (e.g., swapping Ethereum's ETH for Solana's SOL) without using a centralized intermediary.

  • Key Feature: Utilizes bridges, atomic swaps, or liquidity networks to lock assets on one chain and mint or release equivalent assets on another, facilitating interoperability.
  • Real Example: Thorchain uses a network of liquidity pools to perform non-custodial swaps between disparate chains like Bitcoin and Ethereum, while Synapse Protocol connects multiple Layer 1 and Layer 2 networks.
  • User Impact: Expands trading possibilities and access to diverse ecosystems, but introduces additional complexity and security risks associated with the bridging mechanisms and wrapped assets involved.

How an Automated Market Maker (AMM) Works

Process overview

1

Understanding the Core DEX Concept

Learn the fundamentals of decentralized exchanges and how they differ from traditional models.

Detailed Instructions

A Decentralized Exchange (DEX) is a peer-to-peer marketplace where cryptocurrency traders can transact directly without an intermediary. Unlike centralized exchanges (CEXs) like Coinbase, DEXs operate on smart contracts deployed on a blockchain, giving users full custody of their funds. The primary innovation of modern DEXs is the Automated Market Maker (AMM) model, which replaces traditional order books with liquidity pools.

  • Sub-step 1: Identify the DEX Platform - Choose a DEX like Uniswap (Ethereum), PancakeSwap (BNB Chain), or Raydium (Solana). Each has its own smart contract address, e.g., Uniswap V2 Router: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D.
  • Sub-step 2: Connect a Non-Custodial Wallet - Use a wallet like MetaMask or Phantom. You retain your private keys, meaning you control the assets, not the exchange.
  • Sub-step 3: Recognize the Trade-off - Understand that DEXs prioritize permissionless access and security over the speed and liquidity depth often found in CEXs.

Tip: Always verify the official contract addresses from the project's documentation to avoid scams.

2

Exploring the Liquidity Pool Foundation

Discover how liquidity pools provide the trading capital for an AMM.

Detailed Instructions

Liquidity Pools are the foundational smart contracts that hold pairs of tokens, enabling all trades on an AMM. Instead of matching buyers and sellers, the AMM algorithm sets prices based on the ratio of assets in the pool. Liquidity Providers (LPs) deposit an equal value of two tokens into these pools and earn fees from trades.

  • Sub-step 1: Examine a Pool's Composition - A pool for ETH/USDC holds both tokens. Its price is determined by the constant product formula x * y = k, where x and y are the reserve amounts.
  • Sub-step 2: Calculate Provider Share - When you add liquidity, you receive LP tokens representing your share. For example, depositing 1 ETH and 2000 USDC into a pool with 100 ETH and 200,000 USDC total gives you a 1% share.
  • Sub-step 3: Review Fee Structure - Typical swap fees are 0.3% per trade, distributed proportionally to LPs. On Uniswap V2, this fee is automatically added to the pool reserves, increasing the value of LP tokens.

Tip: Use a blockchain explorer like Etherscan to check the real-time reserves of a pool contract, e.g., the WETH/USDC pool.

3

Executing a Swap via the Constant Product Formula

Perform a token swap and see how the AMM algorithm determines price and slippage.

Detailed Instructions

The Constant Product Market Maker model, used by Uniswap, ensures liquidity by maintaining the invariant reserve_a * reserve_b = constant. When a swap occurs, the product of the two reserves must remain constant (minus fees), which automatically determines the execution price.

  • Sub-step 1: Determine Input Amount - Decide to swap 1 ETH for DAI. If the ETH/DAI pool has reserves of 100 ETH and 400,000 DAI, the constant k = 100 * 400,000 = 40,000,000.
  • Sub-step 2: Calculate Output with Fee - The protocol charges a 0.3% fee. The input amount minus fee is 1 * 0.997 = 0.997 ETH. New ETH reserve = 100 + 0.997 = 100.997. New DAI reserve = k / 100.997 = 40,000,000 / 100.997 ≈ 396,027.64. Output DAI = 400,000 - 396,027.64 = 3,972.36 DAI.
  • Sub-step 3: Account for Slippage - Slippage is the difference between expected and actual price. Large orders change the reserve ratio more. Set a slippage tolerance (e.g., 0.5%) in your wallet to prevent unfavorable trades.

Tip: Use the getAmountsOut function in a contract call to preview your swap output before submitting the transaction.

4

Adding and Removing Liquidity

Participate as a liquidity provider to earn fees and understand impermanent loss.

Detailed Instructions

Becoming a Liquidity Provider (LP) involves depositing two tokens in a specific ratio defined by the pool's current price. In return, you earn a portion of all trading fees, but you are exposed to Impermanent Loss—a temporary loss compared to simply holding the assets, caused by price divergence.

  • Sub-step 1: Deposit Equal Value - To add liquidity to an ETH/USDT pool, you must deposit amounts of ETH and USDT of equal USD value. If 1 ETH = $2000, and you deposit 1 ETH, you must also deposit 2000 USDT.
  • Sub-step 2: Receive and Manage LP Tokens - The pool mints LP tokens (e.g., Uniswap V2 LP tokens) to your wallet. To remove liquidity, you burn these tokens to reclaim your share of the pool, which will have changed based on all intervening trades.
  • Sub-step 3: Calculate Impermanent Loss - If the price of ETH doubles relative to USDT after you deposit, the AMM rebalances the pool, giving you less ETH and more USDT than if you had just held. The loss can be calculated with online tools or the formula: IL = 2 * sqrt(price_ratio) / (1 + price_ratio) - 1.

Tip: Use a platform like Zapper.fi to easily track your LP positions, fees earned, and impermanent loss across different protocols.

DEX Model Comparison: AMM vs. Order Book

Comparison of core operational models for decentralized exchanges.

FeatureAutomated Market Maker (AMM)Order BookHybrid (e.g., dYdX v3)

Liquidity Source

Pre-funded liquidity pools (e.g., ETH/USDC)

Limit orders from traders

Combined order book & AMM pools

Price Discovery

Algorithmic via constant product formula (x*y=k)

Order matching (bid/ask)

Primarily order book, AMM for backup

Example Protocol

Uniswap v3

Serum (on Solana)

dYdX (v3, on StarkEx)

Typical Fee Structure

0.01% to 1% swap fee to LPs

Maker fee: ~0.02%, Taker fee: ~0.07%

Taker fees: ~0.05%, Maker rebates possible

Capital Efficiency

Lower (requires wide liquidity distribution)

Higher (concentrated at price points)

High (leveraged trading, order book focus)

Slippage

Can be high for large orders in shallow pools

Minimal for orders within order book depth

Minimal when order book is deep

Gas Efficiency (Ethereum)

High for swaps, high for initial LP provision

High for order placement/cancellation

Off-chain order book reduces gas costs

Trading Experience

Simple swap interface

Familiar CEX-like interface with charts

Advanced interface with leverage & order types

DEX Interactions: Trader vs. Liquidity Provider

Getting Started

A Decentralized Exchange (DEX) is a peer-to-peer marketplace where users trade cryptocurrencies directly from their wallets without a central intermediary. The two primary roles are the Trader, who swaps tokens, and the Liquidity Provider (LP), who supplies the trading pools with assets to earn fees.

Key Points

  • Automated Market Makers (AMMs): Most DEXs like Uniswap use this model. Instead of an order book, they use a mathematical formula (e.g., x*y=k) to set prices based on the ratio of tokens in a pool.
  • Liquidity Pools: These are smart contract-held reserves of token pairs (e.g., ETH/USDC). LPs deposit an equal value of both tokens to create the pool, enabling trades.
  • Impermanent Loss: A key risk for LPs. It's the temporary loss compared to holding assets when the price ratio of the pooled tokens changes dramatically.

Example

When using Uniswap to trade ETH for DAI, you connect your wallet (like MetaMask), select the tokens, and confirm the swap. The protocol automatically finds the best price from liquidity pools, and you pay a small fee that is distributed to the LPs who supplied that pool.

Anatomy of a DEX Trade

A step-by-step process overview of executing a trade on a Decentralized Exchange, from wallet connection to settlement.

1

Connect Your Wallet

Link your non-custodial crypto wallet to the DEX interface to authorize transactions.

Detailed Instructions

First, you must connect a non-custodial Web3 wallet like MetaMask, WalletConnect, or Phantom to the DEX's front-end application. This connection does not give the DEX control of your funds; it only allows it to read your public address and request transaction signatures.

  • Sub-step 1: Navigate to the DEX website (e.g., app.uniswap.org) and click the 'Connect Wallet' button.
  • Sub-step 2: Select your wallet provider from the modal list. For MetaMask, a browser extension pop-up will appear requesting connection to the site.
  • Sub-step 3: Authorize the connection by signing a one-time message in your wallet. This proves you own the address without spending gas.

Tip: Always verify you are on the correct, official website URL to avoid phishing scams. Never share your private keys or seed phrase.

2

Select Tokens and Amount

Choose the trading pair and specify the exact input or output amount for your swap.

Detailed Instructions

Define the parameters of your trade by selecting the input token you wish to sell and the output token you wish to buy. You must also decide whether to specify an exact 'Input' amount or a desired 'Output' amount, which affects the trade's slippage tolerance.

  • Sub-step 1: Choose input token. Click the 'From' dropdown, which may show your wallet balance. For example, select ETH.
  • Sub-step 2: Choose output token. Click the 'To' dropdown and search for a token by symbol or contract address, e.g., USDC.
  • Sub-step 3: Enter the amount. Input 1.5 in the 'From' field. The interface will automatically fetch and display the estimated output amount, like 4500 USDC, based on the current liquidity pool rates.

Tip: For tokens not in the default list, you may need to paste the contract address (e.g., 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 for USDC on Ethereum) to import them. Always verify the token contract.

3

Review Quote and Set Parameters

Examine the trade details, including price impact and fees, then configure slippage and deadline.

Detailed Instructions

Before executing, carefully review the quote provided by the DEX's automated market maker (AMM) smart contract. Key metrics include the exchange rate, estimated gas fee, price impact (how much your trade moves the market), and the liquidity provider fee (often 0.3% on Uniswap V2).

  • Sub-step 1: Check the quote details. Look for the '1 ETH = 3000 USDC' price, a price impact of 0.5%, and a network fee of 0.005 ETH.
  • Sub-step 2: Adjust slippage tolerance. Click the settings icon. For stable pairs, 0.5% may suffice. For volatile assets, you might set it to 1% or 2% to prevent transaction failure.
  • Sub-step 3: Set transaction deadline. This is the time (e.g., 20 minutes) after which the trade will revert if not mined, protecting you from stale quotes.

Tip: High price impact on large trades can be mitigated by using a DEX aggregator (like 1inch) that splits the trade across multiple pools for a better effective rate.

4

Approve Token Spend (First-Time Only)

Grant the DEX router contract a one-time allowance to access the specific token you are selling.

Detailed Instructions

If you are selling an ERC-20 token (not the network's native gas token like ETH), you must first give the DEX's router contract permission to withdraw that token from your wallet. This is done via an approve transaction.

  • Sub-step 1: Initiate the swap. After clicking 'Swap', your wallet will prompt you for two signatures. The first is the approval.
  • Sub-step 2: Review the approval transaction. It will call the approve function on the token's contract, specifying the DEX router as the spender and an amount (often set to the maximum 2^256 - 1 for unlimited future approvals).
solidity
// Example function call IERC20(tokenAddress).approve(routerAddress, type(uint256).max);
  • Sub-step 3: Pay gas and confirm. Sign and broadcast the approval transaction. This is a separate gas cost from the swap itself.

Tip: You only need to do this once per token per DEX router contract. You can check or revoke allowances using tools like Etherscan's 'Token Approvals' feature.

5

Execute and Confirm the Swap

Sign the final swap transaction and monitor its confirmation on the blockchain.

Detailed Instructions

The final step is to sign the swap transaction itself. This instructs the DEX's router contract to execute the trade against the liquidity pools, transferring tokens between the parties involved.

  • Sub-step 1: Confirm the swap transaction. After token approval, your wallet will prompt for the main swap. Review details: input 1.5 ETH, minimum output 4477.5 USDC (factoring in 0.5% slippage), and recipient address (your wallet).
  • Sub-step 2: Sign and broadcast. The transaction will call a function like swapExactTokensForTokens on the router contract.
solidity
// Example function signature swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline);
  • Sub-step 3: Monitor confirmation. After signing, a transaction hash (e.g., 0xabcd...1234) is generated. Use a block explorer like Etherscan to track its status from 'Pending' to 'Success'.

Tip: If the transaction fails due to slippage (price moved beyond your tolerance), you will lose gas but not the principal. You can adjust your slippage and resubmit.

SECTION-ADVANCED-TOPICS-FAQ

Advanced Topics and Common Questions

Ready to Start Building?

Let's bring your Web3 vision to life.

From concept to deployment, ChainScore helps you architect, build, and scale secure blockchain solutions.