Building a decentralized exchange means writing and deploying smart contracts that let users swap tokens directly from their own wallets, with pricing set by an on-chain formula or order book instead of a company that holds their funds. The hard parts are choosing a market design that can attract liquidity, getting the contracts audited, and defending users against MEV.
This page is a build guide: the architectural choices, the contracts and off-chain components, and the order of work. If you are instead comparing ready-made DEX scripts and white-label products, read the companion guide to decentralised exchange software.
Pick a market design first
Everything else follows from how your DEX discovers prices and matches trades. There are four mainstream designs in 2026.
Constant-product AMM
Popularized by Uniswap v2, the pool holds two tokens and enforces x ยท y = k: after every trade the product of the reserves stays constant (before fees). Anyone can add liquidity in proportion to the current reserves and receives LP tokens representing their share. It is simple, battle-tested and works for any pair, but capital efficiency is poor because liquidity is spread across every possible price, and LPs suffer impermanent loss when prices move.
Concentrated liquidity
Uniswap v3 let LPs place liquidity inside a chosen price range, represented as NFT positions. That makes far more liquidity available near the current price and allows multiple fee tiers. The cost is complexity: tick math, range management for LPs, and much harder contracts to audit. Uniswap v4, launched in early 2025, moved all pools into a single contract and added hooks, custom code that runs at points in a pool's life cycle, which makes it a platform for building new AMM behavior rather than a design you need to clone.
Stable-swap curves
Curve-style invariants blend constant-sum and constant-product behavior so that assets meant to trade near parity, such as two stablecoins or a token and its liquid-staking version, can trade with very low slippage. Use this when your market is pegged assets, not volatile pairs.
Order books and intents
Fully on-chain central limit order books were impractical on Ethereum mainnet because every order and cancel costs gas, but they work on high-throughput chains and app-specific chains; dYdX moved its v4 to its own Cosmos-based chain for this reason. Intent-based designs such as batch auctions and signed-order protocols let users sign what they want, then have solvers or market makers compete to fill it, which can reduce MEV and improve prices. Aggregators that route across many pools are their own category; see building an aggregator like 1inch.
| Design | Best for | Main weakness | Build complexity |
|---|---|---|---|
| Constant-product AMM | Long-tail tokens, simple launches | Capital inefficiency, impermanent loss | Low |
| Concentrated liquidity | Major pairs, professional LPs | Complex math and LP management | High |
| Stable-swap | Pegged assets | Fragile if a peg breaks | Medium |
| On-chain order book | Active traders on fast chains or app-chains | Needs market makers and high throughput | High |
| Intent / batch auction | MEV protection, best execution | Depends on a healthy solver network | High |
Fork, build on, or write from scratch
Many DEXs started as forks of Uniswap v2. Forking well-audited code is reasonable, but three warnings apply. First, check the license: some AMM releases were published under the Business Source License, which restricts commercial use for a period. Second, a "small" change to forked code invalidates the original audit for that code path; several forks were drained because of exactly such edits. Third, a fork with no distinctive feature has no reason to attract liquidity away from the original.
On Uniswap v4 and similar platforms, a newer option is to build hooks instead of a whole exchange: dynamic fees, on-chain limit orders, or custom oracle logic attached to pools that live inside existing infrastructure. If you want a design walkthrough of the classic clones, see a Uniswap-like DEX and the PancakeSwap-style DEX guide for BNB Smart Chain.
The contracts in a typical AMM DEX
- Factory. Deploys a new pool per token pair (and per fee tier, for concentrated liquidity) and records its address.
- Pool / pair. Holds reserves, enforces the invariant, mints and burns LP shares, collects fees, and exposes a price oracle.
- Router. The contract users actually call. It handles multi-hop paths, wraps native ETH or BNB, enforces the user's minimum output and deadline, and pulls tokens via approvals or signed permits.
- Position manager. In concentrated-liquidity designs, wraps positions as ERC-721 NFTs.
- Governance and fee switch. Optional contracts that let a DAO or multisig turn on a protocol fee, change parameters, or upgrade components through a timelock.
- Incentives. Staking or gauge contracts that distribute reward tokens to LPs. Emissions programs are a separate design problem with their own failure modes.
Off-chain components people forget
A DEX is "decentralized" at the settlement layer, but users still meet it through software you host. Plan for a front end (ideally also pinned to IPFS so it survives your servers), an indexer that turns events into pool, price and volume data (The Graph subgraphs or your own indexer), a token list with sensible defaults and scam warnings, RPC infrastructure, analytics, and monitoring that alerts on abnormal pool behavior. The front end is also where sanctions screening and geographic restrictions are usually enforced, if your legal advice says you need them.
Security: the part that decides whether you survive
DEX exploits tend to come from a handful of patterns:
- Price-oracle manipulation. Using a pool's instantaneous spot price as an oracle lets an attacker move it with a flash loan in the same transaction. Use time-weighted averages or external oracles, and understand their limits.
- Reentrancy and callback abuse. Token callbacks, hooks and flash swaps all reenter your code. Guard state transitions carefully.
- Rounding and precision. Fixed-point math errors in favor of the user, repeated many times, can drain a pool.
- Non-standard tokens. Fee-on-transfer, rebasing and tokens that return no boolean break naive accounting.
- Admin key risk. Upgradeable contracts controlled by a single key are a central point of failure. Use a multisig and a timelock.
Budget for at least one independent audit of the final code, ideally two for novel math, plus a public bug bounty after launch. Our explainer on smart contract audits covers what an audit does and does not guarantee.
MEV and user protection
Public mempools let bots front-run and sandwich swaps. You cannot remove MEV from an AMM, but you can limit the damage: default to tight slippage tolerances, enforce deadlines, offer private transaction submission through protected RPC endpoints, and consider batch-auction or intent-based execution for large orders.
Choosing a chain
Ethereum mainnet offers the deepest liquidity and most composability but the highest fees. Layer 2 rollups such as Arbitrum, Optimism, Base and ZKsync Era offer EVM compatibility at a fraction of the cost and are where much new DEX activity happens. BNB Smart Chain has large retail volume. Non-EVM chains such as Solana require entirely different programs and tooling. Multi-chain deployments multiply your audit and monitoring work, so launch on one chain and expand when there is demand.
Build process
- Define the market. Which assets, which users, and why liquidity will come to you rather than an incumbent.
- Specify the mechanism. Write the invariant, fee model, oracle approach and governance powers down before coding.
- Implement and test. Unit tests, fuzzing and invariant tests (Foundry is the common choice), plus fork tests against mainnet state.
- Audit and fix. Freeze the code, audit, fix, and re-review the fixes.
- Testnet and guarded launch. Deploy with caps or allow-listed pools, monitor, then lift limits.
- Bootstrap liquidity. Seed pools, partner with market makers or run time-limited incentives with clear end dates.
- Operate. Monitoring, incident runbooks, bug bounty, and a governance process for upgrades.
Cost and timeline drivers
As a reasoned estimate: a carefully modified fork of a well-known AMM with a custom front end, built by a small team of two or three smart-contract and front-end engineers over two to four months, plus one audit, typically lands in the low-to-mid six figures in US dollars once audit fees are included. A novel mechanism, such as a new invariant, an order book on an app-chain or a solver network, can take a larger team a year or more. The biggest variables are novelty of the math, number of chains, number of audits, and whether you need governance and token infrastructure at launch.
Frequently asked questions
How is a DEX different from a centralized exchange?
A DEX settles trades in smart contracts and users keep custody of their tokens until the swap executes. A centralized exchange holds customer funds and runs an internal order book. See the white-label exchange guide for the centralized model.
Can I just fork Uniswap?
You can fork code whose license allows it, but you still need an audit of any changes, your own liquidity, and a reason for users to come. Forks without differentiation rarely attract lasting liquidity.
Which AMM design should I start with?
Constant-product for long-tail and new tokens, stable-swap for pegged assets, and concentrated liquidity or v4-style hooks if you are targeting major pairs and professional LPs.
How do DEXs make money?
Swap fees go mainly to liquidity providers. A protocol can take a share through a fee switch, charge front-end fees, or earn from its token treasury, each with different legal and competitive implications.
How long does it take to build a DEX?
A modified fork can reach audited mainnet in a few months. A genuinely new mechanism usually takes a year or more including multiple audits.