Routing Algorithm
The IU2U Protocol employs a sophisticated multi-dimensional routing algorithm that optimizes for multiple factors including price, gas costs, slippage, and execution reliability across all supported DEXes and chains.
Algorithm Overview
The routing engine uses a hybrid approach combining:
Graph-based pathfinding for multi-hop routes
Dynamic programming for optimal split optimization
Machine learning for gas price prediction and slippage estimation
Real-time liquidity monitoring for route validation
Historical performance analysis for reliability scoring
Core Routing Components
1. Liquidity Graph Construction
The algorithm builds a dynamic liquidity graph where:
Nodes represent tokens on different chains
Edges represent available trading pairs with associated costs
Weights combine multiple factors (price impact, fees, gas costs)
class LiquidityGraph {
constructor() {
this.nodes = new Map(); // tokenAddress -> NodeData
this.edges = new Map(); // edgeId -> EdgeData
this.chainBridges = new Map(); // chainId -> bridges
this.lastUpdate = new Map();
}
buildGraph(supportedTokens, supportedDEXes, supportedChains) {
// Build nodes for each token on each chain
for (const chain of supportedChains) {
for (const token of supportedTokens) {
const nodeId = `${chain.id}:${token.address}`;
this.nodes.set(nodeId, {
chainId: chain.id,
tokenAddress: token.address,
tokenSymbol: token.symbol,
decimals: token.decimals,
isNative: token.isNative,
bridges: this.getAvailableBridges(token, chain.id)
});
}
}
// Build edges for each DEX pair
for (const chain of supportedChains) {
for (const dex of supportedDEXes.filter(d => d.chainId === chain.id)) {
this.addDEXEdges(dex, chain.id);
}
}
// Add cross-chain bridge edges
this.addBridgeEdges(supportedChains);
}
addDEXEdges(dex, chainId) {
const pairs = this.getDEXPairs(dex);
for (const pair of pairs) {
const edgeId = `${chainId}:${dex.name}:${pair.tokenA}:${pair.tokenB}`;
this.edges.set(edgeId, {
type: 'DEX_SWAP',
chainId: chainId,
dexName: dex.name,
dexType: dex.type,
tokenA: pair.tokenA,
tokenB: pair.tokenB,
fee: pair.fee,
liquidity: pair.liquidity,
lastUpdate: Date.now(),
gasEstimate: this.estimateDEXGas(dex.type),
reliability: dex.reliability || 0.99
});
// Add reverse edge
const reverseEdgeId = `${chainId}:${dex.name}:${pair.tokenB}:${pair.tokenA}`;
this.edges.set(reverseEdgeId, {
...this.edges.get(edgeId),
tokenA: pair.tokenB,
tokenB: pair.tokenA
});
}
}
addBridgeEdges(supportedChains) {
for (const fromChain of supportedChains) {
for (const toChain of supportedChains) {
if (fromChain.id === toChain.id) continue;
const bridges = this.getChainBridges(fromChain.id, toChain.id);
for (const bridge of bridges) {
for (const token of bridge.supportedTokens) {
const edgeId = `bridge:${fromChain.id}:${toChain.id}:${token}`;
this.edges.set(edgeId, {
type: 'BRIDGE',
fromChain: fromChain.id,
toChain: toChain.id,
token: token,
bridgeName: bridge.name,
fee: bridge.fee,
timeEstimate: bridge.timeEstimate,
gasEstimate: bridge.gasEstimate,
reliability: bridge.reliability,
minAmount: bridge.minAmount,
maxAmount: bridge.maxAmount
});
}
}
}
}
}
updateEdgeWeights(amountIn, priorityWeights = {}) {
const defaultWeights = {
priceImpact: 0.4,
gasCost: 0.3,
fee: 0.2,
reliability: 0.1
};
const weights = { ...defaultWeights, ...priorityWeights };
for (const [edgeId, edge] of this.edges) {
if (edge.type === 'DEX_SWAP') {
edge.weight = this.calculateDEXWeight(edge, amountIn, weights);
} else if (edge.type === 'BRIDGE') {
edge.weight = this.calculateBridgeWeight(edge, amountIn, weights);
}
}
}
calculateDEXWeight(edge, amountIn, weights) {
// Price impact component
const priceImpact = this.estimatePriceImpact(edge, amountIn);
const priceImpactScore = Math.min(priceImpact * 10, 1); // Normalize to 0-1
// Gas cost component (normalized by trade size)
const gasCostUSD = this.estimateGasCostUSD(edge.gasEstimate, edge.chainId);
const tradeSizeUSD = this.getTradeValueUSD(edge.tokenA, amountIn);
const gasCostRatio = gasCostUSD / Math.max(tradeSizeUSD, 1);
const gasCostScore = Math.min(gasCostRatio * 100, 1);
// Fee component
const feeScore = edge.fee;
// Reliability component (inverted - higher reliability = lower weight)
const reliabilityScore = 1 - edge.reliability;
return (
weights.priceImpact * priceImpactScore +
weights.gasCost * gasCostScore +
weights.fee * feeScore +
weights.reliability * reliabilityScore
);
}
calculateBridgeWeight(edge, amountIn, weights) {
// Bridge fee component
const bridgeFeeUSD = this.getBridgeFeeUSD(edge, amountIn);
const tradeSizeUSD = this.getTradeValueUSD(edge.token, amountIn);
const feeRatio = bridgeFeeUSD / Math.max(tradeSizeUSD, 1);
// Time penalty (longer bridges get higher weight)
const timePenalty = edge.timeEstimate / 3600; // Hours normalized
// Gas cost for bridge transactions
const gasCostUSD = this.estimateGasCostUSD(edge.gasEstimate, edge.fromChain);
const gasCostRatio = gasCostUSD / Math.max(tradeSizeUSD, 1);
// Reliability component
const reliabilityScore = 1 - edge.reliability;
return (
weights.fee * feeRatio +
weights.gasCost * gasCostRatio +
weights.reliability * reliabilityScore +
0.1 * timePenalty // Time has fixed 10% weight for bridges
);
}
}2. Multi-Dimensional Pathfinding
The core pathfinding algorithm uses a modified Dijkstra's algorithm with multiple optimization criteria:
3. Route Splitting and Optimization
For large trades, the algorithm can split orders across multiple DEXes to minimize price impact:
4. Real-time Route Validation
Before executing, routes are validated in real-time:
Performance Optimizations
1. Parallel Route Discovery
2. Intelligent Caching
Advanced Features
Machine Learning Integration
The routing algorithm incorporates ML models for:
Gas Price Prediction: Predicting optimal transaction timing
Slippage Estimation: More accurate slippage predictions based on historical data
Liquidity Prediction: Anticipating liquidity changes
Route Success Probability: Estimating the likelihood of successful execution
Dynamic Rebalancing
For routes that cross multiple chains or take significant time, the algorithm supports dynamic rebalancing:
Best Practices
Route Selection Criteria
Minimize Price Impact: Prioritize routes with lower slippage
Optimize Gas Efficiency: Consider gas costs relative to trade size
Balance Speed vs Cost: Offer fast and economical route options
Ensure Reliability: Factor in DEX and bridge uptime history
Liquidity Awareness: Validate sufficient liquidity before execution
Error Handling
Graceful Degradation: Fall back to simpler routes if complex ones fail
Real-time Validation: Verify routes before execution
Partial Execution: Support partial fills for large orders
Rollback Capability: Ability to reverse failed multi-step routes
Performance Monitoring
Route Success Rates: Track execution success by route type
Slippage Accuracy: Monitor predicted vs actual slippage
Gas Estimation: Validate gas estimates against actual usage
Execution Time: Track route completion times
Resources
Last updated

