BTC $67,420 ▲ +2.4% ETH $3,541 ▲ +1.8% SOL $178 ▲ +5.1% BNB $412 ▼ -0.3% XRP $0.63 ▲ +0.9% ADA $0.51 ▼ -1.2% AVAX $38.90 ▲ +2.7% DOGE $0.17 ▲ +3.2% DOT $8.42 ▼ -0.8% LINK $14.60 ▲ +3.6% MATIC $0.92 ▲ +1.5% LTC $88.40 ▼ -0.6% BTC $67,420 ▲ +2.4% ETH $3,541 ▲ +1.8% SOL $178 ▲ +5.1% BNB $412 ▼ -0.3% XRP $0.63 ▲ +0.9% ADA $0.51 ▼ -1.2% AVAX $38.90 ▲ +2.7% DOGE $0.17 ▲ +3.2% DOT $8.42 ▼ -0.8% LINK $14.60 ▲ +3.6% MATIC $0.92 ▲ +1.5% LTC $88.40 ▼ -0.6%
Crypto Currencies

Decentralised Crypto Exchange Architecture and Trade Execution Mechanics

Decentralised exchanges (DEXs) execute token swaps and provide liquidity without a central order book or custodian, relying instead on smart contracts and…
Halille Azami · April 6, 2026 · 7 min read
Decentralised Crypto Exchange Architecture and Trade Execution Mechanics

Decentralised exchanges (DEXs) execute token swaps and provide liquidity without a central order book or custodian, relying instead on smart contracts and onchain settlement. They eliminate counterparty credit risk and offer permissionless access, but introduce execution complexity, gas dependency, and liquidity fragmentation that centralized venues don’t face. This article unpacks how DEX architectures differ, how trades settle, and what operators and integrators should verify before routing flow.

Order Matching Models: AMM vs Order Book DEXs

Automated market makers (AMMs) derive prices algorithmically from liquidity pool reserves. The constant product formula (x * y = k) remains the most deployed variant: swapping token A for token B shifts the reserve ratio, moving price along a bonding curve. Each trade against the pool adjusts the marginal rate. Slippage grows nonlinearly with trade size relative to pool depth.

Order book DEXs replicate centralized limit order mechanics onchain or via hybrid models. Fully onchain order books store every bid and ask in contract state, making order placement and cancellation expensive in gas. Hybrid approaches (offchain order relay with onchain settlement) reduce costs by broadcasting signed limit orders through a relayer network and settling only matched trades onchain. This introduces relayer trust assumptions: the relayer can censor orders or front run, though the settlement remains noncustodial.

The choice between AMM and order book affects capital efficiency and execution quality. AMMs require liquidity providers to deposit inventory across the entire price curve, even ranges unlikely to trade. Concentrated liquidity AMMs (introduced in Uniswap v3) let LPs allocate capital within specific price bounds, improving utilization but requiring active range management. Order book models allow passive limit orders at precise prices but depend on taker flow to match resting orders.

Gas Costs and Transaction Finality

Every DEX interaction consumes gas: the computational cost paid to validators for executing contract logic. Swap complexity varies. A simple AMM swap on Ethereum mainnet (approve token, execute swap function) typically costs 100,000 to 200,000 gas units. Multi hop swaps (routing through intermediate pools) and complex limit order fills can exceed 300,000 gas. At 30 gwei base fee and 2,000 USD per ETH, a 150,000 gas swap costs roughly nine USD in fees, independent of trade size. This makes small trades economically unviable on Layer 1 during periods of network congestion.

Layer 2 rollups (Optimism, Arbitrum, Base) batch transactions and settle proofs to Ethereum, reducing per transaction gas by one to two orders of magnitude. Trades that cost eight USD on mainnet may cost 10 to 50 cents on L2, though bridge delays and liquidity fragmentation remain tradeoffs.

Transaction finality determines when a swap is irreversible. On proof of work chains, finality is probabilistic. On proof of stake Ethereum, finality occurs after two epochs (approximately 13 minutes), though most users treat inclusion in a block as practical settlement. Rollups inherit the finality model of their base layer but add sequencer confirmation latency. Solana and other high throughput chains offer sub second block times but longer finality windows under network stress.

Liquidity Provision and Impermanent Loss Mechanics

Liquidity providers deposit token pairs into AMM pools, earning a fraction of swap fees in proportion to their pool share. The fee percentage is typically set per pool (0.05%, 0.3%, 1%) and accumulates in the pool as trading volume flows through.

Impermanent loss arises when the relative price of deposited tokens diverges from the deposit ratio. An LP deposits equal value of ETH and USDC when ETH trades at 2,000 USDC. If ETH rises to 3,000 USDC, arbitrageurs rebalance the pool by buying underpriced ETH, leaving the LP with more USDC and less ETH than simply holding both tokens. The loss is impermanent because it vanishes if prices revert, but it becomes permanent when the LP withdraws. Volatility and price drift amplify impermanent loss, especially in pools pairing assets with divergent fundamentals.

Concentrated liquidity magnifies both fee capture and impermanent loss. Narrower ranges earn higher fees per dollar deployed but lose more value when price exits the range. Out of range positions earn zero fees and accumulate impermanent loss until price returns or the LP rebalances.

Transaction Routing and Sandwich Attack Exposure

DEX aggregators route trades across multiple liquidity sources (AMM pools, order books, bridges) to minimize slippage. A large swap might split into portions routed through Uniswap, Curve, and Balancer pools simultaneously, executing multiple contract calls in a single transaction.

Mempool visibility exposes pending transactions to front running. Sandwich attacks bracket a target swap with two transactions: one that trades ahead of the victim to move price unfavorably, and another that trades immediately after to capture the spread. The attacker profits from the victim’s slippage. Maximum extractable value (MEV) searchers monitor the mempool for large swaps, simulate sandwich profitability net of gas costs, and bid for block inclusion priority.

Slippage tolerance settings partially mitigate sandwiches by reverting trades that execute beyond a specified price threshold, but wide tolerance windows still allow extraction. Private transaction pools and MEV protection services (Flashbots Protect, MEV Blocker) route transactions directly to block builders, bypassing the public mempool at the cost of slightly delayed inclusion.

Worked Example: Multi Hop Swap Execution

An operator wants to swap 50,000 USDC for TOKEN on Ethereum. TOKEN/USDC has shallow liquidity (200,000 USD depth), but TOKEN/ETH and ETH/USDC are deep (5,000,000 USD each). A direct swap would incur 8% slippage. The aggregator routes through two pools:

  1. Swap 50,000 USDC to ETH via the ETH/USDC pool (0.05% fee): receives approximately 24.9875 ETH (negligible slippage on deep pool).
  2. Swap 24.9875 ETH to TOKEN via the TOKEN/ETH pool (0.3% fee): receives TOKEN at 1.2% slippage due to moderate depth.

Total cost: 0.35% in fees plus 1.2% slippage, versus 8% on the direct route. The transaction bundles both swaps atomically. If either leg fails (slippage exceeds tolerance or liquidity disappears), the entire transaction reverts and no funds move.

Common Mistakes and Misconfigurations

  • Setting slippage tolerance too wide: 5% or 10% tolerance invites sandwich attacks. Use the minimum tolerance that accommodates expected pool slippage, typically 0.5% to 1% for liquid pairs.
  • Ignoring approval front running: Unlimited token approvals let contracts spend any amount from your wallet. Some tokens allow approval changes to be front run, enabling an attacker to drain the old allowance before the new one applies. Use incremental approvals for untrusted contracts.
  • Swapping at pool extremes: Trading when a pool is severely imbalanced (one reserve depleted) yields exponentially worse rates. Check pool reserves before large trades.
  • Assuming instant finality: Treating a confirmed transaction as immediately final can lead to losses if chain reorganizations occur (more common on smaller chains or during consensus anomalies).
  • Underestimating gas variance: Gas prices spike during volatility or network congestion. Transactions submitted with insufficient gas limits sit pending or revert, wasting fees. Monitor real time base fees and priority fees.
  • Liquidity provision without price monitoring: Depositing into a pool and ignoring price movement leads to uncompensated impermanent loss. Active LPs rebalance ranges or exit positions when divergence thresholds are breached.

What to Verify Before You Rely on This

  • Current pool composition and depth: Reserves shift constantly. Query pool state immediately before execution to validate slippage estimates.
  • Fee tier: Pools for the same pair may exist at multiple fee levels (0.05%, 0.3%, 1%). Routing algorithms select optimal tiers based on trade size and depth.
  • Contract audit status: Verify that the DEX contracts have been audited by reputable firms and check for any disclosed vulnerabilities or exploits since the audit.
  • Oracle dependencies: Some DEXs use price oracles for features like limit orders or perpetuals. Confirm the oracle source (Chainlink, Uniswap TWAP) and update frequency.
  • Governance token control: Protocol parameters (fees, pools, upgrade permissions) may be governed by token holders. Review recent governance proposals for parameter changes.
  • Bridge risk for crosschain DEXs: DEXs aggregating liquidity across chains rely on bridges. Assess bridge security model (multisig, optimistic, zero knowledge) and historical incident record.
  • Sequencer uptime for L2 DEXs: Rollup sequencers can experience downtime or censorship. Check sequencer status and fallback mechanisms (forced inclusion queues).
  • Token compatibility: Some ERC20 tokens implement nonstandard behaviors (transfer fees, rebasing, pausing). Test small amounts before large swaps with unfamiliar tokens.
  • Mempool privacy options: Determine whether the chain or DEX supports private transaction submission to mitigate front running.
  • Regulatory restrictions: Some DEX frontends apply geographic or IP based restrictions. Verify access method aligns with compliance requirements.

Next Steps

  • Simulate trades before execution: Use DEX interfaces or aggregator APIs to preview routing, slippage, and gas costs. Compare multiple aggregators for the same trade.
  • Monitor pool health metrics: Track trading volume, liquidity depth, and fee earnings for pools you interact with. Declining metrics signal deteriorating execution quality.
  • Test MEV protection services: Route a test transaction through a private mempool service and compare execution price to public mempool routing under similar conditions.

Category: Crypto Exchanges