Skip to main content

Cross-Chain Swaps with Mach SDK

One of the most powerful features of Mach Exchange is the ability to perform cross-chain swaps, allowing users to trade tokens across different blockchains in a single transaction. This guide explains how to implement cross-chain swaps using the Mach SDK.

Understanding Cross-Chain Swaps

Mach’s cross-chain functionality uses a combination of optimistic settlement and the challenge system to provide secure and efficient cross-chain trading.

Checking Cross-Chain Support

First, verify which chains and token pairs support cross-chain swaps:
import { MachSDK } from '@mach-exchange/sdk';

const machSdk = new MachSDK();

// Get supported chains
const config = await machSdk.getConfig();
const supportedChains = config.supportedChains;

console.log('Supported chains for cross-chain swaps:', supportedChains);

// Check if a specific cross-chain pair is supported
const isSupportedPair = await machSdk.isCrossChainPairSupported({
  fromChainId: 1, // Ethereum
  toChainId: 137, // Polygon
  fromToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI on Ethereum
  toToken: '0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063' // DAI on Polygon
});

console.log('Is this cross-chain pair supported?', isSupportedPair);

Getting a Cross-Chain Quote

Before executing a swap, you’ll want to get a quote:
const crossChainQuote = await machSdk.getQuote({
  fromToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI on Ethereum
  toToken: '0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063', // DAI on Polygon
  amount: '1000000000000000000', // 1 DAI (in wei)
  fromChainId: 1, // Ethereum
  toChainId: 137, // Polygon
  slippage: 0.5 // 0.5% slippage tolerance
});

console.log('Expected output amount:', crossChainQuote.expectedOutput);
console.log('Estimated fee:', crossChainQuote.fee);
console.log('Estimated completion time:', crossChainQuote.estimatedTimeMinutes, 'minutes');

Executing a Cross-Chain Swap

To execute the swap after receiving a quote:
const swapResult = await machSdk.executeCrossChainSwap({
  fromToken: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI on Ethereum
  toToken: '0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063', // DAI on Polygon
  amount: '1000000000000000000', // 1 DAI (in wei)
  fromChainId: 1, // Ethereum
  toChainId: 137, // Polygon
  slippage: 0.5, // 0.5% slippage tolerance
  recipient: '0xYourWalletAddress', // Where to receive the tokens
  deadline: Math.floor(Date.now() / 1000) + 3600 // 1 hour from now
});

console.log('Swap initiated:', swapResult.id);
console.log('Source transaction hash:', swapResult.sourceTxHash);

Tracking a Cross-Chain Swap

Track the progress of your cross-chain swap:
const swapId = swapResult.id;

// One-time check
const status = await machSdk.getCrossChainSwapStatus(swapId);
console.log('Current status:', status.state);
console.log('Progress:', status.progress);

// Subscribe to updates
const unsubscribe = machSdk.subscribeToCrossChainSwap(swapId, (update) => {
  console.log('Swap update:', update.state);
  console.log('Progress:', update.progress);
  
  if (update.state === 'COMPLETED') {
    console.log('Swap completed!');
    console.log('Destination transaction hash:', update.destinationTxHash);
    unsubscribe(); // Stop listening for updates
  }
  
  if (update.state === 'FAILED') {
    console.error('Swap failed:', update.error);
    unsubscribe(); // Stop listening for updates
  }
});

Handling Timeouts and Failures

Cross-chain swaps can sometimes encounter issues. Here’s how to handle them:
try {
  const status = await machSdk.getCrossChainSwapStatus(swapId);
  
  if (status.state === 'STUCK') {
    // Attempt to accelerate the swap
    const accelerateResult = await machSdk.accelerateCrossChainSwap(swapId, {
      additionalFee: '0.01' // Additional fee in ETH to expedite
    });
    console.log('Acceleration requested:', accelerateResult.success);
  }
  
  if (status.state === 'TIMED_OUT') {
    // Initiate refund process
    const refundResult = await machSdk.requestCrossChainSwapRefund(swapId);
    console.log('Refund requested:', refundResult.refundTxHash);
  }
} catch (error) {
  console.error('Error checking swap status:', error);
}

Next Steps