Building a Uniswap Aggregator Bot: When to Route Through V2, V3, V4, and UniswapX Simultaneously

A trader placing a 500 ETH order across Uniswap encounters a practical problem: the optimal execution path is not static. Routing entirely through Uniswap V3’s concentrated liquidity might execute 300 ETH at the best price but leave 200 ETH with severe slippage. The same order split across V2’s simpler pools, V3’s multiple fee tiers, V4’s customizable hooks, and UniswapX’s intent-based architecture might each handle different tranches at different costs. No single version is optimal for all sizes or market conditions. An aggregator bot that evaluates all available routes simultaneously, accounting for gas costs, MEV exposure, and time-to-execution, becomes the practical solution for serious traders and protocols managing substantial volume.

Building such a bot requires understanding not just the mechanics of each Uniswap version, but the tradeoffs between them. V2 offers predictable pool behavior and lowest fees for smaller trades but cannot compete on large orders. V3 introduces concentrated liquidity and fee flexibility but demands more precise routing logic and carries higher gas overhead. V4 extends that with custom execution logic through hooks but introduces additional contract complexity. UniswapX operates differently entirely, submitting signed intents to solvers rather than calling smart contracts directly, which eliminates gas costs but introduces execution uncertainty and solver incentive alignment. The aggregator must treat each as a distinct execution option with its own risk and efficiency profile.

Architecture diagram showing order routing flow through Uniswap V2, V3, V4, and UniswapX, with price comparison and execution path selection.

The core challenge: Multi-version liquidity fragmentation

Uniswap’s evolution created a liquidity landscape where the best execution is almost never contained in a single version. V2 pools remain active and serve smaller trades efficiently because of their straightforward constant-product formula and 0.3% default fee. Major stablecoin pairs still concentrate significant volume in V2, especially on Layer 2 networks where gas costs favor simplicity. However, V2 pools cannot compete on large orders because the execution price deteriorates linearly as the trade size grows relative to the liquidity pool.

V3 introduced concentrated liquidity, allowing providers to specify a price range and earn fees only on capital deployed within that range. This created multiple pools for the same token pair at different fee tiers—0.01%, 0.05%, 0.30%, and 1.00% are standard. A large order may be best executed partially through the 0.01% fee tier where tight liquidity exists, with the remainder routed through higher fee tiers with deeper reserves. The tradeoff is computational: identifying which V3 tick boundaries hold liquidity and calculating the exact amount executed at each price level requires more data and calculation than V2’s simple formula.

V4 introduces custom execution hooks that allow pools to implement custom logic—rebates, MEV burns, or conditional liquidity—directly within the pool contract. An aggregator may find that a V4 pool with a MEV-burning hook provides better net execution than a V3 pool offering lower fees but higher MEV exposure. However, V4 pools are still early in adoption, and routing logic must account for hook-specific behavior that cannot be generalized.

UniswapX, the intent-based layer, operates outside the traditional AMM model. Instead of calling a pool contract, users sign an intent specifying the input and minimum output. Solvers compete to fill that intent profitably. Gas costs become zero for the user—the solver covers them if filling is profitable. The tradeoff is execution uncertainty: no guaranteed fill price exists until the intent is filled and confirmed on-chain. For volatile markets or time-sensitive orders, the delay between intent submission and settlement introduces additional risk that a pool-based route does not face.

Liquidity data collection and price calculation across versions

An effective aggregator must maintain real-time or near-real-time data on liquidity across all pools and versions. For Uniswap V2, this means querying reserve balances from every active pair and applying the constant-product formula: `reserve1 * (reserve1 + inputAmount) = reserve0 * (reserve0 – outputAmount)`. Scanning all relevant pairs quickly is computationally intensive but necessary; missing a low-fee route because data was stale can mean execution failure or suboptimal results.

V3 adds complexity because liquidity is concentrated at specific price ticks. The bot must identify which ticks in the relevant fee tier pools contain liquidity, calculate how much of the input amount executes at each tick, and account for the fee paid on each segment. This requires decoding tick state from the pool contract or using an indexing service. The UniswapX or sites.google.com/uniswap-dex.app/uniswap-trade-crypto Subgraph can provide historical data, but real-time optimization demands either direct contract calls or a specialized indexing provider.

V4 pool data follows a similar pattern to V3 but may include hook-specific state that alters the execution model. A fee-rebate hook, for example, might reduce the effective fee below the nominal rate based on user history or volume. The aggregator must either call the hook’s state-reading functions directly or maintain a curated list of known hook types and their behavior.

Price impact calculations must also account for which network and version will be used. The same token pair on Ethereum mainnet has different liquidity than on Arbitrum or Optimism. Layer 2 versions often have lower absolute liquidity, leading to worse execution prices, but lower gas costs can offset the difference for smaller orders. The bot must store and refresh liquidity snapshots for each relevant network separately.

Gas cost modeling and execution path optimization

Gas costs vary dramatically by version and network. A V2 swap on Ethereum mainnet typically costs 100,000–150,000 gas. A V3 swap on the same network can cost 150,000–200,000 gas due to tick-crossing logic and additional state reads. V4 swaps are still being optimized but currently cost more because of hook execution overhead. On Layer 2 networks like Arbitrum, the base gas cost in compute units is similar, but the cost in USD can be 50–100 times lower because of lower per-gas fees.

A proper aggregator models gas costs as a function of order size and expected execution path, then compares total cost (price impact + gas) rather than price alone. For a 1,000 USDC order on Ethereum, V2’s cheaper gas might outweigh V3’s better pricing. For a 10 million USDC order, V3’s ability to split across multiple fee tiers without proportional gas increases makes it preferable despite higher base cost. UniswapX introduces a different calculus: no gas cost, but an unknown solver spread that might exceed the on-chain gas cost for smaller orders.

The aggregator should implement a post-execution cost analysis mechanism. After routing through an optimal path based on predicted values, the bot should compare the actual outcome against simulated alternatives to refine its model. If a route consistently outperforms predictions, increase its weighting in future decisions. If it consistently underperforms, this suggests either stale data or a calculation error in the routing logic that must be investigated.

MEV exposure and protection across routing options

Maximal extractable value (MEV) represents the profit that can be made by observing pending transactions and reordering or censoring them. A large swap broadcast as a public mempool transaction is exposed to sandwich attacks: other transactions front-running or back-running the swap to profit at the user’s expense. Different routing options provide different MEV protections.

V2 and standard V3 routing through the public mempool offers no MEV protection unless wrapped in a private relay like MEV-Blocker or Flashbots Protect. The order is visible to builders and validators before confirmation, enabling sandwich attacks. UniswapX, by contrast, explicitly incorporates MEV protection into its design: solvers must provide a minimum output guarantee, and encrypted intent submission delays order visibility until confirmation. The tradeoff is that UniswapX solvers capture the MEV profit rather than miners, and the protocol design ensures a minimum MEV rebate to the user.

V4 pools can implement hook-based MEV burning, where captured MEV is burned rather than redistributed. A pool with an active MEV-burning hook provides MEV protection superior to unprotected V2 or V3, but the protection is tied to that specific pool and its hook implementation. An aggregator evaluating a V4 pool with MEV-burning should recognize this as equivalent to MEV protection and weight it accordingly when a user has expressed concern about sandwich attacks.

The aggregator should allow users to specify MEV exposure tolerance: maximum acceptable slippage from sandwich attacks, timeout for UniswapX intent settlement, or mandatory use of MEV-protecting routes. For institutional users managing significant volume, this preference should override pure price optimization. A slightly worse on-chain price through a protected route may be preferable to risk an unknown amount of MEV extraction.

Intent-based execution and solver incentive alignment in UniswapX

UniswapX functions as a solver network: users submit signed intents, and solvers compete to fill them. The filled intent is then submitted to the blockchain for confirmation. This model eliminates gas costs for users and allows solvers to route through off-chain liquidity sources—aggregators, market makers, or cross-chain paths—before settling on-chain if needed.

The key risk is execution uncertainty. Between submitting an intent and having it confirmed, market prices move. A solver may become unwilling to fill an order because the input amount no longer generates a profitable trade at the minimum output specified. The user must then resubmit with worse terms or wait for market conditions to improve. For time-sensitive orders or highly volatile tokens, this delay can be costly.

An aggregator bot should model UniswapX as an asynchronous execution option rather than a direct comparison with on-chain routes. If the intent is submitted and a timeout is specified, the bot should simultaneously prepare a fallback on-chain route to execute if UniswapX does not confirm within that window. The solver network also introduces counterparty risk: solvers could collude to avoid filling certain orders, though the competitive structure and economic incentives make this difficult at scale.

Solver selection within UniswapX also matters. Different solvers offer different service quality, speed, and minimum order size. An aggregator that interfaces with UniswapX should route to solvers with strong historical fill rates and competitive spreads for the token pair in question. This typically requires direct integration with solver APIs rather than relying on a generic submission layer.

Smart contract interactions and execution atomicity

An on-chain aggregator must execute its routing decision atomically—all routes succeed, or the entire transaction reverts. This requires structuring the swap as a series of internal contract calls within a single transaction. V2 swaps use the `swap` function with input and output amounts. V3 swaps use `exactInputSingle` or `exactOutputSingle` depending on whether the order specifies exact input or exact output. V4 swaps follow a similar pattern but may include additional hook initialization.

The aggregator contract must specify the recipient address correctly for each sub-route. If V2 routes to intermediate token A, and V3 routes from A to the final token B, the V2 swap must specify the aggregator contract as the recipient, not the final user. This allows the contract to accumulate intermediary tokens and route them through the next version without additional user interactions. Gas efficiency improves by batching transfers at the end rather than sending each intermediate token to the user and requiring them to re-approve and re-submit.

Slippage protection across the complete route is also complex. The user specifies a maximum acceptable output after all routes complete, but intermediate prices affect the calculation. If V2 executes and produces less output than expected due to price movement, the remaining input may need to be routed differently. Some aggregators implement a “recalculation” step: after each sub-route executes, recalculate the remaining order and select the best route for the remainder. This adds gas cost but can improve overall execution quality.

Architectural decisions: Off-chain optimization versus on-chain flexibility

Most production aggregators perform heavy lifting off-chain. A bot running on a server queries pool data continuously, runs simulations for incoming orders across all routing options, and submits only the optimal route to the blockchain. This approach minimizes on-chain gas costs because the optimization logic runs without consuming contract storage or computation.

The tradeoff is latency and data staleness. If pool liquidity shifts between the bot’s optimization and on-chain execution, the route may no longer be optimal. The bot must decide whether to accept the slippage or recompute and resubmit, incurring the cost of another transaction. For high-frequency or large orders, this can become expensive.

An alternative approach pushes more logic on-chain. The aggregator contract can accept an order, query current pool states directly, and recalculate the optimal route within the transaction itself. This ensures freshness but increases gas costs significantly because contract-to-contract calls and storage reads become part of the execution. This is practical for smaller, less time-sensitive orders but prohibitive for frequent large trades.

The hybrid approach used by most serious aggregators: off-chain optimization provides the baseline route, but on-chain logic includes fallback routes and simple checks. If price impact exceeds a threshold, the contract rejects the route and requires the user to resubmit or accept worse terms. This balances gas efficiency with robustness.

Testing, monitoring, and iterative refinement

Before deploying an aggregator bot to handle real volume, extensive testing on testnets and in simulations is essential. This means running the bot against historical price data to verify that its routing decisions would have been optimal in past market conditions. Backtesting reveals systematic errors: if the bot consistently overestimates V3 liquidity or underestimates gas costs, the bias can be corrected before real money is at stake.

Post-execution monitoring is equally important. For every order routed, the aggregator should log the predicted outcome, actual outcome, and the difference. Track which routes were selected and whether they outperformed alternatives. If UniswapX intents start consistently timing out, reduce their weighting. If V4 MEV-burning hooks prove unreliable, exclude them until they stabilize. The bot should be designed to adapt to changing market conditions and protocol upgrades.

DeFi trading bots also face practical operational challenges: network congestion during volatile periods, contract bugs or upgrades that break assumed behavior, and mempool games where transaction ordering becomes unpredictable. A robust aggregator includes circuit breakers that pause routing during extreme volatility, maintenance windows for protocol updates, and fallback routes that never rely on a single version or network.

Frequently asked questions

Should my aggregator always split orders across all four Uniswap versions simultaneously?

No. Splitting adds transaction cost and complexity. The aggregator should evaluate all versions separately, select the single best route for the entire order, and only split if the improvement in execution price exceeds the additional gas cost of multiple sub-routes. For most orders, a single optimal route will dominate.

How do I handle Uniswap V4’s custom hooks in my routing logic?

Maintain a curated registry of known hook implementations and their behavior. For unknown hooks, fall back to treating them as standard V3-like pools unless the user explicitly enables experimental routing. Test new hook types thoroughly on testnet before including them in live routing decisions.

What happens if a UniswapX intent fails to fill before my timeout expires?

Your aggregator should have simultaneously prepared a fallback on-chain route (through V2, V3, or V4) that executes on-chain if the intent does not confirm within the specified window. This ensures the order completes even if the solver network is congested or unwilling to fill at current prices.

Lavelle Estates is the trading name of Lavelle Properties Ltd, registered in England and Wales No. 13225206 © Lavelle Estates 2021. All rights reserved.