Overview
In ShibaSwap v2, multihop swaps are powered by the Router contract, which automatically finds the optimal path for your trade. The router can route trades through multiple pools to find the best execution price and ensure your trade goes through even when direct liquidity is limited.Multihop swaps are particularly useful when trading between tokens that don’t have a direct pair, such as trading SHIB for a newly listed token through an intermediate token like WETH.
How Multihop Swaps Work
When you execute a multihop swap, the Router contract:- Analyzes available paths - Finds all possible routes between your input and output tokens
- Calculates optimal pricing - Determines which path offers the best exchange rate
- Executes the trade - Performs the swap through the optimal path in a single transaction
- Handles slippage - Ensures your trade executes within your specified slippage tolerance
Router Contract Integration
The ShibaSwap v2 Router contract handles all multihop swap logic. Here’s how to integrate it into your application:Basic Multihop Swap
contracts/MultihopSwap.sol
JavaScript Integration
scripts/multihop-swap.js
Path Optimization
The Router automatically finds the optimal path for your trade, but you can also specify custom paths for more control:Finding Optimal Paths
scripts/path-optimization.js
Advanced Multihop Features
Slippage Protection
contracts/SlippageProtection.sol
Gas Optimization
contracts/GasOptimizedSwap.sol
Error Handling
Common issues and solutions for multihop swaps:Insufficient Liquidity
Insufficient Liquidity
Problem: No direct path exists between tokens or insufficient liquidity in intermediate pools.Solution:
- Try different intermediate tokens (WETH, USDC, USDT)
- Reduce trade size
- Check pool liquidity before attempting swap
Slippage Too High
Slippage Too High
Problem: Price moved significantly during transaction execution.Solution:
- Increase slippage tolerance (but be careful with MEV attacks)
- Use shorter paths when possible
- Execute during lower volatility periods
Transaction Reverted
Transaction Reverted
Problem: Transaction fails due to various reasons.Solution:
- Check token approvals
- Verify sufficient token balance
- Ensure deadline hasn’t passed
- Check for blacklisted tokens
Best Practices
1
Always check liquidity
Use
getAmountsOut to verify sufficient liquidity exists before executing swaps.This prevents failed transactions and wasted gas.
2
Set appropriate slippage
Balance between protection and execution success.
3
Use optimal paths
Let the router find the best path, but verify with multiple options for large trades.
4
Handle errors gracefully
Implement proper error handling and user feedback in your application.
Provide clear error messages to help users understand and resolve issues.
Testing Multihop Swaps
Hardhat Test Example
test/multihop-swap.test.js