DEV Community

rim dinov
rim dinov

Posted on

Designing a Real-Time DEX Arbitrage Detector on Base (Uniswap V3 & Aerodrome)


Architectural breakdown of a WETH/USDC arbitrage detector on Base—covering fixed-point price normalization, WebSocket-to-HTTP fallbacks, and stale-price protection.
tags: web3, typescript, ethereum, defi

Monitoring cross-DEX price discrepancies in real time sounds straightforward until you run into practical edge cases: differing pool mechanics, token ordering (token0 vs token1), precision loss on large integers, flaky WebSocket connections, and stale state during quiet market windows.

In this post, I'll share the architecture behind a local arbitrage detector I built with TypeScript and Viem to track WETH/USDC spreads between Uniswap V3 and Aerodrome on Base.

Live Walkthrough

(Short terminal-only run: 44s demo)

System Architecture

Rather than relying on heavy aggregator SDKs or third-party price APIs, the detector reads state directly from two on-chain liquidity pools on Base:

  • Uniswap V3 WETH/USDC (0.05% tier): 0xd0b53D9277642d899DF5C87A3966A349A798F224
  • Aerodrome Volatile WETH/USDC (0.30% tier): 0xcDAC0d6c6C59727a65F871236188350531885C43

On every state update, the engine evaluates both directions (Uniswap -> Aerodrome and Aerodrome -> Uniswap) for a configurable trade size (e.g., $1,000) and calculates estimated net profit after DEX swap fees, a slippage buffer, and Base gas overhead.

1. Normalizing Two Different AMM Models

Because Uniswap V3 and Aerodrome Volatile represent prices differently, both need to be normalized into a single scale-safe USDC per WETH figure before comparing spreads:

  • Token Ordering & Decimals: On startup, the detector queries token0() and token1() on each contract to verify whether WETH (18 decimals) or USDC (6 decimals) sits in position 0, eliminating hardcoded assumptions.
  • Uniswap V3 (sqrtPriceX96): Concentrated liquidity pools emit sqrtPriceX96 as a Q64.96 fixed-point integer inside Swap events and slot0(). Squaring the value, dividing by $2^{192}$, and scaling by decimal differences in integer arithmetic avoids JavaScript floating-point precision loss.
  • Aerodrome Volatile (getReserves): Constant-product pools emit Sync events and expose reserve0 / reserve1. Spot price is derived directly from the decimal-adjusted reserve ratio.

2. Automatic WebSocket-to-HTTP Polling Fallback

Event subscriptions over wss:// (Swap on Uniswap V3 and Sync on Aerodrome) provide the lowest latency, but proxies, local network setups, and RPC rate limits frequently reject WebSocket handshakes with non-101 status code errors.

To stay resilient without manual restarts:

  1. Each pool watcher starts with a WebSocket subscription.
  2. If an onError handshake or transport failure occurs, the watcher intercepts the error and seamlessly switches that specific pool over to HTTP event polling at a fixed interval.
  3. Both pools operate independently—if one transport degrades, the other continues uninterrupted.

3. Stale-Price Guard & Periodic State Synchronization

Purely event-driven bots have a subtle blind spot: if one pool has frequent swaps while the other goes quiet for 30+ seconds, comparing a live price against an old cached event creates false spread signals.

The detector addresses this with two safeguards:

  • Background State Sync: Alongside event listeners, a lightweight timer queries slot0() and getReserves() concurrently every few seconds (with an in-flight lock so slow RPC responses never stack up).
  • Freshness TTL (MAX_PRICE_AGE_MS): Every price update is stamped with a local timestamp. Before running profit math, the detector verifies that both quotes are fresher than the threshold—otherwise, it skips calculation and logs a stale-price status until both pools sync.

Potential Next Upgrades

  • Depth-Aware Price Impact: Modeling exact output amounts against active tick liquidity (Uniswap V3) and reserve depth (Aerodrome) instead of spot prices plus a static slippage buffer.
  • On-Chain Simulation: Verifying executable output via eth_call against QuoterV2 and the Aerodrome Router prior to alerting.
  • Historical Spread Logging: Recording profitable spread windows to structured logs to analyze how long arbitrage opportunities stay open on Base.

If you're building on-chain monitoring tools on Base, how do you handle RPC transport fallbacks and cross-pool synchronization? Let me know in the comments!

Top comments (0)