Skip to main content
The Nexus SDK provides structured error handling through the NexusError class. All errors include a specific error code, message, and optional contextual data.

Error Structure

class NexusError extends Error {
  readonly code: ErrorCode;
  readonly data?: {
    context?: string;              // Where or why it happened
    cause?: unknown;               // Nested error
    details?: Record<string, unknown>; // Additional structured info
  };
}

Error Handling Example

import { NexusError, ERROR_CODES } from '@avail-project/nexus-core';

try {
  await sdk.bridge({ token: 'USDC', amount: 1_000_000n, toChainId: 137 });
} catch (error) {
  if (error instanceof NexusError) {
    console.error(`Error Code: ${error.code}`);
    console.error(`Message: ${error.message}`);
    console.error(`Context: ${error.data?.context}`);
    
    // Handle specific errors
    switch (error.code) {
      case ERROR_CODES.INSUFFICIENT_BALANCE:
        showInsufficientBalanceUI();
        break;
      case ERROR_CODES.USER_DENIED_INTENT:
        // User cancelled - not an error to display
        break;
      default:
        showGenericError(error.message);
    }
  }
}

Error Categories

User Actions

Errors triggered by user decisions or cancellations.
Description: User rejected the intent in the intent hook.When it occurs: When deny() is called in setOnIntentHook()User action: None - user intentionally cancelled the operationExample:
sdk.setOnIntentHook(({ allow, deny }) => {
  if (!userConfirms()) {
    deny(); // Throws USER_DENIED_INTENT
  }
});
Description: User rejected the token approval request.When it occurs: When deny() is called in setOnAllowanceHook()User action: None - user intentionally cancelledExample:
sdk.setOnAllowanceHook(({ allow, deny }) => {
  if (!userApproves()) {
    deny(); // Throws USER_DENIED_ALLOWANCE
  }
});
Description: User rejected the signature request for the intent.When it occurs: When user declines to sign in their walletUser action: None - user cancelled signatureRecovery: User can retry the operation
Description: User rejected the Sign-In with Ethereum (SIWE) signature.When it occurs: During initial authenticationUser action: None - user cancelled authenticationRecovery: Retry authentication when ready

Balance & Funds

Errors related to insufficient balances or fund availability.
Description: Not enough tokens available for the operation.When it occurs: When attempting to bridge or transfer more than available balanceUser action:
  • Check available balance with getBalancesForBridge()
  • Deposit more funds
  • Reduce the amount
Example:
// Check max before bridging
const max = await sdk.calculateMaxForBridge({
  token: 'USDC',
  toChainId: 137,
});
console.log(`Max available: ${max.amount} USDC`);
Description: No balance found for the specified address.When it occurs: When querying balances for an address with no tokensUser action: Verify the address is correct and has been fundedRecovery: Fund the address or check a different address

Validation Errors

Errors from invalid input parameters or configuration.
Description: Invalid parameters provided to SDK method.When it occurs: When parameters don’t meet validation requirementsUser action: Check parameter types and valuesCommon causes:
  • Negative amounts
  • Invalid chain IDs
  • Malformed addresses
Description: Address has incorrect length (not 42 characters for Ethereum addresses).When it occurs: When providing malformed Ethereum addressesUser action: Verify address format (should start with 0x and be 42 characters)Example: 0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45 (correct)
Description: Invalid values passed to allow() in allowance hook.When it occurs: When allowance hook receives invalid approval amountsUser action: Use valid values: 'min', 'max', or a bigint amountExample:
sdk.setOnAllowanceHook(({ allow }) => {
  allow(['min']); // ✅ Correct
  allow(['invalid']); // ❌ Throws INVALID_VALUES_ALLOWANCE_HOOK
});
Description: The specified token is not supported by the SDK.When it occurs: When requesting operations with unsupported tokensUser action: Use supported tokens (ETH, USDC, USDT, USDM)Recovery: Check Supported Tokens reference

Initialization Errors

Errors related to SDK initialization and setup.
Description: SDK method called before initialization.When it occurs: When calling SDK methods before initialize() completesUser action: Call initialize() before using SDK methodsExample:
const sdk = new NexusSDK({ network: 'mainnet' });
await sdk.initialize(window.ethereum); // Required!
await sdk.getBalancesForBridge(); // Now safe to call
Description: SDK in unexpected initialization state.When it occurs: Internal state management errorUser action: Re-initialize the SDKRecovery: Create a new SDK instance
Description: No wallet connected to the SDK.When it occurs: When provider is not set or wallet not connectedUser action: Connect wallet before SDK operationsExample:
await sdk.initialize(window.ethereum);
Description: Failed to connect to wallet account.When it occurs: When wallet connection failsUser action:
  • Check wallet is unlocked
  • Grant connection permission
  • Retry connection

Chain & Network Errors

Errors related to blockchain networks and configuration.
Description: Specified chain ID not found in supported chains.When it occurs: When using unsupported chain IDsUser action: Use supported chain IDsRecovery: Check Supported Networks reference
Description: Chain data unavailable (RPC or configuration issue).When it occurs: Network connectivity issues or chain configuration errorsUser action:
  • Check internet connection
  • Verify RPC endpoints are accessible
  • Retry after a moment
Description: Vault contract not found for the specified chain.When it occurs: Internal configuration errorUser action: Contact support - this indicates a configuration issue
Description: Specified environment is not supported.When it occurs: When using invalid network configurationUser action: Use 'mainnet' or 'testnet' for network parameter
Description: Unknown environment configuration.When it occurs: Internal configuration errorUser action: Verify SDK initialization parameters
Description: Blockchain universe not supported (e.g., non-EVM chains).When it occurs: When attempting unsupported blockchain typesUser action: SDK currently supports EVM-compatible chains only

Transaction Errors

Errors during transaction execution.
Description: Transaction did not confirm within timeout period.When it occurs: When transaction takes too long to mineUser action:
  • Check transaction on block explorer
  • Retry with higher gas price
  • Wait for network congestion to clear
Recovery: Transaction may still succeed - verify on explorer
Description: Transaction reverted on-chain.When it occurs: Smart contract execution failedUser action:
  • Verify contract parameters
  • Check token allowances
  • Review transaction data
Common causes: Insufficient allowance, slippage, contract conditions not met
Description: Error checking transaction status.When it occurs: RPC or network issues when querying transactionUser action: Retry the status checkRecovery: Check transaction manually on block explorer
Description: Failed to fetch current gas price.When it occurs: RPC error when querying gas pricesUser action:
  • Check network connection
  • Retry operation
  • Specify gas price manually if supported

Operation Errors

Errors during specific SDK operations.
Description: Transaction simulation failed.When it occurs: When simulate*() methods encounter errorsUser action:
  • Verify parameters are correct
  • Check sufficient balance including gas
  • Review token approvals
Description: Failed to get swap quote.When it occurs: Swap quote request failedUser action:
  • Retry request
  • Check token pair is supported
  • Verify amounts are within limits
Description: Swap operation failed.When it occurs: During swap executionUser action:
  • Check error details in error.data
  • Verify token balances
  • Retry operation
Description: Refund request failed.When it occurs: When refundIntent() failsUser action: Contact support with intent ID and error details
Description: Error checking refund status.When it occurs: Network error when querying refundUser action: Retry status check

Intent & Solver Errors

Errors related to intent processing and solver network.
Description: Solver liquidity timeout - no solver accepted the intent.When it occurs: When no solver can fulfill the intent within timeoutUser action:
  • Retry after a few minutes
  • Reduce transfer amount
  • Try different source chains
Note: This may indicate temporary liquidity constraints
Description: Token price moved too much since quote.When it occurs: Significant price movement during operationUser action:
  • Refresh intent/quote
  • Retry operation
  • Accept new rates
Description: Request for funds (RFF) fee quote expired.When it occurs: Quote expired before executionUser action: Retry operation to get fresh quote
Description: Destination request hash not found.When it occurs: Internal tracking errorUser action: Contact support with operation details
Description: Error sweeping funds on destination chain.When it occurs: Final fund collection failedUser action: Contact support - funds may need manual recovery

Allowance Errors

Errors related to token approvals and allowances.
Description: Slippage exceeded during allowance check.When it occurs: Price moved beyond acceptable slippageUser action:
  • Increase allowance amount
  • Approve with 'max' instead of 'min'
  • Retry operation
Example:
sdk.setOnAllowanceHook(({ allow }) => {
  allow(['max']); // Approve unlimited to avoid slippage issues
});
Description: Error setting token allowance.When it occurs: Approval transaction failedUser action:
  • Retry approval
  • Check gas balance
  • Verify wallet connection

Other Errors

Description: Internal SDK error.When it occurs: Unexpected internal stateUser action:
  • Report to support with full error details
  • Include error.data and error.stack
  • Provide reproduction steps
Description: Unknown signature type encountered.When it occurs: Unexpected signature formatUser action: Contact support - this indicates an integration issue
Description: Requested asset not found in configuration.When it occurs: When querying unsupported assetUser action: Verify asset/token symbol or address
Description: Cosmos chain-specific error.When it occurs: Operations involving Cosmos chainsUser action: Check Cosmos configuration and network status
Description: Fee grant was requested (Cosmos chains).When it occurs: Fee grant mechanism triggeredUser action: Contact support for fee grant setup

Complete Error Codes List

export const ERROR_CODES = {
  // User Actions
  USER_DENIED_INTENT: 'USER_DENIED_INTENT',
  USER_DENIED_ALLOWANCE: 'USER_DENIED_ALLOWANCE',
  USER_DENIED_INTENT_SIGNATURE: 'USER_DENIED_INTENT_SIGNATURE',
  USER_DENIED_SIWE_SIGNATURE: 'USER_DENIED_SIWE_SIGNATURE',
  
  // Balance & Funds
  INSUFFICIENT_BALANCE: 'INSUFFICIENT_BALANCE',
  NO_BALANCE_FOR_ADDRESS: 'NO_BALANCE_FOR_ADDRESS',
  
  // Validation
  INVALID_INPUT: 'INVALID_INPUT',
  INVALID_ADDRESS_LENGTH: 'INVALID_ADDRESS_LENGTH',
  INVALID_VALUES_ALLOWANCE_HOOK: 'INVALID_VALUES_ALLOWANCE_HOOK',
  TOKEN_NOT_SUPPORTED: 'TOKEN_NOT_SUPPORTED',
  
  // Initialization
  SDK_NOT_INITIALIZED: 'SDK_NOT_INITIALIZED',
  SDK_INIT_STATE_NOT_EXPECTED: 'SDK_INIT_STATE_NOT_EXPECTED',
  WALLET_NOT_CONNECTED: 'WALLET_NOT_CONNECTED',
  CONNECT_ACCOUNT_FAILED: 'CONNECT_ACCOUNT_FAILED',
  
  // Chain & Network
  CHAIN_NOT_FOUND: 'CHAIN_NOT_FOUND',
  CHAIN_DATA_NOT_FOUND: 'CHAIN_DATA_NOT_FOUND',
  VAULT_CONTRACT_NOT_FOUND: 'VAULT_CONTRACT_NOT_FOUND',
  ENVIRONMENT_NOT_SUPPORTED: 'ENVIRONMENT_NOT_SUPPORTED',
  ENVIRONMENT_NOT_KNOWN: 'ENVIRONMENT_NOT_KNOWN',
  UNIVERSE_NOT_SUPPORTED: 'UNIVERSE_NOT_SUPPORTED',
  
  // Transactions
  TRANSACTION_TIMEOUT: 'TRANSACTION_TIMEOUT',
  TRANSACTION_REVERTED: 'TRANSACTION_REVERTED',
  TRANSACTION_CHECK_ERROR: 'TRANSACTION_CHECK_ERROR',
  FETCH_GAS_PRICE_FAILED: 'FETCH_GAS_PRICE_FAILED',
  
  // Operations
  SIMULATION_FAILED: 'SIMULATION_FAILED',
  QUOTE_FAILED: 'QUOTE_FAILED',
  SWAP_FAILED: 'SWAP_FAILED',
  REFUND_FAILED: 'REFUND_FAILED',
  REFUND_CHECK_ERROR: 'REFUND_CHECK_ERROR',
  
  // Intent & Solver
  LIQUIDITY_TIMEOUT: 'LIQUIDITY_TIMEOUT',
  RATES_CHANGED_BEYOND_TOLERANCE: 'RATES_CHANGED_BEYOND_TOLERANCE',
  RFF_FEE_EXPIRED: 'RFF_FEE_EXPIRED',
  DESTINATION_REQUEST_HASH_NOT_FOUND: 'DESTINATION_REQUEST_HASH_NOT_FOUND',
  DESTINATION_SWEEP_ERROR: 'DESTINATION_SWEEP_ERROR',
  
  // Allowance
  SLIPPAGE_EXCEEDED_ALLOWANCE: 'SLIPPAGE_EXCEEDED_ALLOWANCE',
  ALLOWANCE_SETTING_ERROR: 'ALLOWANCE_SETTING_ERROR',
  
  // Other
  INTERNAL_ERROR: 'INTERNAL_ERROR',
  UNKNOWN_SIGNATURE: 'UNKNOWN_SIGNATURE',
  ASSET_NOT_FOUND: 'ASSET_NOT_FOUND',
  COSMOS_ERROR: 'COSMOS_ERROR',
} as const;

Best Practices

  1. Always check error types:
    if (error instanceof NexusError) {
      // Handle NexusError
    } else {
      // Handle unexpected errors
    }
    
  2. Log error details for debugging:
    console.error('NexusError:', error.toJSON());
    
  3. Handle user cancellations gracefully:
    if (error.code === ERROR_CODES.USER_DENIED_INTENT) {
      // Don't show error - user intentionally cancelled
      return;
    }
    
  4. Provide contextual recovery actions:
    switch (error.code) {
      case ERROR_CODES.INSUFFICIENT_BALANCE:
        showDepositUI();
        break;
      case ERROR_CODES.TRANSACTION_TIMEOUT:
        showTransactionStatusChecker(txHash);
        break;
    }
    

Build docs developers (and LLMs) love