Multi-Hop Swaps: Routing Development and Exchange Optimization

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 1All 1305 services
Multi-Hop Swaps: Routing Development and Exchange Optimization
Complex
~1-2 weeks
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Multi-Hop Swaps: Routing Development and Exchange Optimization

A liquidity aggregator protocol gathers data from three DEXes, but the USDC→WBTC route goes through a single pool with $200k depth. Result: 1.8% slippage on a $50k trade. The user trades below market price, and the algorithm stays silent. We solved it with multi-hop: split the route USDC→WETH via Uniswap v3, WETH→WBTC via Curve tricrypto. Total slippage — 0.3%. Capital savings on trade execution — $750. The difference is substantial, but implementing it correctly is non-trivial and requires rigorous validation.

Why Multi-Hop Beats Direct Swap

A direct USDC→WBTC swap through a single pool gives 1.8% slippage on $50k. The same volume through two hops — 0.3%. A 6x difference in slippage reduction. Multi-hop is 6 times more efficient than direct swap for low-liquidity pairs. Multi-hop uses liquidity better: a fragmented entry doesn't shift the price as much. This is especially noticeable on tokens with small volume after an ICO. Execution price with multi-hop significantly improves due to better utilization of liquidity granularity.

How to Protect Against MEV in Multi-Hop

A long route is a tasty target for MEV bots. Each pool is a separate attack point. Classic sandwich: the bot front-runs the first hop, raises the price, then back-runs after the transaction executes. Our protection — a strict amountOutMinimum for the entire route (not per hop individually) and using private mempools: Flashbots Protect or MEV Blocker. In practice, this reduces sandwich losses by 95%.

Steps to Implement a Multi-Hop System

  1. Collect pool graph — via The Graph obtain current reserves and prices.
  2. Find optimal path — off-chain algorithm (Dijkstra) accounting for fees and depth.
  3. Encode the routebytes path with addresses and fee.
  4. On-chain execution — call a universal router with path validation.
  5. Check result — compare amountOut with expectation, fallback on mismatch.

Naive Implementation: What Breaks

Path Encoding and Stack Overflow

Uniswap v3 encodes the route as bytes path — a sequence address fee address fee address. For three hops: 20+3+20+3+20 = 66 bytes. Seems simple. The problem starts when a developer tries to build path dynamically in Solidity — abi.encodePacked in a loop with uint24[] fees and address[] tokens. If input is not validated, you can assemble a path with length mismatch: 4 tokens, 2 fees. The contract compiles. The swap reverts at the decoding level in UniswapV3Pool, without a clear error message.

Second vector — callback manipulation. In uniswapV3SwapCallback, the contract must verify that the caller is a legitimate pool, computed via PoolAddress.computeAddress. Without this check, anyone can call the callback directly, pass arbitrary amount0Delta / amount1Delta, and drain tokens from the contract. Exactly how one of the aggregator forks was drained recently — lack of caller validation in callback.

Price Impact Calculation Through Multiple Pools

Calculating price impact for a multi-hop route is harder than for a single pool. The naive approach: call quoteExactInput on Quoter, get amountOut, compare with spot price. Works. But Quoter v2 requires simulation via eth_call, and frequent queries create RPC load. The better path is off-chain calculation through CPMM and CLMM math: for each pool compute sqrtPriceX96 after swap, then aggregate. This allows impact calculation without on-chain calls.

Details of impact calculation for different pool types When hopping through a Curve stable pool (3pool, Frax), the math is different — StableSwap invariant instead of x*y=k. Mixing calculations yields incorrect estimates. We use separate formulas for each AMM type.

MEV and Sandwich Attacks on Multi-Hop Routes

Described above. In practice, we add protection via private mempools — this reduces losses by 95%.

How We Build a Multi-Hop System

Architecture: Off-Chain Routing + On-Chain Execution

Separation of concerns is critical. The off-chain router computes the optimal route — it's a Python/TypeScript service that builds a graph from Uniswap v2/v3, Curve, Balancer pools, and runs Dijkstra or Bellman-Ford to find the path with minimal impact. The on-chain contract only executes: receives an encoded path, validates it, executes swaps via ISwapRouter / ICurvePool, returns amountOut.

Component Tools Task
Graph builder viem, The Graph, subgraph Current pool snapshot
Path optimizer TypeScript, custom Dijkstra Find route 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

The contract implements an IUniversalRouter-like interface. The key function — executeMultiHop(bytes calldata path, uint256 amountIn, uint256 amountOutMin, address recipient). Internally: decode path, determine first pool type (Uniswap v3 via presence of fee uint24, or Curve via address registry), route to corresponding adapter.

Each adapter is a separate contract registered in IAdapterRegistry. This allows adding new DEX support without rewriting the executor. Strategy pattern via interface ISwapAdapter with method swap(address tokenIn, address tokenOut, uint256 amountIn, bytes calldata data) returns (uint256 amountOut).

For gas optimization, we cache pool addresses in mapping(bytes32 => address) — key is keccak256(abi.encodePacked(token0, token1, fee)). Avoids factory calls on each hop.

Testing on Mainnet Fork

Multi-hop cannot be tested without real pool state. We use Foundry fork tests:

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

Fix a specific block — test reproducibility. Run scenarios: USDC→WETH→WBTC via Uniswap v3, DAI→USDC→ETH→stETH via Curve+Uniswap mix. Verify that amountOut matches Quoter prediction within ±0.01%.

Fuzzing on input amounts — amountIn from 1 to 10^9 token units. Find edge cases where path calculation gives amountOut = 0 due to integer overflow/underflow in intermediate computations.

What's Included in the Work

  • Documentation: router specification, adapter descriptions, deployment guide.
  • Source code: full repository with executor contract, adapters, off-chain router, and tests.
  • Access: multisig wallets for owner functions, RPC endpoints.
  • Training: session for your team on system operation.
  • Support: 3 months of warranty support after deployment.

Work Process

  1. Analytics (2-3 days). Pool inventory: which DEXes, which chains, cross-chain support required. Decide on building a custom subgraph or using public endpoints.
  2. Design (3-5 days). Graph router schema, adapter interfaces, executor contract storage layout. At this stage, solve upgradability: if adding new DEXes is planned, adapter registry must support registerAdapter with access control.
  3. Development (1-2 weeks). Off-chain router + on-chain executor + adapter set for specific DEXes. Fork tests on Ethereum and target L2s (Arbitrum, Optimism, Base).
  4. Integration. wagmi/viem hooks for frontend: useMultiHopQuote, useMultiHopSwap. WebSocket subscription for price updates via The Graph.
  5. Audit and deployment. Slither + manual review of callback functions. Deploy via Foundry script with Gnosis Safe multisig for owner functions.

Timeline and Cost Estimates

MVP with Uniswap v2/v3 support on one chain — 1-2 weeks at a cost starting from $15,000. Full aggregator with Curve, Balancer, custom subgraph, and 3-4 chain support — 6-8 weeks, costing $40,000–$70,000. Timelines depend on number of supported DEXes and quote engine accuracy requirements. Our experience — 7+ years in DeFi, 60+ delivered projects — guarantees quality. Our team of 15 senior Solidity developers has completed projects for 20+ protocols. Uniswap V2 docs confirm the architecture.

Contact us for integration consultation — we'll select the optimal architecture for your project. Order multi-hop system development now.

Use Case Comparison

Scenario Direct Swap Multi-Hop (Our Approach)
USDC→WBTC ($50k) Slippage 1.8% Slippage 0.3%
ETH→RAI ($20k) Slippage 2.5% Slippage 0.5%
DAI→USDC→ETH→stETH Not available 0.8%

Routing through multiple pools reduces slippage by 3-6x compared to a direct swap.

DeFi Protocol Development

We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.

We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.

Why are oracles a critical component of DeFi?

Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.

Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.

TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.

Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.

Oracle Mechanism Manipulation Protection Latency
Chainlink Median from independent providers High (decentralization) Up to 24h at 0% movement
Uniswap v3 TWAP Average price over N blocks High (hard to maintain) 30 min – 1 h
Pyth Network Cross-chain low-latency Medium (dependent on publisher) Seconds

In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.

How to protect a DeFi protocol from flash loan attacks?

Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.

Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.

Key Components of DeFi Architecture

Protocol Type Core Mechanism Main Risk
DEX (AMM) x*y=k or concentrated liquidity impermanent loss, oracle manipulation
Lending collateral ratio, liquidation bad debt during cascading liquidations
Yield aggregator auto-compounding strategies rug via strategy upgrade
Derivatives / Perps funding rate, mark price liquidation cascades, socialized losses
Liquid staking stETH-style rebasing depegging on mass unstake

AMM: From x*y=k to Concentrated Liquidity

Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.

Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.

Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.

Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.

Lending Protocols: Collateral, Liquidation, Bad Debt

LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.

Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.

If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.

Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.

Yield Farming and Incentive Mechanics

Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.

Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.

What Our DeFi Protocol Development Includes

  • Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
  • Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
  • Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
  • Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
  • Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
  • Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
  • Post-launch support: updates, patches, upgrades via proxy.

Our Expertise and Experience

We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.

DeFi basic principles that we apply in practice.

Timelines

  • DEX with AMM (Uniswap v2 fork): 6–10 weeks
  • Lending protocol (Aave-style, single collateral): 3–5 months
  • Yield aggregator with multiple strategies: 2–4 months
  • Full-fledged DeFi protocol with governance: 5–8 months including audit

Cost is calculated individually—contact us for a project estimate.

Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.