Multi-Hop Swaps System Development

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1 servicesAll 1306 services
Multi-Hop Swaps System Development
Complex
~1-2 weeks
FAQ
Blockchain Development Services
Blockchain Development Stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1214
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_logo-advance_0.png
    B2B Advance company logo design
    561
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823

Developing Multi-Hop Swap System

Protocol aggregates liquidity from three DEXs, but USDC→WBTC route goes through single pool with $200k depth. Result—1.8% slippage on $50k trade. User trades at loss relative to market price, algorithm says nothing. Multi-hop solves this via route splitting: USDC→WETH via Uniswap v3, WETH→WBTC via Curve tricrypto. Total slippage—0.3%. Difference is substantial, but implementing correctly is not trivial.

Where Naive Multi-Hop Implementation Breaks

Path Encoding and Stack Overflow in Solidity

Uniswap v3 encodes route as bytes path—sequence of address fee address fee address. At three hops this is 20+3+20+3+20 = 66 bytes. Seems simple. Problem starts when developer tries building path dynamically in Solidity—abi.encodePacked in loop with uint24[] fees and address[] tokens. If input isn't validated, you can assemble path with mismatched lengths: 4 tokens, 2 fees. Contract compiles. On swap it reverts at UniswapV3Pool decode level without helpful error message.

Second vector—callback manipulation. In uniswapV3SwapCallback, contract must verify caller is legitimate pool, computed via PoolAddress.computeAddress. Without this check, anyone can call callback directly, passing arbitrary amount0Delta/amount1Delta, extracting tokens. One fork aggregator was drained this way in 2023—missing caller validation in callback.

Price Impact Calculation Across Multiple Pools

Computing price impact over multi-hop route is harder than single pool. Naive approach—call quoteExactInput at Quoter, get amountOut, compare with spot price. Works. But Quoter v2 requires simulation via eth_call, creating RPC load with frequent requests. More correct path—off-chain calculation via CPMM and CLMM math: for each pool compute sqrtPriceX96 after swap, then aggregate. Allows impact calculation without on-chain requests.

More subtlety: hop through Curve stable pool (3pool, Frax) has different math—StableSwap invariant instead of x*y=k. Can't mix calculations, result comes out wrong.

MEV and Sandwich Attacks on Multi-Hop Routes

Long route with multiple pools is tasty target for MEV-bots. Each pool is separate attack point. Classic sandwich: bot frontruns first hop, raises price, then backruns after transaction execution. Protection—hard amountOutMinimum on entire route (not per hop) and private mempool: Flashbots Protect, MEV Blocker, or direct send via eth_sendPrivateTransaction.

How We Build Multi-Hop System

Architecture: Off-Chain Routing + On-Chain Execution

Division of responsibilities is fundamental. Off-chain router computes optimal route—Python/TypeScript service building graph from Uniswap v2/v3, Curve, Balancer pools, running Dijkstra or Bellman-Ford for minimum-impact path. On-chain contract only executes: receives encoded path, validates, executes swaps via ISwapRouter/ICurvePool, returns amountOut.

Component Tools Task
Graph builder viem, The Graph, subgraph Current pool snapshot
Path optimizer TypeScript, custom Dijkstra Route search with min slippage
Quote engine UniswapV3 Quoter v2, Curve calc Precise amountOut estimate
Executor contract Solidity 0.8.x, Foundry On-chain execution
Slippage guard amountOutMinimum + deadline MEV protection

Executor Contract Implementation

Contract implements IUniversalRouter-like interface. Key function—executeMultiHop(bytes calldata path, uint256 amountIn, uint256 amountOutMin, address recipient). Inside: decode path, determine first pool type (Uniswap v3 by fee uint24 presence, or Curve by registry address), route to appropriate adapter.

Each adapter—separate contract registered in IAdapterRegistry. Allows adding new DEX support without rewriting executor. Pattern—strategy via ISwapAdapter interface with method swap(address tokenIn, address tokenOut, uint256 amountIn, bytes calldata data) returns (uint256 amountOut).

Cache pool addresses in mapping(bytes32 => address)—key is keccak256(abi.encodePacked(token0, token1, fee)). Avoids factory calls per hop.

Mainnet Fork Testing

Multi-hop can't be tested without real pool state. Use Foundry fork-tests:

vm.createSelectFork(vm.envString("ETH_RPC_URL"), blockNumber);

Pin specific block—reproducible tests. Run scenarios: USDC→WETH→WBTC via Uniswap v3, DAI→USDC→ETH→stETH via Curve+Uniswap mix. Verify amountOut matches Quoter prediction within ±0.01%.

Fuzz input amounts—amountIn from 1 to 10^9 token units. Find edge cases where path calculation gives amountOut = 0 from integer overflow/underflow at intermediate math.

Workflow

Analytics (2-3 days). Pool inventory: which DEXs, which chains, need cross-chain support? Determine if custom subgraph needed or public endpoints sufficient.

Design (3-5 days). Graph-router scheme, adapter interfaces, executor storage layout. At this stage decide upgradability question: if adding new DEXs planned, adapter registry should support registerAdapter with access control.

Development (1-2 weeks). Off-chain router + on-chain executor + adapter set for specific DEXs. Fork-tests on Ethereum and target L2s (Arbitrum, Optimism, Base).

Integration. wagmi/viem hooks for frontend: useMultiHopQuote, useMultiHopSwap. WebSocket price update subscription via The Graph.

Audit and Deployment. Slither + manual callback-function review. Deploy via Foundry script with Gnosis Safe multisig on owner functions.

Timeline Expectations

MVP supporting Uniswap v2/v3 on single chain—1-2 weeks. Full aggregator with Curve, Balancer, custom subgraph and 3-4 chain support—6-8 weeks. Timelines depend on supported DEX count and quote-engine precision requirements.

Cost calculated after technical requirements analysis.