Error Handling

The SDK provides typed errors for robust error handling.

Error Types

import {
  OpenClawWalletError,
  ConfigurationError,
  AuthenticationError,
  RateLimitError,
  ValidationError,
  NetworkError,
  InsufficientFundsError,
} from '@loomlay/openclaw-wallet-sdk';

Basic Error Handling

try {
  await wallet.trading.swap({
    inputToken: 'SOL',
    outputToken: 'USDC',
    amount: '100',
  });
} catch (error) {
  if (error instanceof InsufficientFundsError) {
    console.log('Not enough SOL:', error.message);
    console.log('Required:', error.required);
    console.log('Available:', error.available);
  } else if (error instanceof RateLimitError) {
    console.log('Rate limited. Retry after:', error.retryAfter, 'seconds');
  } else if (error instanceof ValidationError) {
    console.log('Invalid input:', error.field, error.message);
  } else {
    throw error;
  }
}

Error Properties

All errors extend OpenClawWalletError:

interface OpenClawWalletError extends Error {
  code: string;        // Machine-readable error code
  statusCode?: number; // HTTP status if applicable
  details?: unknown;   // Additional error details
}

Specific Error Types

// Configuration issues
class ConfigurationError extends OpenClawWalletError {
  code: 'CONFIGURATION_ERROR';
}
 
// Auth failures
class AuthenticationError extends OpenClawWalletError {
  code: 'UNAUTHORIZED' | 'INVALID_API_KEY';
}
 
// Rate limiting
class RateLimitError extends OpenClawWalletError {
  code: 'RATE_LIMITED';
  retryAfter: number; // Seconds until retry allowed
}
 
// Input validation
class ValidationError extends OpenClawWalletError {
  code: 'VALIDATION_ERROR';
  field: string;
}
 
// Network issues
class NetworkError extends OpenClawWalletError {
  code: 'NETWORK_ERROR' | 'TIMEOUT';
}
 
// Insufficient balance
class InsufficientFundsError extends OpenClawWalletError {
  code: 'INSUFFICIENT_FUNDS';
  required: string;
  available: string;
  token: string;
}
 
// Transaction failed
class TransactionError extends OpenClawWalletError {
  code: 'TRANSACTION_FAILED' | 'TRANSACTION_TIMEOUT';
  txHash?: string;
}
 
// Token launch errors
class TokenizeError extends OpenClawWalletError {
  code: 'ALREADY_LAUNCHED' | 'SYMBOL_TAKEN' | 'INVALID_IMAGE';
}

Error Code Reference

Error CodeHTTP StatusError ClassDescription
CONFIGURATION_ERROR-ConfigurationErrorSDK misconfigured (missing API key, invalid options)
UNAUTHORIZED401AuthenticationErrorMissing or invalid API key
INVALID_API_KEY401AuthenticationErrorAPI key format is invalid
RATE_LIMITED429RateLimitErrorToo many requests, retry after retryAfter seconds
VALIDATION_ERROR400ValidationErrorInvalid input parameters
NETWORK_ERROR-NetworkErrorConnection failed or request timed out
TIMEOUT-NetworkErrorRequest exceeded timeout limit
INSUFFICIENT_FUNDS400InsufficientFundsErrorNot enough balance for operation
TRANSACTION_FAILED500TransactionErrorOn-chain transaction failed
TRANSACTION_TIMEOUT500TransactionErrorTransaction confirmation timed out
ALREADY_LAUNCHED400TokenizeErrorAccount already launched a token
SYMBOL_TAKEN400TokenizeErrorToken symbol already exists
INVALID_IMAGE400TokenizeErrorImage URL invalid or inaccessible
WALLET_NOT_FOUND404OpenClawWalletErrorNo wallet exists for this account
TOKEN_NOT_FOUND404OpenClawWalletErrorToken address or symbol not found
SLIPPAGE_EXCEEDED400OpenClawWalletErrorPrice moved beyond slippage tolerance

Retry Logic

The SDK has built-in retry for transient failures:

const wallet = new OpenClawWallet({
  apiKey: 'agent_xxx',
  maxRetries: 3,     // Retry up to 3 times
  retryDelay: 1000,  // Start with 1s delay
});

Custom Retry

async function swapWithRetry(params: SwapParams, maxAttempts = 3) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await wallet.trading.swap(params);
    } catch (error) {
      if (error instanceof RateLimitError) {
        if (attempt < maxAttempts) {
          await sleep(error.retryAfter * 1000);
          continue;
        }
      }
      throw error;
    }
  }
}

Retry Strategy by Error Type

Error TypeRetry?Strategy
RateLimitErrorYesWait for retryAfter seconds, then retry
NetworkErrorYesExponential backoff (1s, 2s, 4s), max 3 attempts
TransactionError (TIMEOUT)MaybeCheck transaction status first, retry if not confirmed
TransactionError (FAILED)NoTransaction was rejected, fix params and retry
InsufficientFundsErrorNoAdd funds before retrying
ValidationErrorNoFix input parameters before retrying
AuthenticationErrorNoCheck API key, do not retry
ConfigurationErrorNoFix SDK configuration, do not retry
TokenizeErrorNoAddress the specific issue (symbol, image, etc.)
SLIPPAGE_EXCEEDEDYesIncrease slippage or retry with fresh quote

Pro Tip: For SLIPPAGE_EXCEEDED errors, fetch a fresh quote with quoteOnly: true before retrying. Market conditions may have changed significantly.

WebSocket Errors

const dexWs = wallet.createDexWebSocket();
 
dexWs.on('error', (error) => {
  if (error instanceof AuthenticationError) {
    console.log('Invalid API key');
  } else if (error instanceof NetworkError) {
    console.log('Connection lost');
  }
});

Logging

Enable debug logging:

import { setLogLevel } from '@loomlay/openclaw-wallet-sdk';
 
setLogLevel('debug'); // 'debug' | 'info' | 'warn' | 'error' | 'none'