DEX aggregator development: how to build one that routes well
How a DEX aggregator actually works: pool indexing, route search, split routes, quote APIs, gas-aware pricing, MEV protection and the router contract that holds it together.

DEX aggregator development comes down to three systems: an off-chain engine that keeps a live copy of every pool's state and searches it for the best route, an API that turns that route into a quote and a transaction, and an on-chain router contract that executes the whole route atomically and reverts if the user gets less than their minimum. Most of the engineering effort sits in the first one. The contract is small, but it is the part that can lose user funds, so it gets the most review.
What an aggregator does that a DEX does not
A DEX owns liquidity. An aggregator owns none. It reads pools from many DEXs, finds the combination of pools that returns the most output for a given input, and executes that combination in one transaction. The value it sells is execution quality, which is why aggregators skip the liquidity cold start that makes launching a new DEX so hard. We covered that tradeoff in more detail in our crypto exchange MVP guide.
Two techniques produce most of the improvement over a single DEX:
- Multi-hop routes. Going USDC to WETH to a long-tail token through two deep pools often beats one shallow direct pool.
- Split routes. Sending 60% of the order through one pool and 40% through another keeps each pool's price impact lower. 1inch describes its Pathfinder router as splitting between different protocols and even different market depths within one protocol.
The catch is that every extra hop and split costs gas. A route that wins by $3 on output and loses $5 on gas is a worse route. That single fact shapes most of the design.
The architecture in one table
| Component | What it does | Where it runs | What breaks if it is wrong |
|---|---|---|---|
| Pool indexer | Discovers pools, tracks reserves, ticks, fees in real time | Off-chain, close to an RPC or node | Stale quotes, failed transactions |
| Pricing adapters | Simulates a swap for each pool type (constant product, concentrated liquidity, stable curves, order books) | Off-chain, in memory | Wrong outputs, routes that revert |
| Route search | Finds the best path and split for an input amount, net of gas | Off-chain | Mediocre prices, slow quotes |
| Quote and swap API | Returns price, builds calldata, handles approvals | Off-chain, public endpoint | Integrators leave |
| Router contract | Executes the route, enforces minimum output | On-chain | Lost funds |
| Simulation and monitoring | Checks routes before sending, tracks revert rate and quote accuracy | Off-chain | You find problems from users |
Step 1: index the pools
Route search is only as good as the state it searches. You need every relevant pool on the chain and its current state, updated every block.
Start with a factory crawl. Most DEXs deploy pools through a factory contract that emits an event on creation, so you backfill those events and subscribe to new ones. Then track state changes. For a constant-product pool that means reserves after each Sync or swap event. For concentrated liquidity pools it means current price, active liquidity and the initialized ticks around the price, which is far more data per pool.
A few practical points from building these:
- Run your own node or a dedicated RPC. Shared RPC rate limits will throttle you exactly when volume spikes. See our blockchain indexer comparison for the general indexing tradeoffs; an aggregator's pool tracker is one of the clearest cases for a custom, in-memory indexer.
- Handle reorgs. If a block gets replaced, your pool state has to roll back with it.
- Filter junk pools. Pools with tiny liquidity, fee-on-transfer tokens or tokens with transfer restrictions will poison routes. Keep an allowlist or a scoring rule and a way to blacklist a token quickly.
Step 2: write a pricing adapter per pool type
Each DEX design needs its own swap math. Constant product is a few lines. Concentrated liquidity requires walking ticks. Stable-swap curves need the exact invariant the pool uses. Hooks and custom curves can change behavior per pool.
You have two choices for each adapter:
- Reimplement the math off-chain. Fast, which matters because route search calls it thousands of times per quote. The risk is drift from the on-chain result.
- Call the DEX's quoter contract. Exact, but slow. Uniswap's own docs note that QuoterV2 functions are not gas efficient and should not be called on chain, and they work by simulating the swap and reverting. Off-chain via
eth_callthey are fine for verification, too slow for search.
Our default is native math for search, then one simulation of the final route before returning it. Test every adapter against the real contract on a fork across many random amounts. A 0.1% systematic error in one adapter will quietly make your aggregator pick that DEX too often.
Step 3: route search, net of gas
The search problem is a graph: tokens are nodes, pools are edges, edge weights depend on amount. You want the path set and split that maximizes output minus gas cost converted to the output token.
A workable approach for an MVP:
- Limit hops. Two or three hops cover nearly all useful routes. Deeper search costs latency and rarely wins after gas.
- Pick candidate paths through a small set of connector tokens (the chain's native wrapped token, the main stablecoins, a few liquid majors).
- Split the input into chunks and assign each chunk greedily to whichever candidate path gives the best marginal output.
- Merge chunks that ended up on the same pool, because each separate swap step costs gas. 1inch describes its current Pathfinder version as merging paths to achieve better gas cost efficiency.
- Subtract estimated gas per hop and per split, priced in the output token, and compare the net results.
For gas, use a per-pool-type cost table measured from real transactions, then confirm with eth_estimateGas on the final route. Uniswap's quoter returns a gasEstimate alongside the output amount, which is a useful calibration point for concentrated liquidity hops.
Latency matters as much as price. A quote that takes three seconds is stale on a fast chain before the user clicks. Keep pool state in memory, precompute candidate paths per token pair, and cap search time.
Step 4: the quote and swap API
Even if you only plan a consumer frontend, design the API as if wallets and other apps will integrate it. That is where aggregator volume tends to come from.
The established pattern splits pricing from execution. 0x's Swap API, for instance, has a /price endpoint that returns indicative pricing without creating a full order or transaction, and a /quote endpoint that returns a firm quote with calldata. Copy that shape. Your API should return:
- Expected output, minimum output after slippage, price impact
- The route (pools and percentages), so integrators can show it
- Gas estimate and the approval target
- Ready-to-sign transaction calldata
- Any issues, such as insufficient allowance or balance
Add API keys, per-key rate limits and an integrator fee parameter.
Step 5: the router contract
The router receives the user's tokens, executes each step against the target pools, checks that the final output is at least minAmountOut, and sends the output to the user. If the check fails, the whole transaction reverts. That atomic revert is the user's main protection against stale quotes.
Keep the router as dumb as you can. It should not hold balances between transactions and should not have an owner function that moves user tokens. Aggregator routers are a known target because users grant them token approvals. In July 2024, LI.FI lost an estimated $11.6 million after a new contract facet let an attacker make arbitrary calls and pull tokens from wallets that had granted infinite approvals. Users with exact approvals were not affected.
Lessons we apply:
- Never let user-supplied calldata reach an arbitrary
callon an arbitrary target. Whitelist targets and function selectors. - Default to exact-amount approvals in your frontend, or use Permit2, where signed permissions are time-limited and optionally amount-limited.
- Treat every new adapter added to the router as new attack surface, audited before deployment.
- Get the router audited, and fuzz it against the invariant "user output is at least minimum, router balance is unchanged after every call". Our post on smart contract security ROI covers how to budget for that.
Step 6: MEV protection
A swap with a public slippage tolerance is an invitation to be sandwiched: a bot buys ahead of you, lets your trade push the price up, and sells right after. Your minimum output limits the damage but the bot will take everything up to it.
Options, roughly from cheapest to most involved:
| Approach | How it helps | Cost to you |
|---|---|---|
| Tight default slippage, adaptive per pair | Caps what a sandwich can extract | Some extra reverts on volatile pairs |
| Private transaction submission | Keeps the transaction out of the public mempool; Flashbots Protect does this on Ethereum and skips transactions that would revert | Chain-specific, depends on builder support |
| Intent-based settlement with solvers | Users sign an order, solvers compete to fill it; CoW Protocol gives every order for the same pair in an auction one clearing price, which makes transaction order irrelevant within the block | Large build, needs a solver network |
For an MVP, adaptive slippage plus private submission where the chain supports it is the right call. Intent systems are a second product, not a feature.
Check the chain first, though. On chains with a single sequencer or different block building, mempool MEV may look very different from Ethereum, and the right defense changes with it.
Step 7: simulate, monitor, iterate
Before returning a firm quote, simulate the exact transaction against the latest block. Drop routes that revert. After launch, track:
- Quote accuracy: quoted output vs realized output, per DEX adapter
- Revert rate, split by cause (slippage, gas, adapter bug)
- Quote latency at p50 and p99
- Win rate against other aggregators on the same chain for sampled pairs
The last one is the honest scoreboard. If a competitor beats you on most large trades, integrators will notice before you do.
What it looks like in practice
We built Hyperbloom, a DEX aggregator and yield platform on HyperEVM, with a four-person team starting in June 2025. Its router compares prices across 12 exchanges, including HyperSwap, KittenSwap, Curve and Valantis, and uses split and multi-hop routes. The routing algorithm weighs liquidity depth, gas cost and slippage in real time, and each trade executes in one transaction through the aggregator contract. It also ships a REST swap API with quote, price and transaction-building endpoints behind API keys. It has processed more than $300M in total volume. If you are building on that chain specifically, our HyperEVM overview explains why its block design suits trading products.
Build, fork or license
You do not have to write all of this from scratch. The real options:
- Integrate an existing aggregator API into your wallet or app. Fastest, but your execution quality and margin depend on someone else.
- Use white-label aggregator infrastructure with your brand, fees and chain set. We compare those options in white-label DeFi: build vs buy.
- Build your own when you are on a chain the big aggregators cover poorly, when routing quality is your product, or when you need custom liquidity sources.
Our planning estimates for a custom aggregator MVP on one EVM chain: 8 to 14 weeks for a small senior team covering indexer, adapters for the main DEX types, routing, API, router contract and frontend, plus an audit of the router. Each additional pool type with unusual math adds a week or two. Supporting a second chain is cheaper than the first, as long as the pool designs repeat.
FAQ
How does a DEX aggregator find the best price?
It keeps a live copy of pool states across many DEXs, simulates swaps through candidate paths, splits the order across pools to reduce price impact, and subtracts estimated gas from each candidate. The route with the highest net output wins.
How long does it take to build a DEX aggregator?
By our planning estimates, 8 to 14 weeks for an MVP on one EVM chain with a senior team, plus audit time for the router contract. Chains with many unusual pool types take longer.
Is a DEX aggregator custodial?
A well-designed one is not. The router contract only holds tokens during a single transaction and enforces a minimum output, so users keep custody before and after the swap. Check that no admin function can move user tokens or approvals.
How do DEX aggregators protect against MEV?
The common methods are tight slippage defaults, private transaction submission such as Flashbots Protect on Ethereum, and intent-based settlement where solvers compete to fill orders, as CoW Protocol does.
How do DEX aggregators make money?
Usually through a small fee on swaps, positive slippage capture, or revenue shares with integrators that route volume through their API. Be transparent about which you use, because integrators compare net output.
Talk to us
If you are planning an aggregator, or adding swap routing to a wallet or DeFi product, we have built this stack on a live chain and can help you decide what to build and what to reuse. Contact 23studio and tell us which chain and pairs you are targeting.
