Executing a Quote

After receiving a quote from the API, you'll need to handle the transaction execution process. This involves managing token approvals (if needed) and executing the main transfer transaction.

Prerequisites

  • Ethers.js v6 or later

  • A Web3-enabled browser (MetaMask or similar)

  • A valid quote response from the API

Quote Response Types from Request Quote

Direct Transfer Response :

{
  message: "Direct transfer transaction prepared",
  transactionId: string,
  type: "Direct",
  approvalTxParams: null
  transferTxParams: {
    to: string,
    data: string,
    value: string,
    gas: string
  },
}

Swap Transactions Response:

{
  message: "Quote requested",
  transactionId: string,
  type: "Provider",
  approvalTxParams?: {  // Present if token approval needed
    to: string,
    data: string,
    value: string,
    gas: string
  },
  transactionRequest: {
    to: string,
    data: string,
    value: string,
    gas: string
  }
}

Response Field Details

Common Fields

  • transactionId: Unique identifier for tracking the transfer

  • type: Indicates transfer type ("Direct" or "Provider")

  • gas: Estimated gas limit in hexadecimal

Transaction Parameters

  • to: Target contract or recipient address

  • data: Encoded transaction data (empty for native transfers)

  • value: Amount in wei (used for native token transfers)

Approval Parameters

  • Present only when token approval is needed

  • Contains parameters for approving token spending

  • Must be executed before the main transfer

Basic Implementation

import { ethers } from 'ethers';

async function executeQuote(quoteResponse: QuoteResponse) {
  // Initialize provider and signer
  const provider = new ethers.BrowserProvider(window.ethereum);
  const signer = await provider.getSigner();
  
  try {
    // Step 1: Handle token approval if needed
    if (quoteResponse.approvalTxParams) {
      const approvalTx = await signer.sendTransaction({
        to: quoteResponse.approvalTxParams.to,
        data: quoteResponse.approvalTxParams.data,
        value: ethers.toBigInt(quoteResponse.approvalTxParams.value || '0'),
        gasLimit: ethers.toBigInt(quoteResponse.approvalTxParams.gas)
      });
      
      // Wait for approval confirmation
      await approvalTx.wait();
    }

    // Step 2: Execute main transfer
    const txParams = quoteResponse.type === 'Direct' 
      ? quoteResponse.transferTxParams 
      : quoteResponse.transactionRequest;

    const tx = await signer.sendTransaction({
      to: txParams.to,
      data: txParams.data,
      value: ethers.toBigInt(txParams.value || '0'),
      gasLimit: ethers.toBigInt(txParams.gas)
    });

    return tx.hash;
  } catch (error) {
    console.error('Transaction failed:', error);
    throw error;
  }
}

Best Practices

  • Approval Handling

    • Always check for approvalTxParams before proceeding

    • Wait for approval confirmation before executing the main transfer

    • Handle approval failures appropriately

  • Transaction Execution

    • Use proper gas estimation from the quote

    • Handle both direct and cross-chain transfers

    • Monitor transaction status until completion

  • User Experience

    • Show clear loading states during transactions

    • Provide feedback during approval and transfer steps

    • Handle errors gracefully with user-friendly messages

  • Security

    • Validate all transaction parameters

    • Never modify gas limits without proper estimation

    • Always wait for transaction confirmations

Complete Implementation with Error Handling and Status Monitoring:

interface TransactionStatus {
  status: 'Pending' | 'Completed' | 'Failed';
  sourceTransactionHash?: string;
  destinationTransactionHash?: string;
  sourceAmount?: string;
  destinationAmount?: string;
}

async function executeQuoteWithMonitoring(quoteResponse: QuoteResponse): Promise<TransactionStatus> {
  const provider = new ethers.BrowserProvider(window.ethereum);
  const signer = await provider.getSigner();
  
  try {
    // Handle approval if needed
    if (quoteResponse.approvalTxParams) {
      const approvalTx = await signer.sendTransaction({
        to: quoteResponse.approvalTxParams.to,
        data: quoteResponse.approvalTxParams.data,
        value: ethers.toBigInt(quoteResponse.approvalTxParams.value || '0'),
        gasLimit: ethers.toBigInt(quoteResponse.approvalTxParams.gas)
      });
      
      console.log('Waiting for approval confirmation...');
      await approvalTx.wait();
      console.log('Approval confirmed');
    }

    // Execute transfer
    const txParams = quoteResponse.type === 'Direct' 
      ? quoteResponse.transferTxParams 
      : quoteResponse.transactionRequest;

    console.log('Executing transfer...');
    const tx = await signer.sendTransaction({
      to: txParams.to,
      data: txParams.data,
      value: ethers.toBigInt(txParams.value || '0'),
      gasLimit: ethers.toBigInt(txParams.gas)
    });
    
   // Monitor transaction status
    let status: TransactionStatus = { status: 'Pending' };
    
    while (status.status === 'Pending') {
      await new Promise(resolve => setTimeout(resolve, 5000)); // Poll every 5 seconds
      const response = await fetch(
        `/v1/status?transactionId=${quoteResponse.transactionId}`,
        {
          headers: {
            'x-api-key': 'YOUR_API_KEY'
          }
        }
      );
      status = await response.json();
    }

    return status;
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes('user rejected')) {
        throw new Error('Transaction rejected by user');
      }
      if (error.message.includes('insufficient funds')) {
        throw new Error('Insufficient funds for transaction');
      }
    }
    throw error;
  }
}

Error Handling

The implementation handles common errors including:

  • User rejection

  • Insufficient funds

  • Network issues

  • Failed transactions

  • Timeout errors

Status Monitoring

The transaction status can be one of:

  • Pending Transaction is in progress

  • Completed Transaction successfully completed

  • Failed Transaction failed

Learn more about Transaction Status endpoint here.

Last updated