Cross-Chain Swap
This example demonstrates how to perform cross-chain token swaps using IU2U Protocol, including token transfers between different blockchain networks.
Overview
Cross-chain swaps enable users to exchange tokens across different blockchain networks in a single transaction. IU2U Protocol facilitates this through Axelar's cross-chain infrastructure.
Basic Cross-Chain Swap
Frontend Implementation
// examples/cross-chain-swap/frontend.js
import { ethers } from 'ethers';
import { IU2UGateway, CrossChainAggregator } from '@iu2u/sdk';
class CrossChainSwapExample {
constructor(providerUrl, privateKey) {
this.provider = new ethers.providers.JsonRpcProvider(providerUrl);
this.signer = new ethers.Wallet(privateKey, this.provider);
// Initialize IU2U components
this.gateway = new IU2UGateway({
provider: this.provider,
signer: this.signer
});
this.aggregator = new CrossChainAggregator({
provider: this.provider,
signer: this.signer
});
}
/**
* Execute a cross-chain swap from Ethereum to Polygon
* Example: Swap USDC on Ethereum to USDT on Polygon
*/
async executeCrossChainSwap() {
const swapParams = {
// Source chain swap (Ethereum)
sourceChain: 'ethereum',
sourceToken: '0xA0b86a33E6441e1a02c4e4670dd96EA0f25A632', // USDC on Ethereum
sourceAmount: ethers.utils.parseUnits('1000', 6), // 1000 USDC
// Destination chain swap (Polygon)
destinationChain: 'polygon',
destinationToken: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F', // USDT on Polygon
destinationReceiver: this.signer.address,
minDestinationAmount: ethers.utils.parseUnits('950', 6), // 950 USDT (5% slippage)
// Swap configuration
routerType: 0, // Uniswap V2
deadline: Math.floor(Date.now() / 1000) + 1800, // 30 minutes
gasPayment: ethers.utils.parseEther('0.01') // Gas for destination chain
};
try {
console.log('Initiating cross-chain swap...');
// Step 1: Approve source token
await this.approveToken(swapParams.sourceToken, swapParams.sourceAmount);
// Step 2: Execute cross-chain swap
const tx = await this.aggregator.crossChainSwap(swapParams);
console.log('Transaction submitted:', tx.hash);
// Step 3: Wait for confirmation
const receipt = await tx.wait();
console.log('Source chain transaction confirmed:', receipt.transactionHash);
// Step 4: Monitor destination chain completion
const destinationTx = await this.monitorDestinationChain(
swapParams.destinationChain,
receipt.transactionHash
);
console.log('Cross-chain swap completed!');
return {
sourceTransaction: receipt.transactionHash,
destinationTransaction: destinationTx
};
} catch (error) {
console.error('Cross-chain swap failed:', error);
throw error;
}
}
async approveToken(tokenAddress, amount) {
const tokenContract = new ethers.Contract(
tokenAddress,
['function approve(address spender, uint256 amount) returns (bool)'],
this.signer
);
const approveTx = await tokenContract.approve(this.aggregator.address, amount);
await approveTx.wait();
console.log('Token approval confirmed');
}
async monitorDestinationChain(destinationChain, sourceTxHash) {
// Monitor Axelar for cross-chain message execution
const axelarApi = `https://api.axelar.dev/cross-chain/tx/${sourceTxHash}`;
for (let i = 0; i < 60; i++) { // Poll for 10 minutes
try {
const response = await fetch(axelarApi);
const data = await response.json();
if (data.status === 'executed') {
return data.destinationTransactionHash;
}
console.log(`Waiting for destination chain execution... (${i + 1}/60)`);
await new Promise(resolve => setTimeout(resolve, 10000)); // Wait 10 seconds
} catch (error) {
console.error('Error monitoring destination chain:', error);
}
}
throw new Error('Destination chain execution timeout');
}
/**
* Get quote for cross-chain swap
*/
async getCrossChainQuote(params) {
try {
const quote = await this.aggregator.getCrossChainQuote({
sourceChain: params.sourceChain,
sourceToken: params.sourceToken,
sourceAmount: params.sourceAmount,
destinationChain: params.destinationChain,
destinationToken: params.destinationToken,
routerType: params.routerType || 0
});
return {
estimatedOutput: quote.estimatedOutput,
bridgeFee: quote.bridgeFee,
gasFee: quote.gasFee,
totalFee: quote.totalFee,
estimatedTime: quote.estimatedTime,
priceImpact: quote.priceImpact
};
} catch (error) {
console.error('Failed to get cross-chain quote:', error);
throw error;
}
}
}
// Usage example
async function main() {
const swapper = new CrossChainSwapExample(
process.env.ETHEREUM_RPC_URL,
process.env.PRIVATE_KEY
);
// Get quote first
const quote = await swapper.getCrossChainQuote({
sourceChain: 'ethereum',
sourceToken: '0xA0b86a33E6441e1a02c4e4670dd96EA0f25A632',
sourceAmount: ethers.utils.parseUnits('1000', 6),
destinationChain: 'polygon',
destinationToken: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F'
});
console.log('Cross-chain swap quote:', quote);
// Execute if quote is acceptable
if (parseFloat(ethers.utils.formatUnits(quote.estimatedOutput, 6)) >= 950) {
const result = await swapper.executeCrossChainSwap();
console.log('Swap result:', result);
}
}
// Run example
main().catch(console.error);Smart Contract Implementation
React Component
Custom Hook
Advanced Features
Multi-Hop Cross-Chain Swaps
Gas Optimization Strategies
Testing
Resources
Last updated

