WDK logoWDK documentation

Handle Errors

Handle errors, manage fees, and dispose of sensitive data in Tron wallets.

This guide covers how to handle transaction errors and handle token transfer errors, plus best practices for fee management and memory cleanup.

Handle Transaction Errors

Wrap transactions in try/catch blocks to handle common failure scenarios. Use account.sendTransaction() with proper error handling:

Transaction Error Handling
try {
  const tx = {
    to: 'TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH',
    value: 1000000 // 1 TRX in sun
  }

  const quote = await account.quoteSendTransaction(tx)
  if (quote.fee > 10000000n) {
    throw new Error('Transaction fee exceeds configured threshold')
  }

  const result = await account.sendTransaction(tx)
  console.log('Transaction hash:', result.hash)
  console.log('Fee paid:', result.fee, 'sun')
  console.log('Activation fee:', result.activationFee, 'sun')
} catch (error) {
  if (error.message.toLowerCase().includes('insufficient')) {
    console.error('Not enough TRX to complete transaction')
  } else if (error.message.toLowerCase().includes('configured threshold')) {
    console.error('The transaction fee exceeds your configured threshold')
  } else {
    console.error('Transaction failed:', error.message)
  }
}

Handle Token Transfer Errors

TRC20 transfers can fail for additional reasons such as insufficient token balances. Use account.transfer() with error handling:

Token Transfer Error Handling
try {
  const result = await account.transfer({
    token: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', // USDT
    recipient: 'TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH',
    amount: 1000000
  })
  console.log('Transfer successful:', result.hash)
  console.log('Fee paid (sun):', result.fee)
} catch (error) {
  console.error('Transfer failed:', error.message)
  if (error.message.toLowerCase().includes('insufficient')) {
    console.log('Please add more TRC20 tokens to your wallet')
  } else if (error.message.toLowerCase().includes('max fee')) {
    console.log('The transfer fee exceeds your configured maximum')
  }
}

Best Practices

Manage Fee Limits

Set transferMaxFee when creating the wallet to prevent TRC20 transfers from exceeding a maximum cost. For native TRX sends, call account.quoteSendTransaction() and compare quote.fee before calling sendTransaction().

You can retrieve current network rates using wallet.getFeeRates():

Fee Management
const feeRates = await wallet.getFeeRates()
console.log('Normal fee rate:', feeRates.normal, 'sun')
console.log('Fast fee rate:', feeRates.fast, 'sun')

Dispose of Sensitive Data

Call dispose() on accounts and wallet managers to clear private keys and sensitive data from memory when they are no longer needed:

Memory Cleanup
account.dispose()

wallet.dispose()

Always call dispose() in a finally block or cleanup handler to ensure sensitive data is cleared even if an error occurs.

On this page