DEX Architecture
Decentralized exchanges (DEXs) enable peer-to-peer trading without intermediaries. They come in several architectural forms, each with distinct trade-offs regarding speed, cost, and user experience.
Order Book DEX vs AMM DEX
Comparison Table
| Feature | Order Book DEX | AMM DEX |
|---|---|---|
| Price Discovery | Buyer/seller matching | Algorithmic curves |
| Liquidity Source | Market makers | Liquidity providers |
| Slippage | Depends on depth | Predictable (curve-based) |
| Gas Costs | High (per order) | Medium (per swap) |
| Latency | Requires fast matching | Block-time execution |
| Examples | dYdX, Serum | Uniswap, SushiSwap |
| Capital Efficiency | High (limit orders) | Lower (idle liquidity) |
Order Book Mechanics
Hybrid DEX Models
Hybrid models combine order book efficiency with AMM liquidity:
Serum Architecture (Solana)
- Central Limit Order Book (CLOB): Off-chain order matching
- On-chain Settlement: Trades settled on Solana
- Pool-Based Liquidity: AMM pools provide baseline liquidity
- OpenBook: Aggregated order book across multiple markets
Hybrid Pricing Formula
Where is the weight given to order book prices.
Hybrid DEX Architecture
MEV (Maximal Extractable Value)
MEV represents the profit validators/sequencers can extract by reordering, inserting, or censoring transactions.
MEV Types
| Type | Description | Example |
|---|---|---|
| Sandwich Attack | Front/back-run DEX trades | Frontrun large swap |
| Arbitrage | Cross-DEX price exploitation | Buy low, sell high |
| Liquidation | Liquidate under-collateralized loans | Earn liquidation bonus |
| Backrunning | Insert transaction after large trade | Harvest price impact |
| Time Bandit | Reorganize blocks for MEV | Block reordering |
MEV Impact Formula
Where:
- = Price before transaction
- = Price after transaction
- = Trade volume
- = Gas costs for extraction
MEV Protection Mechanisms
| Mechanism | How It Works | Trade-offs |
|---|---|---|
| Flashbots | Private transaction pools | Centralization concerns |
| MEV-Share | Redistribute MEV to users | Complex implementation |
| Batch Auctions | CoW (Coincidence of Wants) | Slower execution |
| Encrypted Mempool | Commit-reveal schemes | Added latency |
| Fair Ordering | First-come-first-served consensus | Requires protocol changes |
MEV Impact Visualization
Limit Orders on DEXs
Limit Order Implementation
Limit orders on DEXs typically use:
- Off-chain Relayers: Orders stored off-chain, executed on-chain
- On-chain Order Books: Gas-intensive but fully decentralized
- Hybrid Models: Off-chain matching, on-chain settlement
Limit Order Smart Contract Logic
struct LimitOrder {
address maker;
address tokenSell;
address tokenBuy;
uint256 amountSell;
uint256 amountBuy;
uint256 expiry;
bool filled;
}
Order Types
| Order Type | Description | Execution |
|---|---|---|
| Limit | Execute at specific price | At price or better |
| Stop-Loss | Execute when price crosses threshold | Market order after trigger |
| IOC (Immediate or Cancel) | Fill immediately or cancel | Partial fills allowed |
| FOK (Fill or Kill) | Complete fill or cancel | No partial fills |
Governance Token Value Accrual
Value Accrual Mechanisms
| Mechanism | Description | Example |
|---|---|---|
| Fee Sharing | Protocol fees distributed to holders | Sushi (xSUSHI) |
| Buyback & Burn | Protocol buys and burns tokens | BNB |
| Vote Escrow | Lock tokens for boosted rewards | Curve (veCRV) |
| Revenue Sharing | Direct distribution of revenue | GMX (esGMX) |
| Staking Rewards | Token inflation to stakers | AAVE Safety Module |
Token Value Formula
Where:
- = Annual protocol revenue
- = Growth rate
- = Discount rate
Governance Premium
Where = Cash flows from governance decisions.
DEX Token Comparison
| Token | Market Cap | Revenue Share | Staking APY |
|---|---|---|---|
| UNI | $5B+ | None (proposed) | 0% |
| SUSHI | $200M+ | 0.05% of trades | 5-10% |
| CRV | $500M+ | 50% to veCRV | 10-30% |
| GMX | $500M+ | 30% to stakers | 10-20% |
| CAKE | $400M+ | Buyback & burn | 5-15% |
Real-World Example: Uniswap v3 Architecture
Uniswap v3 combines concentrated liquidity with on-chain order execution:
- Liquidity Positions: LPs provide concentrated liquidity in price ranges
- Swaps: Users execute trades against LP positions
- Fee Tiers: Multiple fee tiers (0.01%, 0.05%, 0.3%, 1%)
- Oracle: TWAP oracle using tick observations
Swap Execution
Trade-Offs
DEX Architecture Trade-Offs
- Order Book vs AMM: Order books offer better price discovery; AMMs provide passive liquidity
- On-chain vs Off-chain: Fully on-chain is decentralized but expensive; off-chain is faster but centralized
- MEV Protection vs Speed: Protection mechanisms add latency
- Capital Efficiency vs Complexity: Concentrated liquidity is efficient but complex
- Governance vs Efficiency: Token governance is slow but fair; multisig is fast but centralized
Key Design Decisions
- Matching Engine: Centralized (fast) vs Distributed (decentralized)
- Settlement: On-chain (trustless) vs Off-chain (scalable)
- Liquidity Model: Order book (dynamic) vs Pool (passive)
- Fee Structure: Flat fees vs Dynamic fees
- Oracle Integration: On-chain TWAP vs External oracle
DEX Performance Metrics
| Metric | Description | Target |
|---|---|---|
| Throughput | Transactions per second | > 10 TPS |
| Latency | Time to finality | < 12 seconds |
| Slippage | Price impact per trade | < 0.5% |
| Uptime | System availability | > 99.9% |
| Gas Efficiency | Cost per trade | < $5 |
DEX Technology Stack
Interview Questions
-
Compare order book DEXs and AMM DEXs. What are the key trade-offs in terms of price discovery, liquidity, and gas costs?
-
Explain how MEV sandwich attacks work and describe two mechanisms that DEXs use to protect users from MEV extraction.
-
How do governance tokens accrue value in DEX ecosystems? Compare fee-sharing and buyback-and-burn mechanisms.
DEX Selection Criteria
| Criteria | Weight | Evaluation Method |
|---|---|---|
| Liquidity | 30% | Volume/TVL ratio |
| Security | 25% | Audit status, bug bounty |
| Fees | 20% | Trading fees + gas costs |
| User Experience | 15% | Interface, speed, features |
| Governance | 10% | Decentralization, community |
DEX Ecosystem Map
DEX Security Considerations
| Risk | Impact | Mitigation |
|---|---|---|
| Smart Contract | High | Audits, bug bounties |
| Oracle Manipulation | High | TWAP, multiple sources |
| Front-Running | Medium | MEV protection |
| Liquidity Drain | High | Insurance, monitoring |
| Admin Key Compromise | Critical | Multi-sig, time locks |
DEX Future Trends
- Intent-based Trading: User intents matched off-chain
- Cross-chain DEX: Seamless multi-chain trading
- AI-powered Routing: ML for optimal execution
- Concentrated Liquidity v2: More granular position management
- Account Abstraction: Improved user experience
Quiz Questions
-
What is the primary advantage of AMM DEXs over order book DEXs?
- A) Better price discovery
- B) Always-on liquidity without market makers
- C) Lower gas costs
- D) No slippage
-
In a sandwich attack, when does the attacker profit?
- A) Before the victim's trade executes
- B) After the victim's trade executes
- C) Both before and after
- D) Never, sandwich attacks always lose money
-
Which MEV protection mechanism uses private transaction pools?
- A) Batch auctions
- B) Encrypted mempool
- C) Flashbots
- D) Fair ordering