Cipherbase
BTC ETH XMR
DeFi Entry 02 of 20

Decentralized Exchanges (DEX): How They Work and Why They Matter

Decentralized exchanges (DEXes) let you trade crypto directly from your wallet using smart contracts — no account, no KYC, no custodial risk. They are one of the core building blocks of DeFi. This guide covers how they work, the different models, and their real-world tradeoffs.

Animated diagram of two tokens entering a liquidity pool and LP tokens coming out.
Animated diagram of two tokens entering a liquidity pool and LP tokens coming out.
On this page
  1. How DEXes Work
  2. Types of DEXes
  3. Providing Liquidity and Its Risks
  4. Gas Optimization When Using DEXes
  5. MEV and DEX Trading
  6. Comparing Leading DEXes

Decentralized exchanges are one of the foundational building blocks of DeFi. Unlike traditional exchanges that hold your funds and match orders through a central system, DEXes let you trade directly from your wallet using smart contracts. No account creation, no KYC, no custodial risk. Understanding how they work and their tradeoffs is essential for anyone serious about navigating DeFi.


How DEXes Work

At the core of every DEX is a smart contract that enforces trade logic on-chain. When you swap tokens, you're interacting with that contract directly. Your wallet signs the transaction, the contract executes the trade, and the result lands in your wallet — all without a third party touching your funds at any point.

Most modern DEXes use an Automated Market Maker (AMM) model rather than a traditional order book. Instead of matching buyers with sellers, AMMs use liquidity pools (reserves of two or more tokens) and a pricing formula to determine exchange rates automatically.

The Constant Product Formula

Uniswap popularized the x * y = k formula, where x and y are the token reserves in a pool and k is a constant. Every trade adjusts the ratio of tokens in the pool, which shifts the price. The larger the trade relative to pool size, the more the price moves — a phenomenon called price impact or slippage.

Say a pool holds 100 ETH and 200,000 USDC:

x = 100 ETH
y = 200,000 USDC
k = 100 * 200,000 = 20,000,000

If you buy 10 ETH, the pool must now hold 90 ETH. To keep k constant:

90 * y = 20,000,000
y = 222,222 USDC

You paid roughly 22,222 USDC for 10 ETH (an effective price of ~2,222 USDC/ETH), slightly higher than the pool's starting price of 2,000 USDC/ETH. That difference is your price impact.


Types of DEXes

Not all DEXes work the same way. The right choice depends on what you're trading and how much you care about cost versus precision.

DEX TypeMechanismBest ForExamples
AMM (constant product)x * y = k formulaGeneral token swapsUniswap v2, SushiSwap
Concentrated liquidity AMMLPs set price rangesCapital-efficient LPUniswap v3, Camelot
Stable AMMStableSwap curveStablecoin/pegged assetsCurve Finance
Order book DEXBids and asks on-chainPrecise limit ordersdYdX, Serum (Solana)
DEX AggregatorRoutes across multiple DEXesBest price execution1inch, Paraswap

Curve Finance uses a hybrid curve optimized for assets that trade near parity, like USDC/USDT or stETH/ETH. This dramatically reduces slippage for stable swaps compared to a standard AMM.

DEX aggregators like 1inch don't hold liquidity themselves. They split your trade across multiple pools and DEXes to find the best net price, accounting for fees and slippage. For large trades, this often beats going to a single DEX directly.


Providing Liquidity and Its Risks

Liquidity providers (LPs) deposit token pairs into pools and earn a share of the trading fees generated. On Uniswap v2, LPs earn 0.3% of every swap proportional to their share of the pool. On Uniswap v3, fees can be 0.05%, 0.3%, or 1% depending on the pool tier.

Impermanent Loss

The main risk LPs face is impermanent loss (IL) — the difference in value between holding tokens in a pool versus holding them in your wallet. It happens when the price ratio of your pooled tokens diverges from what it was when you deposited.

Here's a concrete example. You deposit 1 ETH and 2,000 USDC when ETH is worth $2,000. ETH later rises to $4,000, and arbitrageurs rebalance the pool. You end up with less ETH and more USDC than you started with. You still profited in dollar terms, but less than if you'd simply held the tokens. That shortfall is the impermanent loss.

It's only "impermanent" if prices return to the original ratio, which often doesn't happen. For volatile asset pairs, fee income needs to meaningfully exceed IL for an LP position to actually be profitable.

Concentrated Liquidity

Uniswap v3 introduced concentrated liquidity, letting LPs allocate capital within a specific price range rather than spreading it across the entire curve. A position set to the $1,800–$2,200 ETH range earns fees only when ETH trades in that band, but it earns far more fees per dollar deployed while price stays within range. Capital efficiency goes up significantly, but so does the management burden.


Gas Optimization When Using DEXes

On Ethereum mainnet, gas costs can meaningfully affect the economics of small trades. A few practical strategies help reduce what you pay.

Batch transactions where possible. Some DEX routers and aggregators let you approve and swap in a single transaction using permit signatures (EIP-2612), eliminating the separate approval transaction entirely.

Trade during low-congestion windows. Gas prices on Ethereum follow predictable patterns — weekday business hours in US/EU timezones tend to run more expensive. Tools like Etherscan Gas Tracker show real-time and historical gas trends.

Use L2s and alternative chains. Uniswap and Curve are both deployed on Arbitrum, Optimism, Base, and Polygon, where the same swap might cost $0.10 instead of $15.

# Check current gas prices via Ethereum JSON-RPC
curl https://mainnet.infura.io/v3/YOUR_PROJECT_ID \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}'

Set appropriate slippage tolerance. Too high and you're exposed to sandwich attacks. Too low and your transaction reverts, wasting the base gas fee. For stable pairs, 0.1% is reasonable; for volatile tokens, 0.5–1% is typical.


MEV and DEX Trading

MEV (Maximal Extractable Value) is profit extracted by reordering, inserting, or censoring transactions within a block. DEX trades are a primary MEV target because every pending swap is visible in the mempool before it confirms.

Sandwich Attacks

A sandwich attack is the most common MEV attack against DEX users. A bot detects your pending swap, places a buy order immediately before it and a sell order immediately after. Your trade moves the price, the attacker sells into the price you created, and you receive fewer tokens than expected.

A few ways to protect yourself. Private mempools like Flashbots Protect or MEV Blocker route your transactions directly to block builders without public mempool exposure. Tightening your slippage tolerance reduces the profitability window for sandwich bots. Some DEX aggregators also have MEV protection built into their routing, so you get it without thinking about it.

“Decentralized finance is the future of money.”

— Unknown

MEV is something you'll encounter no matter where you start in DeFi, because it directly affects trade outcomes and fairness at the protocol level.


Comparing Leading DEXes

DEXChain(s)FeeNotable Feature
Uniswap v3ETH, Arbitrum, Optimism, Base, Polygon0.05%–1%Concentrated liquidity ranges
Curve FinanceETH + 10+ chains0.04%–0.4%Optim

Frequently Asked Questions

What is a decentralized exchange (DEX) and how is it different from a regular exchange?

A DEX is a platform that lets you trade cryptocurrencies directly with other users without a company or middleman holding your funds. Unlike centralized exchanges like Coinbase or Binance, a DEX runs on smart contracts, so you stay in control of your wallet the entire time.

Do I need to create an account to use a DEX?

No, DEXs don't require sign-ups, email addresses, or identity verification. You just connect a crypto wallet like MetaMask and you're ready to trade.

Why are fees sometimes so high on a DEX?

Most DEX fees come from two sources: the platform's trading fee and the network's gas fee for processing your transaction on the blockchain. Gas fees can spike during busy periods on networks like Ethereum, so many beginners use lower-cost chains like Arbitrum or Polygon to reduce costs.

Video Resources

Sources & Further Reading

  • Uniswap Docs — Protocol documentation for the leading automated market maker.
  • Finematics — Educational explainers on DeFi mechanisms with diagrams.
  • DeFi Llama — Total value locked and protocol analytics across chains.
  • Ethereum.org: DeFi — Official introduction to decentralised finance on Ethereum.
  • Aave Docs — Lending protocol documentation, risk parameters and governance.
  • Compound Docs — Documentation for the Compound money market protocol.
  • Lido Docs — Liquid staking protocol documentation.