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:

  1. Graph-based pathfinding for multi-hop routes

  2. Dynamic programming for optimal split optimization

  3. Machine learning for gas price prediction and slippage estimation

  4. Real-time liquidity monitoring for route validation

  5. 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:

  1. Gas Price Prediction: Predicting optimal transaction timing

  2. Slippage Estimation: More accurate slippage predictions based on historical data

  3. Liquidity Prediction: Anticipating liquidity changes

  4. 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

  1. Minimize Price Impact: Prioritize routes with lower slippage

  2. Optimize Gas Efficiency: Consider gas costs relative to trade size

  3. Balance Speed vs Cost: Offer fast and economical route options

  4. Ensure Reliability: Factor in DEX and bridge uptime history

  5. Liquidity Awareness: Validate sufficient liquidity before execution

Error Handling

  1. Graceful Degradation: Fall back to simpler routes if complex ones fail

  2. Real-time Validation: Verify routes before execution

  3. Partial Execution: Support partial fills for large orders

  4. Rollback Capability: Ability to reverse failed multi-step routes

Performance Monitoring

  1. Route Success Rates: Track execution success by route type

  2. Slippage Accuracy: Monitor predicted vs actual slippage

  3. Gas Estimation: Validate gas estimates against actual usage

  4. Execution Time: Track route completion times

Resources

Last updated