🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

DEX Architecture

Blockchain Financial SystemsđŸŸĸ Free Lesson

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

FeatureOrder Book DEXAMM DEX
Price DiscoveryBuyer/seller matchingAlgorithmic curves
Liquidity SourceMarket makersLiquidity providers
SlippageDepends on depthPredictable (curve-based)
Gas CostsHigh (per order)Medium (per swap)
LatencyRequires fast matchingBlock-time execution
ExamplesdYdX, SerumUniswap, SushiSwap
Capital EfficiencyHigh (limit orders)Lower (idle liquidity)

Order Book Mechanics

Order Book Depth VisualizationBidsAsksSpreadBids (buy orders) on left, Asks (sell orders) on right DEX Architecture ComparisonOrder Book DEXBuy Orders (Bids)Sell Orders (Asks)â€ĸ Off-chain matchingâ€ĸ On-chain settlementâ€ĸ Price-time priorityâ€ĸ Requires market makersAMM DEXLiquidity PoolToken A + Token Bx × y = kâ€ĸ Algorithmic pricingâ€ĸ Always-on liquidityâ€ĸ No counterparty neededâ€ĸ LP fee income

Hybrid DEX Models

Hybrid models combine order book efficiency with AMM liquidity:

Serum Architecture (Solana)

  1. Central Limit Order Book (CLOB): Off-chain order matching
  2. On-chain Settlement: Trades settled on Solana
  3. Pool-Based Liquidity: AMM pools provide baseline liquidity
  4. OpenBook: Aggregated order book across multiple markets

Hybrid Pricing Formula

Where is the weight given to order book prices.

Hybrid DEX Architecture

Hybrid DEX ArchitectureOrder Book EngineOff-chain matchingAMM Liquidity PoolOn-chain settlementSettlement LayerOn-chain verification + finality

MEV (Maximal Extractable Value)

MEV represents the profit validators/sequencers can extract by reordering, inserting, or censoring transactions.

MEV Types

TypeDescriptionExample
Sandwich AttackFront/back-run DEX tradesFrontrun large swap
ArbitrageCross-DEX price exploitationBuy low, sell high
LiquidationLiquidate under-collateralized loansEarn liquidation bonus
BackrunningInsert transaction after large tradeHarvest price impact
Time BanditReorganize blocks for MEVBlock reordering

MEV Impact Formula

Where:

  • = Price before transaction
  • = Price after transaction
  • = Trade volume
  • = Gas costs for extraction
Sandwich Attack DiagramVictim TxBuy 100 ETHFront-runBuy 50 ETH firstBack-runSell 50 ETH afterPrice ImpactBefore: 1 ETH = 1800 USDCAfter front-run: 1810After victim: 1825Profit: (1825-1810)×50= 750 USDC - gas

MEV Protection Mechanisms

MechanismHow It WorksTrade-offs
FlashbotsPrivate transaction poolsCentralization concerns
MEV-ShareRedistribute MEV to usersComplex implementation
Batch AuctionsCoW (Coincidence of Wants)Slower execution
Encrypted MempoolCommit-reveal schemesAdded latency
Fair OrderingFirst-come-first-served consensusRequires protocol changes

MEV Impact Visualization

MEV Extraction by TypeMEV TypeMonthly Volume ($M)SandwichArbitrageLiquidationBackrunSandwich attacks remain the most common form of MEV extraction

Limit Orders on DEXs

Limit Order Implementation

Limit orders on DEXs typically use:

  1. Off-chain Relayers: Orders stored off-chain, executed on-chain
  2. On-chain Order Books: Gas-intensive but fully decentralized
  3. 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 TypeDescriptionExecution
LimitExecute at specific priceAt price or better
Stop-LossExecute when price crosses thresholdMarket order after trigger
IOC (Immediate or Cancel)Fill immediately or cancelPartial fills allowed
FOK (Fill or Kill)Complete fill or cancelNo partial fills

Governance Token Value Accrual

Value Accrual Mechanisms

MechanismDescriptionExample
Fee SharingProtocol fees distributed to holdersSushi (xSUSHI)
Buyback & BurnProtocol buys and burns tokensBNB
Vote EscrowLock tokens for boosted rewardsCurve (veCRV)
Revenue SharingDirect distribution of revenueGMX (esGMX)
Staking RewardsToken inflation to stakersAAVE Safety Module

Token Value Formula

Where:

  • = Annual protocol revenue
  • = Growth rate
  • = Discount rate

Governance Premium

Where = Cash flows from governance decisions.

DEX Token Comparison

TokenMarket CapRevenue ShareStaking APY
UNI$5B+None (proposed)0%
SUSHI$200M+0.05% of trades5-10%
CRV$500M+50% to veCRV10-30%
GMX$500M+30% to stakers10-20%
CAKE$400M+Buyback & burn5-15%

Real-World Example: Uniswap v3 Architecture

Uniswap v3 combines concentrated liquidity with on-chain order execution:

  1. Liquidity Positions: LPs provide concentrated liquidity in price ranges
  2. Swaps: Users execute trades against LP positions
  3. Fee Tiers: Multiple fee tiers (0.01%, 0.05%, 0.3%, 1%)
  4. 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

  1. Matching Engine: Centralized (fast) vs Distributed (decentralized)
  2. Settlement: On-chain (trustless) vs Off-chain (scalable)
  3. Liquidity Model: Order book (dynamic) vs Pool (passive)
  4. Fee Structure: Flat fees vs Dynamic fees
  5. Oracle Integration: On-chain TWAP vs External oracle

DEX Performance Metrics

MetricDescriptionTarget
ThroughputTransactions per second> 10 TPS
LatencyTime to finality< 12 seconds
SlippagePrice impact per trade< 0.5%
UptimeSystem availability> 99.9%
Gas EfficiencyCost per trade< $5

DEX Technology Stack

DEX Technology StackFrontend (React, Next.js)API Layer (GraphQL, REST)Matching Engine (Off-chain)Settlement (Smart Contracts)Blockchain (Ethereum, L2)

Interview Questions

  1. Compare order book DEXs and AMM DEXs. What are the key trade-offs in terms of price discovery, liquidity, and gas costs?

  2. Explain how MEV sandwich attacks work and describe two mechanisms that DEXs use to protect users from MEV extraction.

  3. How do governance tokens accrue value in DEX ecosystems? Compare fee-sharing and buyback-and-burn mechanisms.

DEX Selection Criteria

CriteriaWeightEvaluation Method
Liquidity30%Volume/TVL ratio
Security25%Audit status, bug bounty
Fees20%Trading fees + gas costs
User Experience15%Interface, speed, features
Governance10%Decentralization, community

DEX Ecosystem Map

DEX Ecosystem OverviewOrder BookdYdX, SerumAMMUniswap, SushiHybridCurve, BalancerConcentratedUniswap v3Each DEX type has specific use cases and trade-offsSelection depends on trading needs, risk tolerance, and gas budget

DEX Security Considerations

RiskImpactMitigation
Smart ContractHighAudits, bug bounties
Oracle ManipulationHighTWAP, multiple sources
Front-RunningMediumMEV protection
Liquidity DrainHighInsurance, monitoring
Admin Key CompromiseCriticalMulti-sig, time locks

DEX Future Trends

  1. Intent-based Trading: User intents matched off-chain
  2. Cross-chain DEX: Seamless multi-chain trading
  3. AI-powered Routing: ML for optimal execution
  4. Concentrated Liquidity v2: More granular position management
  5. Account Abstraction: Improved user experience

Quiz Questions

  1. 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
  2. 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
  3. Which MEV protection mechanism uses private transaction pools?

    • A) Batch auctions
    • B) Encrypted mempool
    • C) Flashbots
    • D) Fair ordering
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement