⛓️ Cross-Chain Operations Example
Advanced cross-chain operations using BRDZ SDK including multi-blockchain transfers, DeFi strategies, arbitrage opportunities, and AI-powered cross-chain management.
Prerequisites
- API Key configured
- Authentication setup
- AI Wallet Management understanding
- User authenticated with wallets on multiple chains
Overview
BRDZ SDK provides comprehensive cross-chain capabilities:
- CrossChain Module: Direct chain-to-chain USDC transfers
- Bridge Module: Virtual account and wallet bridging
- AI Integration: Natural language cross-chain operations
- DeFi Operations: Cross-chain yield farming and arbitrage
Supported Chains
const SUPPORTED_CHAINS = {
sepolia: {
name: 'Ethereum Sepolia Testnet',
native_symbol: 'ETH',
usdc_contract: '0x...',
explorer: 'https://sepolia.etherscan.io'
},
amoy: {
name: 'Polygon Amoy Testnet',
native_symbol: 'POL',
usdc_contract: '0x...',
explorer: 'https://amoy.polygonscan.com'
},
neon: {
name: 'Neon EVM DevNet',
native_symbol: 'NEON',
usdc_contract: '0x...',
explorer: 'https://neon-devnet.blockscout.com'
}
};
Basic Cross-Chain Operations
CrossChain USDC Transfers
import brdzSDK from 'anantla_sdk';
class CrossChainManager {
constructor(userId) {
this.userId = userId;
this.crosschain = brdzSDK.crosschain;
this.cryptoWallet = brdzSDK.cryptoWallet;
}
// Check USDC balances across all chains
async getAllChainBalances() {
const chains = ['sepolia', 'amoy', 'neon'];
const balances = {};
try {
// Get user wallets
const wallets = await this.cryptoWallet.getUserWallets(this.userId);
for (const chain of chains) {
balances[chain] = { balance: '0', address: null };
// Find wallet address for this chain
for (const wallet of wallets) {
const addresses = await this.cryptoWallet.getWalletAddresses(wallet.bw_id);
const chainAddress = addresses.find(addr => addr.chain_id === chain);
if (chainAddress) {
const balanceData = await this.crosschain.getUSDCBalance(chain, chainAddress.address);
balances[chain] = {
balance: balanceData.balance,
address: chainAddress.address,
wallet_name: wallet.wallet_name,
value_usd: balanceData.value_usd
};
break;
}
}
}
return balances;
} catch (error) {
throw new Error(`Failed to get chain balances: ${error.message}`);
}
}
// Initiate cross-chain USDC transfer
async initiateCrossChainTransfer(fromChain, toChain, amount, recipientAddress, returnAddress) {
try {
console.log(`🌉 Initiating transfer: ${amount} USDC from ${fromChain} to ${toChain}`);
// Check balance before transfer
const balance = await this.crosschain.getUSDCBalance(fromChain, returnAddress);
if (parseFloat(balance.balance) < parseFloat(amount)) {
throw new Error(`Insufficient balance. Available: ${balance.balance} USDC, Required: ${amount} USDC`);
}
// Initiate transfer
const result = await this.crosschain.initiateTransfer({
user_id: this.userId,
amount: amount,
from_chain: fromChain,
to_chain: toChain,
token: 'USDC',
recipient_address: recipientAddress,
return_address: returnAddress
});
return {
log_id: result.log_id,
nonce: result.nonce,
burn_required: true,
from_chain: fromChain,
to_chain: toChain,
amount: amount,
status: 'initiated'
};
} catch (error) {
throw new Error(`Transfer initiation failed: ${error.message}`);
}
}
// Execute burn transaction (frontend-based)
async executeBurnTransaction(logId, nonce, privateKey) {
try {
console.log('🔥 Executing burn transaction...');
const result = await this.crosschain.burnTokenFrontend({
log_id: logId,
nonce: nonce,
private_key: privateKey
});
return {
burn_tx_hash: result.transaction_hash,
burn_status: result.status,
mint_ready: result.mint_ready
};
} catch (error) {
throw new Error(`Burn transaction failed: ${error.message}`);
}
}
// Complete transfer by minting on destination chain
async completeCrossChainTransfer(nonce) {
try {
console.log('✨ Minting tokens on destination chain...');
const result = await this.crosschain.mintToken(nonce);
return {
mint_tx_hash: result.transaction_hash,
destination_chain: result.chain,
amount: result.amount,
recipient: result.recipient,
status: 'completed'
};
} catch (error) {
throw new Error(`Mint transaction failed: ${error.message}`);
}
}
// Get cross-chain transaction history
async getCrossChainHistory(limit = 20) {
try {
const history = await this.crosschain.getCTransactionHistory(this.userId, {
limit: limit,
offset: 0
});
return history.data.map(tx => ({
log_id: tx.log_id,
from_chain: tx.from_chain,
to_chain: tx.to_chain,
amount: tx.amount,
status: tx.status,
burn_tx_hash: tx.burn_tx_hash,
mint_tx_hash: tx.mint_tx_hash,
created_at: tx.created_at,
completed_at: tx.completed_at,
duration: tx.completed_at ?
Math.round((new Date(tx.completed_at) - new Date(tx.created_at)) / 1000 / 60) : null
}));
} catch (error) {
throw new Error(`Failed to get history: ${error.message}`);
}
}
// Get transaction details
async getTransactionDetails(logId) {
try {
const details = await this.crosschain.getCTransactionDetails(logId);
return {
log_id: details.log_id,
from_chain: details.from_chain,
to_chain: details.to_chain,
amount: details.amount,
token: details.token,
sender_address: details.sender_address,
recipient_address: details.recipient_address,
burn_tx_hash: details.burn_tx_hash,
mint_tx_hash: details.mint_tx_hash,
status: details.status,
gas_fees: details.gas_fees,
created_at: details.created_at,
updated_at: details.updated_at,
error_message: details.error_message
};
} catch (error) {
throw new Error(`Failed to get transaction details: ${error.message}`);
}
}
}
// Usage Examples
const crossChainManager = new CrossChainManager(123);
// Check balances across all chains
const balances = await crossChainManager.getAllChainBalances();
console.log('Chain Balances:', balances);
// Execute cross-chain transfer
const transfer = await crossChainManager.initiateCrossChainTransfer(
'sepolia',
'amoy',
'10.5',
'0x742d35Cc6635C0532925a3b8D400d93458f8DA83', // recipient on Amoy
'0x8ba1f109551bD432803012645Hac136c5C63c2C7' // return address on Sepolia
);
console.log('Transfer initiated:', transfer);
Advanced Cross-Chain Strategies
class AdvancedCrossChainStrategies extends CrossChainManager {
constructor(userId) {
super(userId);
this.fx = brdzSDK.fx;
}
// Cross-chain arbitrage detector
async detectArbitrageOpportunities() {
try {
const balances = await this.getAllChainBalances();
const opportunities = [];
// Get exchange rates for each chain (simulated - in real world you'd query DEXs)
const rates = {
sepolia: { usd_rate: 1.00, liquidity: 'high' },
amoy: { usd_rate: 0.998, liquidity: 'medium' },
neon: { usd_rate: 1.005, liquidity: 'low' }
};
const chains = Object.keys(rates);
for (let i = 0; i < chains.length; i++) {
for (let j = 0; j < chains.length; j++) {
if (i !== j) {
const fromChain = chains[i];
const toChain = chains[j];
const priceDiff = rates[toChain].usd_rate - rates[fromChain].usd_rate;
const profitPercentage = (priceDiff / rates[fromChain].usd_rate) * 100;
if (profitPercentage > 0.1) { // Minimum 0.1% profit
const maxAmount = Math.min(
parseFloat(balances[fromChain]?.balance || '0'),
1000 // Max arbitrage amount
);
if (maxAmount > 10) { // Minimum viable amount
opportunities.push({
from_chain: fromChain,
to_chain: toChain,
profit_percentage: profitPercentage.toFixed(3),
max_amount: maxAmount.toFixed(2),
estimated_profit: (maxAmount * profitPercentage / 100).toFixed(2),
liquidity_risk: rates[toChain].liquidity,
recommended: profitPercentage > 0.5 && rates[toChain].liquidity !== 'low'
});
}
}
}
}
}
return opportunities.sort((a, b) => parseFloat(b.profit_percentage) - parseFloat(a.profit_percentage));
} catch (error) {
throw new Error(`Arbitrage detection failed: ${error.message}`);
}
}
// Execute arbitrage strategy
async executeArbitrageStrategy(opportunity, amount) {
try {
console.log(`💹 Executing arbitrage: ${opportunity.from_chain} → ${opportunity.to_chain}`);
// Get wallet addresses
const balances = await this.getAllChainBalances();
const fromAddress = balances[opportunity.from_chain].address;
const toAddress = balances[opportunity.to_chain].address;
if (!fromAddress || !toAddress) {
throw new Error('Wallet addresses not found for arbitrage chains');
}
// Step 1: Initiate cross-chain transfer
const transfer = await this.initiateCrossChainTransfer(
opportunity.from_chain,
opportunity.to_chain,
amount,
toAddress,
fromAddress
);
// Step 2: Execute burn (in real implementation, you'd handle this with user's private key)
console.log('⚠️ Burn transaction required - implement with user private key');
return {
strategy: 'arbitrage',
opportunity: opportunity,
transfer: transfer,
status: 'burn_required',
estimated_profit: (parseFloat(amount) * parseFloat(opportunity.profit_percentage) / 100).toFixed(2)
};
} catch (error) {
throw new Error(`Arbitrage execution failed: ${error.message}`);
}
}
// Cross-chain portfolio rebalancing
async rebalancePortfolio(targetDistribution) {
try {
console.log('⚖️ Rebalancing cross-chain portfolio...');
const balances = await this.getAllChainBalances();
const totalBalance = Object.values(balances).reduce(
(sum, chain) => sum + parseFloat(chain.balance || '0'), 0
);
if (totalBalance === 0) {
throw new Error('No USDC balance found across chains');
}
const rebalanceActions = [];
// Calculate target amounts
const targetAmounts = {};
Object.keys(targetDistribution).forEach(chain => {
targetAmounts[chain] = totalBalance * (targetDistribution[chain] / 100);
});
// Determine required transfers
Object.keys(targetAmounts).forEach(toChain => {
const currentAmount = parseFloat(balances[toChain]?.balance || '0');
const targetAmount = targetAmounts[toChain];
const difference = targetAmount - currentAmount;
if (Math.abs(difference) > 1) { // Only rebalance if difference > 1 USDC
if (difference > 0) {
// Need to transfer TO this chain
// Find chain with excess balance
const fromChain = Object.keys(balances).find(chain => {
const excess = parseFloat(balances[chain]?.balance || '0') - targetAmounts[chain];
return excess >= difference;
});
if (fromChain) {
rebalanceActions.push({
action: 'transfer',
from_chain: fromChain,
to_chain: toChain,
amount: difference.toFixed(2),
reason: `Rebalance to ${targetDistribution[toChain]}% target`
});
}
}
}
});
return {
current_distribution: this.calculateDistribution(balances, totalBalance),
target_distribution: targetDistribution,
total_balance: totalBalance.toFixed(2),
rebalance_actions: rebalanceActions,
estimated_gas_cost: rebalanceActions.length * 0.05 // Estimated gas per transfer
};
} catch (error) {
throw new Error(`Portfolio rebalancing failed: ${error.message}`);
}
}
calculateDistribution(balances, totalBalance) {
const distribution = {};
Object.keys(balances).forEach(chain => {
const amount = parseFloat(balances[chain]?.balance || '0');
distribution[chain] = ((amount / totalBalance) * 100).toFixed(1);
});
return distribution;
}
// Cross-chain yield farming strategy
async analyzeYieldOpportunities() {
try {
// Simulated yield opportunities (in real implementation, query DeFi protocols)
const yieldOpportunities = [
{
chain: 'sepolia',
protocol: 'Aave',
apy: '4.5%',
tvl: '$120M',
risk_level: 'low',
minimum_deposit: '100',
lock_period: 0
},
{
chain: 'amoy',
protocol: 'Compound',
apy: '6.2%',
tvl: '$80M',
risk_level: 'medium',
minimum_deposit: '50',
lock_period: 0
},
{
chain: 'neon',
protocol: 'Venus',
apy: '8.1%',
tvl: '$25M',
risk_level: 'high',
minimum_deposit: '25',
lock_period: 30
}
];
const balances = await this.getAllChainBalances();
// Calculate optimal allocation
const recommendations = yieldOpportunities.map(opp => {
const availableBalance = parseFloat(balances[opp.chain]?.balance || '0');
const canInvest = availableBalance >= parseFloat(opp.minimum_deposit);
const maxInvestment = Math.min(availableBalance * 0.8, 1000); // Max 80% of balance or 1000 USDC
return {
...opp,
available_balance: availableBalance.toFixed(2),
can_invest: canInvest,
max_investment: maxInvestment.toFixed(2),
estimated_yearly_return: (maxInvestment * parseFloat(opp.apy) / 100).toFixed(2),
recommendation_score: this.calculateYieldScore(opp, availableBalance)
};
}).sort((a, b) => b.recommendation_score - a.recommendation_score);
return {
opportunities: recommendations,
total_potential_yield: recommendations.reduce((sum, opp) =>
sum + parseFloat(opp.estimated_yearly_return || '0'), 0
).toFixed(2)
};
} catch (error) {
throw new Error(`Yield analysis failed: ${error.message}`);
}
}
calculateYieldScore(opportunity, availableBalance) {
const apyScore = parseFloat(opportunity.apy) * 10; // Weight APY highly
const riskPenalty = opportunity.risk_level === 'high' ? -20 :
opportunity.risk_level === 'medium' ? -10 : 0;
const liquidityBonus = opportunity.lock_period === 0 ? 10 : -5;
const balanceScore = availableBalance >= parseFloat(opportunity.minimum_deposit) ? 15 : -50;
return apyScore + riskPenalty + liquidityBonus + balanceScore;
}
}
AI-Powered Cross-Chain Operations
Natural Language Cross-Chain Management
class AICrossChainManager extends AdvancedCrossChainStrategies {
constructor(userId) {
super(userId);
}
// Process natural language cross-chain requests
async processAICrossChainRequest(userInput, context = {}) {
try {
console.log('🤖 Processing cross-chain AI request:', userInput);
const result = await this.cryptoWallet.processAIIntent({
user_input: userInput,
user_id: this.userId,
context: {
...context,
specialty: 'cross_chain_operations',
available_chains: ['sepolia', 'amoy', 'neon']
}
});
return this.parseAICrossChainResponse(result);
} catch (error) {
throw new Error(`AI cross-chain request failed: ${error.message}`);
}
}
parseAICrossChainResponse(result) {
const response = this.cryptoWallet.utils.ai.parseResponse(result);
if (!response) {
return { success: false, error: 'Invalid AI response' };
}
return {
success: true,
message: response.message,
intent_type: response.intent_type,
requires_execution: response.execution_result?.requires_user_confirmation,
cross_chain_action: response.execution_result?.cross_chain_action,
parameters: response.execution_result?.parameters,
estimated_cost: response.execution_result?.estimated_cost,
warnings: response.execution_result?.warnings
};
}
// AI-powered cross-chain examples
async aiCrossChainExamples() {
const examples = [
{
prompt: "Move 50 USDC from Sepolia to Polygon Amoy",
expected_action: "cross_chain_transfer"
},
{
prompt: "Show me balances across all chains and find best arbitrage opportunities",
expected_action: "arbitrage_analysis"
},
{
prompt: "Rebalance my portfolio to 40% Sepolia, 35% Amoy, 25% Neon",
expected_action: "portfolio_rebalance"
},
{
prompt: "Find the highest yield farming opportunities across all chains",
expected_action: "yield_analysis"
},
{
prompt: "Help me optimize gas fees for cross-chain transfers",
expected_action: "gas_optimization"
}
];
console.log('🤖 AI Cross-Chain Command Examples:');
examples.forEach((example, index) => {
console.log(`${index + 1}. "${example.prompt}"`);
console.log(` Expected: ${example.expected_action}`);
});
return examples;
}
// Execute AI-guided cross-chain strategy
async executeAIStrategy(userInput) {
try {
// Step 1: Process AI request
const aiResponse = await this.processAICrossChainRequest(userInput);
if (!aiResponse.success) {
throw new Error(aiResponse.error);
}
console.log('🤖 AI Response:', aiResponse.message);
// Step 2: Execute based on intent
let executionResult;
switch (aiResponse.intent_type) {
case 'cross_chain_transfer':
executionResult = await this.executeAITransfer(aiResponse.parameters);
break;
case 'arbitrage_analysis':
executionResult = await this.detectArbitrageOpportunities();
break;
case 'portfolio_rebalance':
executionResult = await this.rebalancePortfolio(aiResponse.parameters.target_distribution);
break;
case 'yield_analysis':
executionResult = await this.analyzeYieldOpportunities();
break;
case 'balance_check':
executionResult = await this.getAllChainBalances();
break;
default:
executionResult = { message: 'AI request processed but no execution needed' };
}
return {
ai_response: aiResponse,
execution_result: executionResult,
success: true
};
} catch (error) {
throw new Error(`AI strategy execution failed: ${error.message}`);
}
}
async executeAITransfer(parameters) {
if (!parameters.from_chain || !parameters.to_chain || !parameters.amount) {
throw new Error('Missing required transfer parameters');
}
// Get user wallet addresses
const balances = await this.getAllChainBalances();
const fromAddress = balances[parameters.from_chain]?.address;
const toAddress = balances[parameters.to_chain]?.address;
if (!fromAddress || !toAddress) {
throw new Error('Wallet addresses not found for specified chains');
}
return await this.initiateCrossChainTransfer(
parameters.from_chain,
parameters.to_chain,
parameters.amount,
toAddress,
fromAddress
);
}
}
React Cross-Chain Components
Cross-Chain Dashboard
import React, { useState, useEffect } from 'react';
import { useSDK } from '../contexts/SDKContext';
interface ChainBalance {
balance: string;
address: string;
wallet_name: string;
value_usd: number;
}
interface CrossChainTransfer {
log_id: string;
from_chain: string;
to_chain: string;
amount: string;
status: string;
burn_tx_hash?: string;
mint_tx_hash?: string;
created_at: string;
duration?: number;
}
const CrossChainDashboard: React.FC = () => {
const { currentUser } = useSDK();
const [balances, setBalances] = useState<Record<string, ChainBalance>>({});
const [transfers, setTransfers] = useState<CrossChainTransfer[]>([]);
const [loading, setLoading] = useState(false);
const [selectedTransfer, setSelectedTransfer] = useState<CrossChainTransfer | null>(null);
// Transfer form state
const [transferForm, setTransferForm] = useState({
fromChain: 'sepolia',
toChain: 'amoy',
amount: '',
recipientAddress: ''
});
useEffect(() => {
loadDashboardData();
}, []);
const loadDashboardData = async () => {
setLoading(true);
try {
// Load balances and transfer history
await Promise.all([
loadChainBalances(),
loadTransferHistory()
]);
} catch (error) {
console.error('Failed to load dashboard data:', error);
} finally {
setLoading(false);
}
};
const loadChainBalances = async () => {
try {
const brdzSDK = await import('anantla_sdk').then(sdk => sdk.default);
const crosschain = brdzSDK.crosschain;
const cryptoWallet = brdzSDK.cryptoWallet;
const chains = ['sepolia', 'amoy', 'neon'];
const chainBalances: Record<string, ChainBalance> = {};
// Get user wallets
const wallets = await cryptoWallet.getUserWallets(currentUser!.id);
for (const chain of chains) {
chainBalances[chain] = {
balance: '0',
address: '',
wallet_name: '',
value_usd: 0
};
// Find wallet address for this chain
for (const wallet of wallets) {
const addresses = await cryptoWallet.getWalletAddresses(wallet.bw_id);
const chainAddress = addresses.find(addr => addr.chain_id === chain);
if (chainAddress) {
const balanceData = await crosschain.getUSDCBalance(chain, chainAddress.address);
chainBalances[chain] = {
balance: balanceData.balance || '0',
address: chainAddress.address,
wallet_name: wallet.wallet_name,
value_usd: parseFloat(balanceData.balance || '0')
};
break;
}
}
}
setBalances(chainBalances);
} catch (error) {
console.error('Failed to load chain balances:', error);
}
};
const loadTransferHistory = async () => {
try {
const brdzSDK = await import('anantla_sdk').then(sdk => sdk.default);
const crosschain = brdzSDK.crosschain;
const history = await crosschain.getCTransactionHistory(currentUser!.id, {
limit: 10,
offset: 0
});
const formattedTransfers = history.data.map((tx: any) => ({
log_id: tx.log_id,
from_chain: tx.from_chain,
to_chain: tx.to_chain,
amount: tx.amount,
status: tx.status,
burn_tx_hash: tx.burn_tx_hash,
mint_tx_hash: tx.mint_tx_hash,
created_at: tx.created_at,
duration: tx.completed_at ?
Math.round((new Date(tx.completed_at).getTime() - new Date(tx.created_at).getTime()) / 1000 / 60) : null
}));
setTransfers(formattedTransfers);
} catch (error) {
console.error('Failed to load transfer history:', error);
}
};
const initiateTransfer = async () => {
if (!transferForm.amount || !transferForm.recipientAddress) {
alert('Please fill in all required fields');
return;
}
if (!balances[transferForm.fromChain]?.address) {
alert(`No wallet found for ${transferForm.fromChain} chain`);
return;
}
try {
setLoading(true);
const brdzSDK = await import('anantla_sdk').then(sdk => sdk.default);
const crosschain = brdzSDK.crosschain;
const result = await crosschain.initiateTransfer({
user_id: currentUser!.id,
amount: transferForm.amount,
from_chain: transferForm.fromChain,
to_chain: transferForm.toChain,
token: 'USDC',
recipient_address: transferForm.recipientAddress,
return_address: balances[transferForm.fromChain].address
});
alert(`Transfer initiated! Log ID: ${result.log_id}\nBurn transaction required to complete.`);
// Reset form and reload data
setTransferForm({
fromChain: 'sepolia',
toChain: 'amoy',
amount: '',
recipientAddress: ''
});
await loadDashboardData();
} catch (error) {
alert(`Transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setLoading(false);
}
};
const getTotalBalance = () => {
return Object.values(balances).reduce((sum, chain) => sum + chain.value_usd, 0);
};
const getChainIcon = (chainId: string) => {
const icons: Record<string, string> = {
sepolia: '🔷',
amoy: '🟣',
neon: '🟢'
};
return icons[chainId] || '⛓️';
};
const getStatusColor = (status: string) => {
const colors: Record<string, string> = {
initiated: '#ffc107',
burn_completed: '#17a2b8',
completed: '#28a745',
failed: '#dc3545'
};
return colors[status] || '#6c757d';
};
return (
<div className="cross-chain-dashboard">
<div className="dashboard-header">
<h2>⛓️ Cross-Chain Operations</h2>
<button onClick={loadDashboardData} disabled={loading}>
{loading ? '⏳ Loading...' : '🔄 Refresh'}
</button>
</div>
{/* Chain Balances Overview */}
<section className="balances-section">
<h3>💰 Chain Balances</h3>
<div className="total-balance">
<span className="total-label">Total Portfolio:</span>
<span className="total-value">{getTotalBalance().toFixed(2)} USDC</span>
</div>
<div className="chain-balances">
{Object.entries(balances).map(([chainId, balance]) => (
<div key={chainId} className="balance-card">
<div className="chain-header">
<span className="chain-icon">{getChainIcon(chainId)}</span>
<span className="chain-name">{chainId.toUpperCase()}</span>
</div>
<div className="balance-amount">
{parseFloat(balance.balance).toFixed(2)} USDC
</div>
<div className="balance-info">
<div className="wallet-name">{balance.wallet_name || 'No Wallet'}</div>
{balance.address && (
<div className="wallet-address">
{balance.address.substring(0, 6)}...{balance.address.substring(-4)}
</div>
)}
</div>
</div>
))}
</div>
</section>
{/* Transfer Form */}
<section className="transfer-section">
<h3>🌉 New Cross-Chain Transfer</h3>
<div className="transfer-form">
<div className="form-row">
<div className="form-group">
<label>From Chain</label>
<select
value={transferForm.fromChain}
onChange={(e) => setTransferForm(prev => ({ ...prev, fromChain: e.target.value }))}
disabled={loading}
>
<option value="sepolia">🔷 Sepolia</option>
<option value="amoy">🟣 Polygon Amoy</option>
<option value="neon">🟢 Neon EVM</option>
</select>
</div>
<div className="transfer-arrow">→</div>
<div className="form-group">
<label>To Chain</label>
<select
value={transferForm.toChain}
onChange={(e) => setTransferForm(prev => ({ ...prev, toChain: e.target.value }))}
disabled={loading}
>
<option value="amoy">🟣 Polygon Amoy</option>
<option value="sepolia">🔷 Sepolia</option>
<option value="neon">🟢 Neon EVM</option>
</select>
</div>
</div>
<div className="form-row">
<div className="form-group">
<label>Amount (USDC)</label>
<input
type="number"
step="0.01"
placeholder="0.00"
value={transferForm.amount}
onChange={(e) => setTransferForm(prev => ({ ...prev, amount: e.target.value }))}
disabled={loading}
/>
<div className="balance-hint">
Available: {balances[transferForm.fromChain]?.balance || '0'} USDC
</div>
</div>
<div className="form-group">
<label>Recipient Address</label>
<input
type="text"
placeholder="0x..."
value={transferForm.recipientAddress}
onChange={(e) => setTransferForm(prev => ({ ...prev, recipientAddress: e.target.value }))}
disabled={loading}
/>
</div>
</div>
<button
onClick={initiateTransfer}
disabled={loading || !transferForm.amount || !transferForm.recipientAddress}
className="initiate-transfer-btn"
>
{loading ? '⏳ Processing...' : '🚀 Initiate Transfer'}
</button>
</div>
</section>
{/* Transfer History */}
<section className="history-section">
<h3>📊 Transfer History ({transfers.length})</h3>
{transfers.length === 0 ? (
<div className="empty-history">
<p>🌉 No cross-chain transfers yet</p>
<p>Start your first transfer above!</p>
</div>
) : (
<div className="transfers-list">
{transfers.map((transfer) => (
<div
key={transfer.log_id}
className="transfer-item"
onClick={() => setSelectedTransfer(transfer)}
>
<div className="transfer-route">
<span className="from-chain">
{getChainIcon(transfer.from_chain)} {transfer.from_chain}
</span>
<span className="arrow">→</span>
<span className="to-chain">
{getChainIcon(transfer.to_chain)} {transfer.to_chain}
</span>
</div>
<div className="transfer-amount">
{transfer.amount} USDC
</div>
<div className="transfer-status">
<span
className="status-badge"
style={{ backgroundColor: getStatusColor(transfer.status) }}
>
{transfer.status}
</span>
</div>
<div className="transfer-time">
{new Date(transfer.created_at).toLocaleDateString()}
{transfer.duration && (
<div className="duration">({transfer.duration}m)</div>
)}
</div>
<div className="transfer-actions">
<button className="view-details">👁️</button>
</div>
</div>
))}
</div>
)}
</section>
{/* Transfer Details Modal */}
{selectedTransfer && (
<div className="modal-overlay" onClick={() => setSelectedTransfer(null)}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
<div className="modal-header">
<h3>🔍 Transfer Details</h3>
<button onClick={() => setSelectedTransfer(null)}>✖</button>
</div>
<div className="modal-body">
<div className="detail-row">
<strong>Transfer ID:</strong>
<code>{selectedTransfer.log_id}</code>
</div>
<div className="detail-row">
<strong>Route:</strong>
{getChainIcon(selectedTransfer.from_chain)} {selectedTransfer.from_chain} → {getChainIcon(selectedTransfer.to_chain)} {selectedTransfer.to_chain}
</div>
<div className="detail-row">
<strong>Amount:</strong>
{selectedTransfer.amount} USDC
</div>
<div className="detail-row">
<strong>Status:</strong>
<span
className="status-badge"
style={{ backgroundColor: getStatusColor(selectedTransfer.status) }}
>
{selectedTransfer.status}
</span>
</div>
<div className="detail-row">
<strong>Created:</strong>
{new Date(selectedTransfer.created_at).toLocaleString()}
</div>
{selectedTransfer.burn_tx_hash && (
<div className="detail-row">
<strong>Burn TX:</strong>
<code className="tx-hash">{selectedTransfer.burn_tx_hash}</code>
</div>
)}
{selectedTransfer.mint_tx_hash && (
<div className="detail-row">
<strong>Mint TX:</strong>
<code className="tx-hash">{selectedTransfer.mint_tx_hash}</code>
</div>
)}
</div>
<div className="modal-actions">
<button onClick={() => setSelectedTransfer(null)}>
Close
</button>
</div>
</div>
</div>
)}
</div>
);
};
export default CrossChainDashboard;
AI Cross-Chain Assistant
import React, { useState } from 'react';
import { useSDK } from '../contexts/SDKContext';
interface AICrossChainRequest {
id: string;
input: string;
response: string;
intent_type: string;
execution_result?: any;
timestamp: Date;
}
const AICrossChainAssistant: React.FC = () => {
const { currentUser } = useSDK();
const [input, setInput] = useState('');
const [requests, setRequests] = useState<AICrossChainRequest[]>([]);
const [loading, setLoading] = useState(false);
const exampleCommands = [
"Show me balances across all chains",
"Move 25 USDC from Sepolia to Polygon Amoy",
"Find arbitrage opportunities between chains",
"Rebalance my portfolio to 50% Sepolia, 30% Amoy, 20% Neon",
"What are the best yield farming opportunities?",
"Help me optimize gas fees for cross-chain transfers"
];
const processAIRequest = async (userInput: string) => {
if (!userInput.trim()) return;
setLoading(true);
try {
const brdzSDK = await import('anantla_sdk').then(sdk => sdk.default);
const cryptoWallet = brdzSDK.cryptoWallet;
// Process AI request with cross-chain context
const result = await cryptoWallet.processAIIntent({
user_input: userInput,
user_id: currentUser!.id,
context: {
specialty: 'cross_chain_operations',
available_chains: ['sepolia', 'amoy', 'neon'],
supported_tokens: ['USDC'],
cross_chain_features: ['transfer', 'arbitrage', 'rebalancing', 'yield_analysis']
}
});
const aiResponse = cryptoWallet.utils.ai.parseResponse(result);
if (aiResponse) {
const newRequest: AICrossChainRequest = {
id: Date.now().toString(),
input: userInput,
response: aiResponse.message || 'No response',
intent_type: aiResponse.intent_type || 'unknown',
execution_result: aiResponse.execution_result,
timestamp: new Date()
};
setRequests(prev => [newRequest, ...prev]);
// Execute if required
if (aiResponse.execution_result?.requires_user_confirmation) {
const confirmed = confirm(`Execute this cross-chain operation?\n\n${aiResponse.message}`);
if (confirmed) {
await executeAIOperation(newRequest);
}
}
}
} catch (error) {
const errorRequest: AICrossChainRequest = {
id: Date.now().toString(),
input: userInput,
response: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
intent_type: 'error',
timestamp: new Date()
};
setRequests(prev => [errorRequest, ...prev]);
} finally {
setLoading(false);
setInput('');
}
};
const executeAIOperation = async (request: AICrossChainRequest) => {
try {
// This would execute the actual cross-chain operation
console.log('Executing AI operation:', request);
// Update request with execution status
setRequests(prev => prev.map(req =>
req.id === request.id
? { ...req, execution_result: { ...req.execution_result, executed: true } }
: req
));
} catch (error) {
console.error('Execution failed:', error);
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
processAIRequest(input);
};
const getIntentIcon = (intentType: string) => {
const icons: Record<string, string> = {
cross_chain_transfer: '🌉',
arbitrage_analysis: '💹',
portfolio_rebalance: '⚖️',
yield_analysis: '🌾',
balance_check: '💰',
gas_optimization: '⛽',
error: '❌',
unknown: '🤖'
};
return icons[intentType] || '🤖';
};
return (
<div className="ai-cross-chain-assistant">
<div className="assistant-header">
<h3>🤖 AI Cross-Chain Assistant</h3>
<p>Ask me anything about cross-chain operations, arbitrage, or portfolio management</p>
</div>
{/* Example Commands */}
<div className="example-commands">
<h4>💡 Try these commands:</h4>
<div className="commands-grid">
{exampleCommands.map((command, index) => (
<button
key={index}
className="command-suggestion"
onClick={() => setInput(command)}
disabled={loading}
>
{command}
</button>
))}
</div>
</div>
{/* Input Form */}
<form onSubmit={handleSubmit} className="ai-input-form">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Ask about cross-chain operations, balances, or strategies..."
disabled={loading}
className="ai-input"
/>
<button
type="submit"
disabled={loading || !input.trim()}
className="ai-submit"
>
{loading ? '🤔' : '🚀'}
</button>
</form>
{/* AI Conversations */}
<div className="ai-conversations">
{requests.length === 0 && (
<div className="empty-conversations">
<p>Start a conversation with the AI assistant!</p>
</div>
)}
{requests.map((request) => (
<div key={request.id} className="conversation-item">
<div className="user-message">
<div className="message-header">
<span className="sender">👤 You</span>
<span className="timestamp">
{request.timestamp.toLocaleTimeString()}
</span>
</div>
<div className="message-content">{request.input}</div>
</div>
<div className="ai-response">
<div className="message-header">
<span className="sender">
{getIntentIcon(request.intent_type)} AI Assistant
</span>
<span className="intent-badge">
{request.intent_type.replace('_', ' ')}
</span>
</div>
<div className="message-content">{request.response}</div>
{request.execution_result && (
<div className="execution-info">
<h5>⚡ Execution Details:</h5>
{request.execution_result.requires_user_confirmation && (
<p>⚠️ This operation requires confirmation</p>
)}
{request.execution_result.estimated_cost && (
<p>💰 Estimated Cost: ${request.execution_result.estimated_cost}</p>
)}
{request.execution_result.warnings && (
<p>⚠️ Warning: {request.execution_result.warnings}</p>
)}
{request.execution_result.executed && (
<p className="executed-badge">✅ Operation Executed</p>
)}
</div>
)}
</div>
</div>
))}
</div>
</div>
);
};
export default AICrossChainAssistant;
Styling for Cross-Chain Components
/* Cross-Chain Dashboard Styles */
.cross-chain-dashboard {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.dashboard-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
}
.dashboard-header button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
/* Balances Section */
.balances-section {
margin-bottom: 40px;
}
.total-balance {
display: flex;
justify-content: space-between;
align-items: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 8px;
margin-bottom: 20px;
}
.total-label {
font-size: 18px;
}
.total-value {
font-size: 24px;
font-weight: bold;
}
.chain-balances {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
.balance-card {
background: white;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
text-align: center;
}
.chain-header {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
margin-bottom: 15px;
}
.chain-icon {
font-size: 24px;
}
.chain-name {
font-weight: bold;
font-size: 16px;
}
.balance-amount {
font-size: 20px;
font-weight: bold;
color: #007bff;
margin-bottom: 10px;
}
.balance-info {
font-size: 12px;
color: #666;
}
.wallet-address {
font-family: 'Courier New', monospace;
background: #f8f9fa;
padding: 2px 4px;
border-radius: 4px;
margin-top: 5px;
}
/* Transfer Section */
.transfer-section {
background: #f8f9fa;
padding: 25px;
border-radius: 8px;
margin-bottom: 40px;
}
.transfer-form {
max-width: 600px;
}
.form-row {
display: flex;
align-items: end;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
flex: 1;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #495057;
}
.form-group input,
.form-group select {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.transfer-arrow {
font-size: 24px;
color: #007bff;
margin: 0 10px;
}
.balance-hint {
font-size: 12px;
color: #666;
margin-top: 5px;
}
.initiate-transfer-btn {
padding: 12px 24px;
background: linear-gradient(135deg, #28a745, #20c997);
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 16px;
font-weight: bold;
width: 100%;
}
.initiate-transfer-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
/* Transfer History */
.history-section {
margin-bottom: 40px;
}
.empty-history {
text-align: center;
padding: 40px;
color: #666;
background: #f8f9fa;
border-radius: 8px;
}
.transfers-list {
background: white;
border-radius: 8px;
overflow: hidden;
border: 1px solid #ddd;
}
.transfer-item {
display: grid;
grid-template-columns: 2fr 120px 120px 140px 80px;
gap: 15px;
align-items: center;
padding: 15px;
border-bottom: 1px solid #eee;
cursor: pointer;
transition: background-color 0.2s;
}
.transfer-item:hover {
background: #f8f9fa;
}
.transfer-route {
display: flex;
align-items: center;
gap: 10px;
}
.arrow {
color: #007bff;
font-weight: bold;
}
.transfer-amount {
font-weight: bold;
color: #495057;
}
.status-badge {
padding: 4px 8px;
border-radius: 12px;
color: white;
font-size: 11px;
text-transform: uppercase;
font-weight: bold;
}
.transfer-time {
font-size: 12px;
color: #666;
}
.duration {
font-style: italic;
color: #999;
}
.view-details {
background: #17a2b8;
color: white;
border: none;
padding: 4px 8px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
/* AI Assistant Styles */
.ai-cross-chain-assistant {
padding: 20px;
max-width: 800px;
margin: 0 auto;
}
.assistant-header {
text-align: center;
margin-bottom: 30px;
}
.example-commands {
margin-bottom: 30px;
}
.commands-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 10px;
margin-top: 15px;
}
.command-suggestion {
padding: 10px;
background: #f8f9fa;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
text-align: left;
transition: background-color 0.2s;
}
.command-suggestion:hover {
background: #e9ecef;
}
.command-suggestion:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.ai-input-form {
display: flex;
gap: 10px;
margin-bottom: 30px;
}
.ai-input {
flex: 1;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
}
.ai-submit {
padding: 12px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 16px;
}
.ai-submit:disabled {
background: #ccc;
cursor: not-allowed;
}
.ai-conversations {
max-height: 600px;
overflow-y: auto;
}
.empty-conversations {
text-align: center;
padding: 40px;
color: #666;
background: #f8f9fa;
border-radius: 8px;
}
.conversation-item {
margin-bottom: 30px;
}
.user-message,
.ai-response {
margin-bottom: 15px;
}
.user-message {
background: #007bff;
color: white;
padding: 15px;
border-radius: 8px;
margin-left: 20%;
}
.ai-response {
background: #f8f9fa;
border: 1px solid #ddd;
padding: 15px;
border-radius: 8px;
margin-right: 20%;
}
.message-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
font-size: 12px;
font-weight: bold;
}
.user-message .message-header {
color: rgba(255, 255, 255, 0.8);
}
.ai-response .message-header {
color: #666;
}
.intent-badge {
background: #28a745;
color: white;
padding: 2px 6px;
border-radius: 12px;
font-size: 10px;
text-transform: capitalize;
}
.execution-info {
margin-top: 15px;
padding: 10px;
background: rgba(0, 123, 255, 0.1);
border-radius: 4px;
border-left: 4px solid #007bff;
}
.execution-info h5 {
margin-bottom: 8px;
color: #007bff;
}
.executed-badge {
color: #28a745;
font-weight: bold;
}
/* Modal Styles */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 30px;
border-radius: 8px;
max-width: 600px;
width: 90%;
max-height: 80vh;
overflow-y: auto;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.modal-header button {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
}
.detail-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #eee;
}
.tx-hash {
font-family: 'Courier New', monospace;
background: #f8f9fa;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
}
.modal-actions {
display: flex;
justify-content: center;
margin-top: 20px;
}
.modal-actions button {
padding: 8px 16px;
background: #6c757d;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
/* Responsive Design */
@media (max-width: 768px) {
.form-row {
flex-direction: column;
}
.transfer-arrow {
transform: rotate(90deg);
margin: 10px 0;
}
.chain-balances {
grid-template-columns: 1fr;
}
.transfer-item {
grid-template-columns: 1fr;
gap: 10px;
}
.commands-grid {
grid-template-columns: 1fr;
}
.user-message,
.ai-response {
margin-left: 0;
margin-right: 0;
}
}
Advanced Cross-Chain Strategies
Automated Portfolio Management
class AutomatedCrossChainPortfolio {
constructor(userId) {
this.userId = userId;
this.crossChainManager = new AICrossChainManager(userId);
}
async executeAutomaticRebalancing(schedule = 'weekly') {
try {
// Define target portfolio distribution
const targetDistribution = {
sepolia: 40, // 40% Ethereum ecosystem
amoy: 35, // 35% Polygon ecosystem
neon: 25 // 25% Solana ecosystem
};
// Get current portfolio state
const balances = await this.crossChainManager.getAllChainBalances();
const rebalanceStrategy = await this.crossChainManager.rebalancePortfolio(targetDistribution);
console.log('🤖 Automated Rebalancing Strategy:');
console.log('Target Distribution:', targetDistribution);
console.log('Current Distribution:', rebalanceStrategy.current_distribution);
console.log('Required Actions:', rebalanceStrategy.rebalance_actions);
// Execute rebalancing actions
for (const action of rebalanceStrategy.rebalance_actions) {
await this.executeRebalanceAction(action);
// Wait between transactions
await new Promise(resolve => setTimeout(resolve, 5000));
}
return {
success: true,
actions_executed: rebalanceStrategy.rebalance_actions.length,
new_distribution: await this.crossChainManager.getAllChainBalances()
};
} catch (error) {
throw new Error(`Automated rebalancing failed: ${error.message}`);
}
}
async executeRebalanceAction(action) {
if (action.action === 'transfer') {
const balances = await this.crossChainManager.getAllChainBalances();
const fromAddress = balances[action.from_chain].address;
const toAddress = balances[action.to_chain].address;
return await this.crossChainManager.initiateCrossChainTransfer(
action.from_chain,
action.to_chain,
action.amount,
toAddress,
fromAddress
);
}
}
}
Best Practices
Error Handling and Recovery
const handleCrossChainErrors = async (operation, maxRetries = 3) => {
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
console.warn(`Cross-chain attempt ${attempt} failed:`, error.message);
// Handle specific error types
if (error.message.includes('insufficient balance')) {
throw new Error('Insufficient balance - cannot retry');
}
if (error.message.includes('invalid address')) {
throw new Error('Invalid address - cannot retry');
}
if (attempt < maxRetries) {
// Exponential backoff
const delay = Math.pow(2, attempt) * 2000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw new Error(`Cross-chain operation failed after ${maxRetries} attempts: ${lastError.message}`);
};
Security Considerations
const validateCrossChainOperation = (fromChain, toChain, amount, address) => {
// Validate chain IDs
const supportedChains = ['sepolia', 'amoy', 'neon'];
if (!supportedChains.includes(fromChain) || !supportedChains.includes(toChain)) {
throw new Error('Unsupported chain specified');
}
// Validate amount
if (isNaN(amount) || parseFloat(amount) <= 0) {
throw new Error('Invalid amount specified');
}
// Validate address format
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
throw new Error('Invalid Ethereum address format');
}
// Check minimum transfer amount
if (parseFloat(amount) < 1) {
throw new Error('Minimum transfer amount is 1 USDC');
}
// Check maximum transfer amount per transaction
if (parseFloat(amount) > 10000) {
throw new Error('Maximum transfer amount is 10,000 USDC per transaction');
}
return true;
};
Bridge Module Integration
Virtual Account Bridging
class BridgeManager {
constructor(userId) {
this.userId = userId;
this.bridge = brdzSDK.bridge;
this.crosschain = brdzSDK.crosschain;
}
// Get available chains for bridging
async getAvailableBridgeChains() {
try {
const chains = await this.bridge.getAvailableChains();
return chains.map(chain => ({
chain_id: chain.chain_id,
name: chain.name,
native_currency: chain.native_currency,
bridge_support: chain.bridge_support,
virtual_account_support: chain.virtual_account_support,
fees: chain.estimated_fees
}));
} catch (error) {
throw new Error(`Failed to get bridge chains: ${error.message}`);
}
}
// Get user's bridge wallets (Virtual Accounts)
async getUserBridgeWallets() {
try {
const wallets = await this.bridge.getUserBridgeWallets(this.userId);
return wallets.map(wallet => ({
wallet_id: wallet.wallet_id,
chain: wallet.chain,
address: wallet.address,
currency: wallet.currency,
balance: wallet.balance,
type: wallet.type, // 'virtual_account' or 'cross_chain_address'
created_at: wallet.created_at,
status: wallet.status
}));
} catch (error) {
throw new Error(`Failed to get bridge wallets: ${error.message}`);
}
}
// Add new bridge wallet/Virtual Account
async addBridgeWallet(chainId, currency = 'USDC') {
try {
const result = await this.bridge.addBridgeWallet({
user_id: this.userId,
chain: chainId,
address: null, // Will be generated
currency: currency
});
return {
wallet_id: result.wallet_id,
chain: result.chain,
address: result.generated_address,
currency: result.currency,
type: result.type
};
} catch (error) {
throw new Error(`Failed to add bridge wallet: ${error.message}`);
}
}
// Simulate bridge operation with fees
async simulateBridgeOperation(fromChain, toChain, amount, currency = 'USDC') {
try {
const simulation = await this.bridge.simulateBridge({
from_chain: fromChain,
to_chain: toChain,
amount: amount,
currency: currency
});
return {
from_chain: simulation.from_chain,
to_chain: simulation.to_chain,
input_amount: simulation.input_amount,
output_amount: simulation.output_amount,
bridge_fee: simulation.bridge_fee,
gas_estimate: simulation.gas_estimate,
total_cost: simulation.total_cost,
execution_time: simulation.estimated_time,
price_impact: simulation.price_impact,
route: simulation.optimal_route
};
} catch (error) {
throw new Error(`Bridge simulation failed: ${error.message}`);
}
}
// Execute bridge operation
async executeBridgeOperation(fromWalletId, toChain, amount) {
try {
const result = await this.bridge.executeBridge({
from_wallet_id: fromWalletId,
to_chain: toChain,
amount: amount
});
return {
bridge_tx_id: result.bridge_tx_id,
from_tx_hash: result.from_tx_hash,
to_tx_hash: result.to_tx_hash,
status: result.status,
estimated_completion: result.estimated_completion,
tracking_url: result.tracking_url
};
} catch (error) {
throw new Error(`Bridge execution failed: ${error.message}`);
}
}
// Combined Cross-Chain + Bridge Strategy
async executeOptimalTransfer(fromChain, toChain, amount, recipientAddress) {
try {
// Compare both CrossChain and Bridge options
const crossChainOption = await this.simulateCrossChain(fromChain, toChain, amount);
const bridgeOption = await this.simulateBridgeOperation(fromChain, toChain, amount);
console.log('🔍 Comparing transfer options:');
console.log('CrossChain:', crossChainOption);
console.log('Bridge:', bridgeOption);
// Choose optimal route based on cost and time
const optimalRoute = this.selectOptimalRoute(crossChainOption, bridgeOption);
if (optimalRoute.method === 'crosschain') {
return await this.executeCrossChainTransfer(fromChain, toChain, amount, recipientAddress);
} else {
return await this.executeBridgeTransfer(fromChain, toChain, amount, recipientAddress);
}
} catch (error) {
throw new Error(`Optimal transfer failed: ${error.message}`);
}
}
selectOptimalRoute(crossChainOption, bridgeOption) {
// Cost comparison (lower is better)
const crossChainCost = parseFloat(crossChainOption.total_fees || '0');
const bridgeCost = parseFloat(bridgeOption.total_cost || '0');
// Time comparison (lower is better)
const crossChainTime = crossChainOption.estimated_time || 300; // 5 minutes default
const bridgeTime = bridgeOption.execution_time || 600; // 10 minutes default
// Simple scoring: cost weight 70%, time weight 30%
const crossChainScore = (crossChainCost * 0.7) + (crossChainTime * 0.3);
const bridgeScore = (bridgeCost * 0.7) + (bridgeTime * 0.3);
if (crossChainScore <= bridgeScore) {
return {
method: 'crosschain',
reason: `Better cost/time ratio: ${crossChainCost} in ${crossChainTime}s`,
savings: bridgeScore - crossChainScore
};
} else {
return {
method: 'bridge',
reason: `Better cost/time ratio: ${bridgeCost} in ${bridgeTime}s`,
savings: crossChainScore - bridgeScore
};
}
}
async simulateCrossChain(fromChain, toChain, amount) {
// Estimate CrossChain costs (simplified)
const gasEstimate = 0.05; // ~$0.05 per chain
const totalFees = gasEstimate * 2; // Burn + Mint
return {
method: 'crosschain',
total_fees: totalFees.toString(),
estimated_time: 300, // 5 minutes
reliability: 'high'
};
}
}
// Usage Example
const bridgeManager = new BridgeManager(123);
// Get bridge options
const bridgeChains = await bridgeManager.getAvailableBridgeChains();
console.log('Available bridge chains:', bridgeChains);
// Add virtual account for new chain
const newWallet = await bridgeManager.addBridgeWallet('avalanche', 'USDC');
console.log('New bridge wallet:', newWallet);
// Execute optimal transfer
const optimalTransfer = await bridgeManager.executeOptimalTransfer(
'sepolia',
'amoy',
'100.00',
'0x742d35Cc6635C0532925a3b8D400d93458f8DA83'
);
Advanced Cross-Chain Analytics
Portfolio Analytics Dashboard
class CrossChainAnalytics {
constructor(userId) {
this.userId = userId;
this.crosschain = brdzSDK.crosschain;
this.cryptoWallet = brdzSDK.cryptoWallet;
this.onchain = brdzSDK.onchain;
}
// Comprehensive portfolio analysis
async generatePortfolioAnalytics(timeframe = '30d') {
try {
const [balances, history, onchainHistory] = await Promise.all([
this.getAllChainBalances(),
this.getCrossChainHistory(),
this.getOnchainHistory()
]);
const analytics = {
portfolio_summary: this.calculatePortfolioSummary(balances),
chain_distribution: this.calculateChainDistribution(balances),
transaction_volume: this.calculateTransactionVolume(history, onchainHistory),
cross_chain_activity: this.analyzeCrossChainActivity(history),
cost_analysis: this.analyzeCosts(history, onchainHistory),
recommendations: await this.generateRecommendations(balances, history)
};
return analytics;
} catch (error) {
throw new Error(`Portfolio analytics failed: ${error.message}`);
}
}
calculatePortfolioSummary(balances) {
const totalBalance = Object.values(balances).reduce(
(sum, chain) => sum + parseFloat(chain.balance || '0'), 0
);
const activeChains = Object.values(balances).filter(
chain => parseFloat(chain.balance || '0') > 0
).length;
return {
total_balance: totalBalance.toFixed(2),
active_chains: activeChains,
largest_position: this.findLargestPosition(balances),
smallest_position: this.findSmallestPosition(balances),
diversity_score: this.calculateDiversityScore(balances, totalBalance)
};
}
calculateChainDistribution(balances) {
const totalBalance = Object.values(balances).reduce(
(sum, chain) => sum + parseFloat(chain.balance || '0'), 0
);
const distribution = {};
Object.keys(balances).forEach(chain => {
const amount = parseFloat(balances[chain]?.balance || '0');
distribution[chain] = {
amount: amount.toFixed(2),
percentage: totalBalance > 0 ? ((amount / totalBalance) * 100).toFixed(1) : '0',
address: balances[chain].address,
wallet_name: balances[chain].wallet_name
};
});
return distribution;
}
calculateTransactionVolume(crossChainHistory, onchainHistory) {
const now = new Date();
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
// Cross-chain volume
const recentCrossChain = crossChainHistory.filter(tx =>
new Date(tx.created_at) >= thirtyDaysAgo
);
const crossChainVolume = recentCrossChain.reduce(
(sum, tx) => sum + parseFloat(tx.amount || '0'), 0
);
// On-chain volume
const recentOnchain = onchainHistory.filter(tx =>
new Date(tx.created_at) >= thirtyDaysAgo
);
const onchainVolume = recentOnchain.reduce(
(sum, tx) => sum + parseFloat(tx.amount || '0'), 0
);
return {
total_volume_30d: (crossChainVolume + onchainVolume).toFixed(2),
cross_chain_volume_30d: crossChainVolume.toFixed(2),
onchain_volume_30d: onchainVolume.toFixed(2),
transaction_count_30d: recentCrossChain.length + recentOnchain.length,
average_transaction_size: ((crossChainVolume + onchainVolume) / (recentCrossChain.length + recentOnchain.length + 1)).toFixed(2)
};
}
analyzeCrossChainActivity(history) {
const chainPairs = {};
const chainActivity = {};
history.forEach(tx => {
// Track chain pairs
const pair = `${tx.from_chain}-${tx.to_chain}`;
chainPairs[pair] = (chainPairs[pair] || 0) + 1;
// Track individual chain activity
chainActivity[tx.from_chain] = (chainActivity[tx.from_chain] || 0) + 1;
chainActivity[tx.to_chain] = (chainActivity[tx.to_chain] || 0) + 1;
});
const mostActiveRoute = Object.keys(chainPairs).reduce(
(max, pair) => chainPairs[pair] > (chainPairs[max] || 0) ? pair : max,
Object.keys(chainPairs)[0]
);
const mostActiveChain = Object.keys(chainActivity).reduce(
(max, chain) => chainActivity[chain] > (chainActivity[max] || 0) ? chain : max,
Object.keys(chainActivity)[0]
);
return {
most_active_route: mostActiveRoute,
most_active_chain: mostActiveChain,
unique_routes: Object.keys(chainPairs).length,
route_frequency: chainPairs,
chain_activity: chainActivity
};
}
analyzeCosts(crossChainHistory, onchainHistory) {
// Calculate total fees spent
const crossChainFees = crossChainHistory.reduce((sum, tx) => {
const burnFee = parseFloat(tx.burn_gas_fee || '0');
const mintFee = parseFloat(tx.mint_gas_fee || '0');
return sum + burnFee + mintFee;
}, 0);
const onchainFees = onchainHistory.reduce((sum, tx) => {
const gasFee = parseFloat(tx.gas_fee || '0');
const platformFee = parseFloat(tx.platform_fee || '0');
return sum + gasFee + platformFee;
}, 0);
const totalFees = crossChainFees + onchainFees;
const totalVolume = this.calculateTotalVolume(crossChainHistory, onchainHistory);
return {
total_fees_spent: totalFees.toFixed(4),
cross_chain_fees: crossChainFees.toFixed(4),
onchain_fees: onchainFees.toFixed(4),
fee_to_volume_ratio: totalVolume > 0 ? ((totalFees / totalVolume) * 100).toFixed(3) : '0',
average_fee_per_transaction: (totalFees / (crossChainHistory.length + onchainHistory.length + 1)).toFixed(4),
cost_efficiency_score: this.calculateCostEfficiency(totalFees, totalVolume)
};
}
async generateRecommendations(balances, history) {
const recommendations = [];
// Portfolio concentration check
const distribution = this.calculateChainDistribution(balances);
const maxConcentration = Math.max(...Object.values(distribution).map(d => parseFloat(d.percentage)));
if (maxConcentration > 60) {
recommendations.push({
type: 'portfolio_rebalancing',
priority: 'high',
message: `Your portfolio is ${maxConcentration}% concentrated in one chain. Consider rebalancing for better risk distribution.`,
action: 'rebalance_portfolio'
});
}
// Low balance utilization
const smallBalances = Object.entries(distribution).filter(
([chain, data]) => parseFloat(data.amount) > 0 && parseFloat(data.amount) < 10
);
if (smallBalances.length > 0) {
recommendations.push({
type: 'balance_optimization',
priority: 'medium',
message: `You have small balances (< $10) on ${smallBalances.length} chain(s). Consider consolidating to reduce gas costs.`,
action: 'consolidate_balances'
});
}
// Inactivity check
const recentActivity = history.filter(tx => {
const txDate = new Date(tx.created_at);
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
return txDate >= thirtyDaysAgo;
});
if (recentActivity.length === 0 && Object.values(balances).some(b => parseFloat(b.balance || '0') > 0)) {
recommendations.push({
type: 'yield_opportunity',
priority: 'low',
message: 'No cross-chain activity in 30 days. Consider yield farming opportunities to grow your idle assets.',
action: 'explore_yield_farming'
});
}
// Gas optimization
const avgFeeRatio = this.calculateAverageFeeRatio(history);
if (avgFeeRatio > 2) { // If fees > 2% of transaction value
recommendations.push({
type: 'cost_optimization',
priority: 'medium',
message: 'Your transaction fees are high relative to transfer amounts. Consider larger, less frequent transfers.',
action: 'optimize_transaction_size'
});
}
return recommendations;
}
// Helper methods
findLargestPosition(balances) {
let largest = { chain: '', amount: 0 };
Object.entries(balances).forEach(([chain, data]) => {
const amount = parseFloat(data.balance || '0');
if (amount > largest.amount) {
largest = { chain, amount };
}
});
return largest;
}
findSmallestPosition(balances) {
let smallest = { chain: '', amount: Infinity };
Object.entries(balances).forEach(([chain, data]) => {
const amount = parseFloat(data.balance || '0');
if (amount > 0 && amount < smallest.amount) {
smallest = { chain, amount };
}
});
return smallest.amount === Infinity ? { chain: '', amount: 0 } : smallest;
}
calculateDiversityScore(balances, totalBalance) {
if (totalBalance === 0) return 0;
// Shannon diversity index adapted for crypto portfolios
let diversity = 0;
Object.values(balances).forEach(chain => {
const proportion = parseFloat(chain.balance || '0') / totalBalance;
if (proportion > 0) {
diversity -= proportion * Math.log2(proportion);
}
});
// Normalize to 0-100 scale
return Math.min(100, (diversity / Math.log2(3)) * 100).toFixed(1);
}
calculateTotalVolume(crossChainHistory, onchainHistory) {
const crossChainVolume = crossChainHistory.reduce(
(sum, tx) => sum + parseFloat(tx.amount || '0'), 0
);
const onchainVolume = onchainHistory.reduce(
(sum, tx) => sum + parseFloat(tx.amount || '0'), 0
);
return crossChainVolume + onchainVolume;
}
calculateCostEfficiency(totalFees, totalVolume) {
if (totalVolume === 0) return 0;
const feeRatio = (totalFees / totalVolume) * 100;
// Score: 100 = very efficient (< 0.5% fees), 0 = very inefficient (> 5% fees)
if (feeRatio < 0.5) return 100;
if (feeRatio > 5) return 0;
return Math.max(0, 100 - (feeRatio - 0.5) * 22.2);
}
calculateAverageFeeRatio(history) {
if (history.length === 0) return 0;
const totalFeeRatio = history.reduce((sum, tx) => {
const amount = parseFloat(tx.amount || '1');
const fees = parseFloat(tx.total_fees || '0');
return sum + (fees / amount);
}, 0);
return (totalFeeRatio / history.length) * 100;
}
async getAllChainBalances() {
// Implementation from CrossChainManager
const crossChainManager = new CrossChainManager(this.userId);
return await crossChainManager.getAllChainBalances();
}
async getCrossChainHistory() {
return await this.crosschain.getCTransactionHistory(this.userId, { limit: 100 });
}
async getOnchainHistory() {
const history = await this.onchain.getTransactionHistory(this.userId, { limit: 100 });
return history.data || [];
}
}
// Usage Example
const analytics = new CrossChainAnalytics(123);
const portfolioReport = await analytics.generatePortfolioAnalytics('30d');
console.log('📊 Portfolio Analytics Report:');
console.log('Summary:', portfolioReport.portfolio_summary);
console.log('Distribution:', portfolioReport.chain_distribution);
console.log('Volume:', portfolioReport.transaction_volume);
console.log('Recommendations:', portfolioReport.recommendations);
Performance Optimization
Cross-Chain Operation Batching
class BatchCrossChainOperations {
constructor(userId) {
this.userId = userId;
this.crosschain = brdzSDK.crosschain;
this.pendingOperations = [];
}
// Queue multiple cross-chain operations
queueOperation(operation) {
this.pendingOperations.push({
id: Date.now().toString(),
...operation,
status: 'queued',
created_at: new Date()
});
}
// Execute all queued operations in optimal order
async executeBatchOperations() {
if (this.pendingOperations.length === 0) {
return { message: 'No operations in queue' };
}
try {
// Optimize execution order
const optimizedQueue = this.optimizeExecutionOrder(this.pendingOperations);
console.log(`🚀 Executing ${optimizedQueue.length} cross-chain operations...`);
const results = [];
for (const operation of optimizedQueue) {
try {
operation.status = 'executing';
const result = await this.executeOperation(operation);
operation.status = 'completed';
operation.result = result;
results.push({
id: operation.id,
success: true,
result: result
});
// Wait between operations to avoid rate limits
await new Promise(resolve => setTimeout(resolve, 3000));
} catch (error) {
operation.status = 'failed';
operation.error = error.message;
results.push({
id: operation.id,
success: false,
error: error.message
});
}
}
// Clear completed operations
this.pendingOperations = this.pendingOperations.filter(
op => op.status === 'queued'
);
return {
total_operations: optimizedQueue.length,
successful: results.filter(r => r.success).length,
failed: results.filter(r => !r.success).length,
results: results,
execution_time: Date.now()
};
} catch (error) {
throw new Error(`Batch execution failed: ${error.message}`);
}
}
optimizeExecutionOrder(operations) {
// Sort operations for optimal execution:
// 1. Group by source chain to minimize chain switching
// 2. Order by amount (larger first to handle liquidity better)
// 3. Prioritize operations with higher success probability
return operations.sort((a, b) => {
// Primary: Group by source chain
if (a.from_chain !== b.from_chain) {
return a.from_chain.localeCompare(b.from_chain);
}
// Secondary: Larger amounts first
const amountA = parseFloat(a.amount || '0');
const amountB = parseFloat(b.amount || '0');
return amountB - amountA;
});
}
async executeOperation(operation) {
switch (operation.type) {
case 'cross_chain_transfer':
return await this.crosschain.initiateTransfer({
user_id: this.userId,
amount: operation.amount,
from_chain: operation.from_chain,
to_chain: operation.to_chain,
token: operation.token || 'USDC',
recipient_address: operation.recipient_address,
return_address: operation.return_address
});
case 'balance_check':
return await this.crosschain.getUSDCBalance(
operation.chain,
operation.address
);
default:
throw new Error(`Unknown operation type: ${operation.type}`);
}
}
// Get queue status
getQueueStatus() {
const statusCount = this.pendingOperations.reduce((acc, op) => {
acc[op.status] = (acc[op.status] || 0) + 1;
return acc;
}, {});
return {
total_operations: this.pendingOperations.length,
status_breakdown: statusCount,
estimated_execution_time: this.pendingOperations.length * 5, // 5 seconds per operation
queue: this.pendingOperations.map(op => ({
id: op.id,
type: op.type,
status: op.status,
created_at: op.created_at
}))
};
}
// Clear queue
clearQueue() {
this.pendingOperations = [];
return { message: 'Queue cleared' };
}
}
// Usage Example
const batchOperations = new BatchCrossChainOperations(123);
// Queue multiple operations
batchOperations.queueOperation({
type: 'cross_chain_transfer',
from_chain: 'sepolia',
to_chain: 'amoy',
amount: '50.00',
recipient_address: '0x742d35Cc6635C0532925a3b8D400d93458f8DA83',
return_address: '0x8ba1f109551bD432803012645Hac136c5C63c2C7'
});
batchOperations.queueOperation({
type: 'cross_chain_transfer',
from_chain: 'sepolia',
to_chain: 'neon',
amount: '25.00',
recipient_address: '0x456...789',
return_address: '0x123...456'
});
// Check queue status
const queueStatus = batchOperations.getQueueStatus();
console.log('Queue Status:', queueStatus);
// Execute all operations
const batchResults = await batchOperations.executeBatchOperations();
console.log('Batch Results:', batchResults);
Testing and Debugging
Cross-Chain Testing Suite
class CrossChainTestSuite {
constructor(userId) {
this.userId = userId;
this.testResults = [];
}
async runCompleteTestSuite() {
console.log('🧪 Starting Cross-Chain Test Suite...');
const tests = [
() => this.testBalanceRetrieval(),
() => this.testTransferInitiation(),
() => this.testHistoryRetrieval(),
() => this.testErrorHandling(),
() => this.testAIIntegration()
];
for (const test of tests) {
try {
await test();
} catch (error) {
console.error('Test failed:', error);
}
}
return this.generateTestReport();
}
async testBalanceRetrieval() {
const testName = 'Balance Retrieval';
console.log(`🔍 Testing: ${testName}`);
try {
const crossChainManager = new CrossChainManager(this.userId);
const balances = await crossChainManager.getAllChainBalances();
const hasValidStructure = typeof balances === 'object' &&
Object.keys(balances).length > 0;
this.testResults.push({
test: testName,
status: hasValidStructure ? 'PASS' : 'FAIL',
details: hasValidStructure ? 'Valid balance structure returned' : 'Invalid balance structure',
data: balances
});
} catch (error) {
this.testResults.push({
test: testName,
status: 'ERROR',
details: error.message,
data: null
});
}
}
async testTransferInitiation() {
const testName = 'Transfer Initiation (Dry Run)';
console.log(`🔍 Testing: ${testName}`);
try {
// Test with minimal amount to avoid actual transfers
const crossChainManager = new CrossChainManager(this.userId);
// Get user balances first
const balances = await crossChainManager.getAllChainBalances();
const hasValidWallets = Object.values(balances).some(
chain => chain.address && chain.address.length > 0
);
if (!hasValidWallets) {
throw new Error('No valid wallet addresses found for testing');
}
this.testResults.push({
test: testName,
status: 'PASS',
details: 'Transfer initiation prerequisites validated',
data: { wallet_addresses_found: hasValidWallets }
});
} catch (error) {
this.testResults.push({
test: testName,
status: 'ERROR',
details: error.message,
data: null
});
}
}
async testHistoryRetrieval() {
const testName = 'History Retrieval';
console.log(`🔍 Testing: ${testName}`);
try {
const crossChainManager = new CrossChainManager(this.userId);
const history = await crossChainManager.getCrossChainHistory(5);
const hasValidHistory = Array.isArray(history) &&
history.every(tx => tx.log_id && tx.from_chain && tx.to_chain);
this.testResults.push({
test: testName,
status: 'PASS',
details: `Retrieved ${history.length} historical transactions`,
data: { transaction_count: history.length, valid_structure: hasValidHistory }
});
} catch (error) {
this.testResults.push({
test: testName,
status: 'ERROR',
details: error.message,
data: null
});
}
}
async testErrorHandling() {
const testName = 'Error Handling';
console.log(`🔍 Testing: ${testName}`);
try {
const crossChainManager = new CrossChainManager(this.userId);
// Test invalid chain ID
let errorCaught = false;
try {
await crossChainManager.initiateCrossChainTransfer(
'invalid_chain',
'sepolia',
'1.00',
'0x742d35Cc6635C0532925a3b8D400d93458f8DA83',
'0x8ba1f109551bD432803012645Hac136c5C63c2C7'
);
} catch (error) {
errorCaught = true;
}
this.testResults.push({
test: testName,
status: errorCaught ? 'PASS' : 'FAIL',
details: errorCaught ? 'Error handling working correctly' : 'Error handling not working',
data: { error_properly_caught: errorCaught }
});
} catch (error) {
this.testResults.push({
test: testName,
status: 'ERROR',
details: error.message,
data: null
});
}
}
async testAIIntegration() {
const testName = 'AI Integration';
console.log(`🔍 Testing: ${testName}`);
try {
const aiManager = new AICrossChainManager(this.userId);
const response = await aiManager.processAICrossChainRequest(
"Show me my balances across all chains"
);
const hasValidAIResponse = response.success && response.message;
this.testResults.push({
test: testName,
status: hasValidAIResponse ? 'PASS' : 'FAIL',
details: hasValidAIResponse ? 'AI integration working' : 'AI integration failed',
data: { ai_response_valid: hasValidAIResponse, intent_type: response.intent_type }
});
} catch (error) {
this.testResults.push({
test: testName,
status: 'ERROR',
details: error.message,
data: null
});
}
}
generateTestReport() {
const totalTests = this.testResults.length;
const passedTests = this.testResults.filter(t => t.status === 'PASS').length;
const failedTests = this.testResults.filter(t => t.status === 'FAIL').length;
const errorTests = this.testResults.filter(t => t.status === 'ERROR').length;
const report = {
summary: {
total_tests: totalTests,
passed: passedTests,
failed: failedTests,
errors: errorTests,
success_rate: totalTests > 0 ? ((passedTests / totalTests) * 100).toFixed(1) : '0'
},
details: this.testResults,
timestamp: new Date().toISOString(),
recommendations: this.generateRecommendations()
};
console.log('📊 Test Report Generated:');
console.log('Summary:', report.summary);
return report;
}
generateRecommendations() {
const recommendations = [];
const hasErrors = this.testResults.some(t => t.status === 'ERROR');
const hasFailures = this.testResults.some(t => t.status === 'FAIL');
if (hasErrors) {
recommendations.push('🔧 Fix configuration errors before using cross-chain features');
}
if (hasFailures) {
recommendations.push('⚠️ Some features may not work correctly - review failed tests');
}
if (!hasErrors && !hasFailures) {
recommendations.push('✅ All systems operational - ready for cross-chain operations');
}
return recommendations;
}
}
// Usage Example
const testSuite = new CrossChainTestSuite(123);
const testReport = await testSuite.runCompleteTestSuite();
console.log('Final Test Report:', testReport);
Next Steps
You've mastered advanced cross-chain operations with BRDZ SDK:
✅ Cross-Chain Transfers - USDC transfers between Sepolia, Amoy, and Neon
✅ Bridge Integration - Virtual account management and optimal routing
✅ AI-Powered Operations - Natural language cross-chain management
✅ Advanced Strategies - Arbitrage, portfolio rebalancing, yield farming
✅ Analytics Dashboard - Comprehensive portfolio analysis and recommendations
✅ React Components - Production-ready cross-chain interfaces
✅ Performance Optimization - Batch operations and cost optimization
✅ Testing Suite - Comprehensive testing and debugging tools
Continue Learning
- SDK Reference - Complete CrossChain module documentation
- SDK Reference - Bridge module APIs
- SDK Reference - AI wallet integration
Build Advanced Features
- Automated portfolio rebalancing bots
- Cross-chain arbitrage strategies
- Multi-chain DeFi yield optimization
- Enterprise cross-chain payment solutions
- Advanced analytics and reporting
If you encounter issues:
- Email: contact@anantla.com
- Contact: BRDZ Contact Form