Error Codes Reference

This document covers all SDK error codes, common contract revert reasons, and troubleshooting guidance.

Table of Contents


Error Handling Overview

All SDK methods throw ThetanutsError or its subclasses. Use instanceof or the error code property for handling:

import {
  ThetanutsError,
  isThetanutsError,
  ContractRevertError,
  InsufficientAllowanceError,
  OrderExpiredError,
  KeyNotFoundError,
  InvalidKeyError,
  EncryptionError,
  DecryptionError,
} from '@thetanuts-finance/thetanuts-client';

try {
  await client.optionBook.fillOrder(order);
} catch (error) {
  // Option 1: Check error code
  if (isThetanutsError(error)) {
    switch (error.code) {
      case 'INSUFFICIENT_ALLOWANCE':
        console.log('Need to approve tokens first');
        break;
      case 'ORDER_EXPIRED':
        console.log('Order has expired');
        break;
    }
  }

  // Option 2: Use instanceof for typed handling
  if (error instanceof InsufficientAllowanceError) {
    await client.erc20.approve(token, spender, amount);
    // Retry...
  }

  if (error instanceof OrderExpiredError) {
    const freshOrders = await client.api.fetchOrders();
    // Retry with fresh order...
  }
}

SDK Error Codes

Code
Description
Typical Cause

ORDER_EXPIRED

Order has expired

Order's expiry timestamp has passed

SLIPPAGE_EXCEEDED

Price moved beyond tolerance

Market moved during transaction

INSUFFICIENT_ALLOWANCE

Token approval needed

Haven't approved tokens for contract

INSUFFICIENT_BALANCE

Not enough tokens

Wallet balance too low

NETWORK_UNSUPPORTED

Chain not supported

Using unsupported chain ID

HTTP_ERROR

API request failed

Network issues, API downtime

BAD_REQUEST

Invalid API request

Malformed parameters

NOT_FOUND

Resource not found

Invalid order ID, address, etc.

RATE_LIMIT

Rate limit exceeded

Too many API requests

CONTRACT_REVERT

Contract call failed

Transaction reverted on-chain

INVALID_PARAMS

Invalid parameters

Wrong types, missing required fields

INVALID_ORDER

Order validation failed

Malformed order structure

ORDER_NOT_FOUND

Order doesn't exist

Order ID not in orderbook

SIZE_EXCEEDED

Fill size too large

Requested more than available

SIGNER_REQUIRED

Signer needed

Write operation without signer

WEBSOCKET_ERROR

WebSocket error

Connection issues

KEY_NOT_FOUND

RFQ key missing

No ECDH keypair generated

INVALID_KEY

Invalid key format

Corrupted or wrong key format

ENCRYPTION_FAILED

Encryption failed

ECDH encryption error

DECRYPTION_FAILED

Decryption failed

Wrong key or corrupted data

UNKNOWN

Unknown error

Unexpected error


Error Classes

The SDK provides typed error classes for precise handling:

Base Class

API Errors

Contract Errors

Client Errors

RFQ Key Errors

Error Details:

Error Class
Code
Description

KeyNotFoundError

KEY_NOT_FOUND

No ECDH keypair found in storage for this chain

InvalidKeyError

INVALID_KEY

Key format is corrupted or incompatible

EncryptionError

ENCRYPTION_FAILED

Failed to encrypt offer with ECDH/AES-GCM

DecryptionError

DECRYPTION_FAILED

Failed to decrypt offer - wrong key or corrupted data


Contract Revert Reasons

Common smart contract revert messages and their meanings:

OptionFactory Contract

Revert Reason
Cause
Solution

InvalidImplementation

Unknown option implementation

Use valid implementation from chainConfig.implementations

InvalidCollateral

Unsupported collateral token

Use USDC, WETH, or cbBTC

InvalidExpiry

Expiry in the past or too far

Set expiry between now and reasonable future

InvalidStrikes

Strike price invalid

Ensure strikes are positive and properly scaled

OfferPeriodEnded

Offer period has ended

Cannot make offer after offerEndTimestamp

OfferPeriodNotEnded

Offer period not over

Wait for offer period to end before reveal

RevealPeriodEnded

Reveal window closed

Reveal within the reveal window

NoOffersToReveal

No offers submitted

At least one MM offer required

QuotationAlreadySettled

Already settled

Cannot settle twice

NotRequester

Wrong caller

Only requester can cancel their RFQ

InvalidSignature

Bad offer signature

Check EIP-712 signature

OptionBook Contract

Revert Reason
Cause
Solution

OrderExpired

Order has expired

Fetch fresh orders

OrderCancelled

Order was cancelled

Use a different order

InsufficientSize

Not enough to fill

Reduce fill amount

InvalidOrder

Malformed order

Check order structure

SignatureInvalid

Bad order signature

Order signature doesn't match

ERC20 Errors

Revert Reason
Cause
Solution

ERC20: insufficient allowance

Not approved

Call approve() first

ERC20: transfer amount exceeds balance

Not enough tokens

Check balance before transaction

ERC20: approve to the zero address

Invalid spender

Use valid spender address

Option Contract

Revert Reason
Cause
Solution

NotExpired

Option not expired yet

Wait for expiry before payout

AlreadySettled

Already settled

Cannot payout twice

NotBuyer

Caller is not buyer

Only buyer can execute payout

NotBuyerOrSeller

Wrong caller

Only buyer/seller can close

TransferNotApproved

Transfer not approved

Call approveTransfer() first


Common Issues & Solutions

Issue 1: INSUFFICIENT_ALLOWANCE

Symptom: Transaction fails with "insufficient allowance" error

Cause: Haven't approved tokens for the contract

Solution:

Issue 2: ORDER_EXPIRED

Symptom: "Order has expired" error

Cause: Order's expiry timestamp has passed

Solution:

Issue 3: SIGNER_REQUIRED

Symptom: "Signer is required for this operation"

Cause: Attempting write operation without signer

Solution:

Issue 4: RFQ collateralAmount Error

Symptom: RFQ fails or behaves unexpectedly

Cause: Setting collateralAmount to non-zero value

Solution:

Issue 5: Strike Precision Errors

Symptom: Incorrect strike prices, transactions failing

Cause: Floating-point precision issues

Solution:

Issue 6: Rate Limiting

Symptom: HTTP 429 errors

Cause: Too many API requests

Solution:

Issue 7: WebSocket Disconnection

Symptom: Real-time updates stop

Cause: Network issues, server restart

Solution:

Issue 8: KEY_NOT_FOUND Error

Symptom: KeyNotFoundError: No RFQ key found in storage

Cause: No ECDH keypair has been generated, or keys were lost (using MemoryStorageProvider)

Solution:

Prevention:

  • Use FileStorageProvider in Node.js (default)

  • Use LocalStorageProvider in browsers (default)

  • Back up the .thetanuts-keys/ directory for critical applications

Issue 9: DECRYPTION_FAILED Error

Symptom: DecryptionError: Failed to decrypt offer data

Cause: Key mismatch between RFQ creation and decryption, or corrupted data

Solution:

Troubleshooting Checklist:

  1. ✅ Is the keypair the same one used when creating the RFQ?

  2. ✅ Was the keypair backed up before process restart?

  3. ✅ Does client.rfqKeys.compressedPublicKey match rfq.requesterPublicKey?

  4. ✅ Is the signingKey from the correct offer?

  5. ✅ Is the signedOfferForRequester data complete (not truncated)?

Issue 10: INVALID_KEY Error

Symptom: InvalidKeyError: Invalid key format

Cause: Corrupted key, wrong format, or incompatible key type

Solution:

Key Format Requirements:

  • Private key: 32 bytes, hex string with 0x prefix

  • Compressed public key: 33 bytes, hex string with 0x prefix (starts with 02 or 03)

  • Uncompressed public key: 65 bytes, hex string with 0x prefix (starts with 04)

Issue 11: ENCRYPTION_FAILED Error

Symptom: EncryptionError: Failed to encrypt offer data

Cause: Invalid requester public key or ECDH computation failure

Solution:


Debugging Tips

1. Enable Debug Logging

2. Inspect Error Details

3. Verify Contract State

4. Verify Token State

5. Use callStatic for Simulation

6. Check Gas Estimation


See Also

Last updated