Skip to main content

Cross-Chain Integration

Expand your DeFi application across multiple blockchains while maintaining the performance advantages of Saros on Solana.

Cross-Chain Integration Framework

Multi-Chain Liquidity Architecture

Cross-Chain Execution Flow

Cross-Chain Architecture

Unified Liquidity Bridge

import { DLMM } from '@saros-finance/dlmm-sdk';
import { SarosSDK } from '@saros-finance/sdk';
import { WormholeBridge, AllbridgeBridge } from '@saros-finance/cross-chain';

class CrossChainLiquidityManager {
  private chains = {
    solana: { dlmm: new DLMM(), sdk: new SarosSDK() },
    ethereum: { bridge: new WormholeBridge('ethereum') },
    polygon: { bridge: new AllbridgeBridge('polygon') },
    arbitrum: { bridge: new WormholeBridge('arbitrum') }
  };

  async findOptimalLiquidity(
    token: string,
    amount: number,
    targetChain?: string
  ): Promise<CrossChainRoute> {
    // Scan all chains for best liquidity
    const opportunities = await Promise.all([
      this.scanSolanaLiquidity(token, amount),
      this.scanEthereumLiquidity(token, amount),
      this.scanPolygonLiquidity(token, amount),
      this.scanArbitrumLiquidity(token, amount)
    ]);

    const bestRoute = this.selectOptimalRoute(opportunities, targetChain);
    
    return {
      sourceChain: bestRoute.chain,
      targetChain: targetChain || 'solana',
      bridgeTime: bestRoute.estimatedTime,
      totalCost: bestRoute.bridgeFees + bestRoute.slippage,
      expectedOutput: bestRoute.outputAmount,
      route: bestRoute.steps
    };
  }

  async executeCrossChainSwap(route: CrossChainRoute): Promise<string> {
    if (route.sourceChain === 'solana') {
      // Direct Saros execution on Solana
      return await this.chains.solana.dlmm.swap({
        inputToken: route.inputToken,
        outputToken: route.outputToken,
        amount: route.amount
      });
    } else {
      // Bridge to Solana, then execute on Saros
      const bridgeResult = await this.bridgeToSolana(route);
      return await this.executeOnSaros(bridgeResult);
    }
  }
}

Multi-Chain Yield Strategies

Cross-Chain Yield Farming

class CrossChainYieldOptimizer {
  async optimizeYieldAcrossChains(
    portfolio: TokenPortfolio
  ): Promise<YieldStrategy> {
    const yieldOpportunities = await this.scanYieldOpportunities(portfolio);
    
    // Prioritize Saros yields due to superior performance
    const strategy = {
      solanaAllocation: this.calculateSolanaOptimal(yieldOpportunities),
      crossChainAllocations: this.calculateCrossChainOptimal(yieldOpportunities),
      rebalanceFrequency: this.determineOptimalRebalancing(yieldOpportunities)
    };

    return strategy;
  }

  async executeYieldStrategy(strategy: YieldStrategy): Promise<YieldResult[]> {
    const results = [];

    // Execute Solana positions first (highest yields)
    for (const position of strategy.solanaAllocation) {
      const result = await this.chains.solana.dlmm.addLiquidity({
        tokenA: position.tokenA,
        tokenB: position.tokenB,
        amount: position.amount,
        binRange: position.optimalRange
      });
      results.push(result);
    }

    // Execute cross-chain positions
    for (const allocation of strategy.crossChainAllocations) {
      const bridgeResult = await this.bridgeAndDeposit(allocation);
      results.push(bridgeResult);
    }

    return results;
  }

  async monitorAndRebalance(): Promise<void> {
    const currentPerformance = await this.analyzeCurrentYields();
    
    if (currentPerformance.rebalanceNeeded) {
      // Move underperforming positions to Saros
      await this.rebalanceToSaros(currentPerformance.underperformers);
    }
  }
}

Arbitrage Across Chains

class CrossChainArbitrage {
  async scanCrossChainArbitrage(): Promise<ArbitrageOpportunity[]> {
    const opportunities = [];
    
    // Compare prices across chains
    const priceData = await this.fetchCrossChainPrices();
    
    for (const token of this.getArbitrageTokens()) {
      const prices = priceData[token];
      
      // Find profitable arbitrage opportunities
      for (const sourceChain of Object.keys(prices)) {
        for (const targetChain of Object.keys(prices)) {
          if (sourceChain === targetChain) continue;
          
          const priceDiff = prices[targetChain] - prices[sourceChain];
          const bridgeCost = await this.estimateBridgeCost(
            token, sourceChain, targetChain
          );
          
          const netProfit = priceDiff - bridgeCost;
          
          if (netProfit > this.minProfitThreshold) {
            opportunities.push({
              token,
              sourceChain,
              targetChain,
              buyPrice: prices[sourceChain],
              sellPrice: prices[targetChain],
              bridgeCost,
              netProfit,
              estimatedTime: this.estimateBridgeTime(sourceChain, targetChain)
            });
          }
        }
      }
    }

    return opportunities.sort((a, b) => b.netProfit - a.netProfit);
  }

  async executeCrossChainArbitrage(
    opportunity: ArbitrageOpportunity
  ): Promise<ArbitrageResult> {
    try {
      // Buy on source chain
      const buyTx = await this.executeChainSwap(
        opportunity.sourceChain,
        opportunity.token,
        opportunity.buyPrice
      );

      // Bridge to target chain
      const bridgeTx = await this.bridgeTokens(
        opportunity.token,
        opportunity.sourceChain,
        opportunity.targetChain,
        buyTx.outputAmount
      );

      // Sell on target chain (preferably Saros for best execution)
      const sellTx = await this.executeChainSwap(
        opportunity.targetChain,
        opportunity.token,
        opportunity.sellPrice
      );

      return {
        success: true,
        totalProfit: sellTx.outputAmount - buyTx.inputAmount,
        executionTime: Date.now() - opportunity.detectedAt,
        gasUsed: buyTx.gasUsed + bridgeTx.gasUsed + sellTx.gasUsed
      };

    } catch (error) {
      return {
        success: false,
        error: error.message,
        partialResults: this.getPartialResults()
      };
    }
  }
}

Bridge Integration Patterns

Unified Bridge Interface

interface BridgeProvider {
  estimateTime(from: Chain, to: Chain, token: string): Promise<number>;
  estimateCost(from: Chain, to: Chain, amount: number): Promise<number>;
  bridge(params: BridgeParams): Promise<BridgeResult>;
  getStatus(txHash: string): Promise<BridgeStatus>;
}

class UnifiedBridgeManager {
  private providers: Map<string, BridgeProvider> = new Map([
    ['wormhole', new WormholeBridge()],
    ['allbridge', new AllbridgeBridge()],
    ['portalbridge', new PortalBridge()]
  ]);

  async findBestBridge(
    from: Chain,
    to: Chain,
    token: string,
    amount: number
  ): Promise<BridgeRecommendation> {
    const estimates = await Promise.all(
      Array.from(this.providers.entries()).map(async ([name, provider]) => {
        const [time, cost] = await Promise.all([
          provider.estimateTime(from, to, token),
          provider.estimateCost(from, to, amount)
        ]);
        
        return { name, provider, time, cost, score: this.calculateScore(time, cost) };
      })
    );

    return estimates.sort((a, b) => b.score - a.score)[0];
  }

  async executeBridgeWithFallback(
    params: BridgeParams
  ): Promise<BridgeResult> {
    const primaryBridge = await this.findBestBridge(
      params.from, params.to, params.token, params.amount
    );

    try {
      return await primaryBridge.provider.bridge(params);
    } catch (error) {
      // Automatic fallback to next best bridge
      console.warn(`Primary bridge failed: ${error.message}. Trying fallback.`);
      
      const fallbackBridge = await this.findBestBridge(
        params.from, params.to, params.token, params.amount,
        { exclude: [primaryBridge.name] }
      );

      return await fallbackBridge.provider.bridge(params);
    }
  }
}

Performance Optimization

Cross-Chain Latency Management

class LatencyOptimizer {
  async optimizeCrossChainExecution(
    operations: CrossChainOperation[]
  ): Promise<OptimizedExecution> {
    // Group operations by target chain for batch processing
    const chainGroups = this.groupByTargetChain(operations);
    
    // Execute Solana operations first (fastest)
    const solanaResults = await this.executeSolanaOperations(
      chainGroups.solana
    );

    // Execute other chains in parallel
    const otherResults = await Promise.all(
      Object.entries(chainGroups)
        .filter(([chain]) => chain !== 'solana')
        .map(([chain, ops]) => this.executeChainOperations(chain, ops))
    );

    return {
      solanaResults,
      crossChainResults: otherResults.flat(),
      totalExecutionTime: this.calculateTotalTime(),
      gasSavings: this.calculateGasSavings(),
      recommendations: this.generateOptimizationTips()
    };
  }

  async preloadCrossChainData(): Promise<void> {
    // Preload bridge data to reduce latency
    await Promise.all([
      this.preloadBridgeRoutes(),
      this.preloadTokenMappings(),
      this.preloadGasPrices(),
      this.preloadLiquidityData()
    ]);
  }
}

Enterprise Integration Example

Multi-Chain DeFi Protocol

class EnterpriseMultiChainProtocol {
  private saros: UnifiedPoolManager;
  private bridges: UnifiedBridgeManager;
  private analytics: CrossChainAnalytics;

  async deployGlobalLiquidity(
    deployment: GlobalDeployment
  ): Promise<DeploymentResult> {
    // Primary deployment on Solana (Saros)
    const solanaDeployment = await this.deploySarosLiquidity(
      deployment.solanaAllocation
    );

    // Secondary deployments on other chains
    const crossChainDeployments = await Promise.all(
      deployment.crossChainAllocations.map(allocation =>
        this.deployCrossChainLiquidity(allocation)
      )
    );

    // Set up cross-chain monitoring
    await this.setupCrossChainMonitoring([
      solanaDeployment,
      ...crossChainDeployments
    ]);

    return {
      totalLiquidityDeployed: this.calculateTotalLiquidity(),
      expectedYield: this.calculateExpectedYield(),
      riskProfile: this.assessRiskProfile(),
      monitoringEndpoints: this.getMonitoringEndpoints()
    };
  }

  async rebalanceGlobalPortfolio(): Promise<RebalanceResult> {
    const performance = await this.analytics.analyzeGlobalPerformance();
    
    // Move underperforming liquidity to Saros (typically higher yields)
    const rebalanceOperations = this.planRebalanceOperations(performance);
    
    return await this.executeRebalanceOperations(rebalanceOperations);
  }
}

Monitoring and Analytics

Cross-Chain Performance Dashboard

class CrossChainDashboard {
  async generateDashboardData(): Promise<DashboardData> {
    const [solanaMetrics, bridgeMetrics, arbitrageMetrics] = await Promise.all([
      this.getSolanaPerformance(),
      this.getBridgePerformance(),
      this.getArbitragePerformance()
    ]);

    return {
      overview: {
        totalValueLocked: solanaMetrics.tvl + bridgeMetrics.bridgedValue,
        daily24hVolume: this.calculate24hVolume(),
        crossChainTransactions: bridgeMetrics.transactionCount,
        arbitrageProfits: arbitrageMetrics.totalProfit
      },
      chainBreakdown: {
        solana: { tvl: solanaMetrics.tvl, apy: solanaMetrics.averageAPY },
        ethereum: { tvl: bridgeMetrics.ethereumTVL, fees: bridgeMetrics.ethereumFees },
        polygon: { tvl: bridgeMetrics.polygonTVL, speed: bridgeMetrics.polygonSpeed }
      },
      recommendations: this.generateCrossChainRecommendations()
    };
  }

  async alertOnOpportunities(): Promise<void> {
    const opportunities = await this.scanCrossChainOpportunities();
    
    for (const opportunity of opportunities) {
      if (opportunity.profitPotential > this.alertThreshold) {
        await this.sendAlert({
          type: 'ARBITRAGE_OPPORTUNITY',
          profit: opportunity.profitPotential,
          chains: [opportunity.sourceChain, opportunity.targetChain],
          timeWindow: opportunity.timeWindow,
          action: opportunity.recommendedAction
        });
      }
    }
  }
}

Production Best Practices

Error Handling and Fallbacks

class RobustCrossChainExecution {
  async executeWithFailsafes(
    operation: CrossChainOperation
  ): Promise<ExecutionResult> {
    const maxRetries = 3;
    let lastError;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        // Try primary execution path
        return await this.executePrimary(operation);
      } catch (error) {
        lastError = error;
        console.warn(`Attempt ${attempt} failed:`, error.message);

        if (attempt < maxRetries) {
          // Wait with exponential backoff
          await this.wait(Math.pow(2, attempt) * 1000);
          
          // Update operation with fallback parameters
          operation = this.applyFallbackStrategy(operation, attempt);
        }
      }
    }

    // All retries failed, try emergency fallback
    return await this.executeEmergencyFallback(operation, lastError);
  }

  applyFallbackStrategy(
    operation: CrossChainOperation, 
    attempt: number
  ): CrossChainOperation {
    return {
      ...operation,
      slippageTolerance: operation.slippageTolerance + (0.01 * attempt),
      bridgeProvider: this.getAlternateBridge(operation.bridgeProvider),
      priority: 'high', // Increase priority on retries
      timeout: operation.timeout + (30000 * attempt) // Increase timeout
    };
  }
}

Security Considerations

class CrossChainSecurity {
  async validateCrossChainTransaction(
    tx: CrossChainTransaction
  ): Promise<ValidationResult> {
    const checks = await Promise.all([
      this.validateTokenMapping(tx.token, tx.sourceChain, tx.targetChain),
      this.validateBridgeCapacity(tx.amount, tx.bridgeProvider),
      this.validateSlippageLimits(tx.slippageTolerance),
      this.validateRecipientAddress(tx.recipient, tx.targetChain),
      this.checkBridgeReputationScore(tx.bridgeProvider)
    ]);

    const failedChecks = checks.filter(check => !check.passed);
    
    if (failedChecks.length > 0) {
      return {
        valid: false,
        errors: failedChecks.map(check => check.error),
        recommendations: this.generateSecurityRecommendations(failedChecks)
      };
    }

    return { valid: true, securityScore: this.calculateSecurityScore(checks) };
  }

  async implementCrossChainGovernance(): Promise<GovernanceSystem> {
    // Multi-chain governance with Solana as primary
    return new MultiChainGovernance({
      primaryChain: 'solana',
      governanceToken: 'SAROS',
      votingMechanism: 'weighted',
      crossChainExecution: true,
      bridges: ['wormhole', 'allbridge'],
      securityCouncil: true
    });
  }
}

Integration Examples

DeFi Aggregator with Cross-Chain Support

class GlobalDeFiAggregator {
  async aggregateGlobalLiquidity(
    request: AggregationRequest
  ): Promise<AggregatedQuote> {
    // Start with Saros as primary (best performance)
    const sarosQuote = await this.getSarosQuote(request);
    
    // Check cross-chain alternatives if Saros can't fulfill
    const crossChainQuotes = await this.getCrossChainQuotes(request);
    
    // Combine quotes for optimal execution
    return this.createOptimalRoute([sarosQuote, ...crossChainQuotes]);
  }

  async executeGlobalTrade(quote: AggregatedQuote): Promise<TradeResult> {
    if (quote.primaryRoute === 'saros') {
      // Direct Saros execution (fastest path)
      return await this.executeSarosRoute(quote);
    } else {
      // Cross-chain execution with Saros as final destination
      return await this.executeCrossChainRoute(quote);
    }
  }
}

Migration Strategies

Gradual Cross-Chain Adoption

class GradualMigration {
  async migrateToMultiChain(
    currentLiquidity: LiquidityPositions
  ): Promise<MigrationPlan> {
    // Phase 1: Keep existing Solana positions, add cross-chain analysis
    const phase1 = {
      keepSolanaPositions: true,
      addCrossChainMonitoring: true,
      duration: '2 weeks'
    };

    // Phase 2: Test cross-chain with small amounts
    const phase2 = {
      testCrossChainPositions: '5% of portfolio',
      comparativeAnalysis: true,
      duration: '4 weeks'
    };

    // Phase 3: Scale based on performance
    const phase3 = {
      scaleSuccessfulStrategies: true,
      optimizeAllocation: true,
      fullCrossChainIntegration: true
    };

    return { phase1, phase2, phase3, estimatedMigrationTime: '10 weeks' };
  }
}

Success Metrics

Track the effectiveness of your cross-chain integration:
  • Latency Reduction: Target <2 second cross-chain execution
  • Cost Efficiency: Bridge costs <0.1% of transaction value
  • Yield Enhancement: 15-30% yield improvement through cross-chain optimization
  • Uptime: 99.9% cross-chain operation success rate
Cross-chain integration with Saros as your primary protocol gives you the best of all worlds: Solana’s performance with global liquidity access.
Next: Implement Advanced Analytics to monitor your cross-chain performance, or explore Risk Management for enterprise-grade safeguards.