@thetanuts-finance/thetanuts-client

TypeScript SDK for Thetanuts Finance V4 - Options trading on EVM chains.

Table of Contents

Features

  • Complete Options Trading: Fill orders, manage positions, handle RFQs

  • Settlement Types: Cash-settled and physically settled options

  • Multi-Strategy Support: Spreads, butterflies, condors, iron condors (cash-settled)

  • Real-time Data: WebSocket subscriptions for live updates

  • Type-Safe: Full TypeScript support with comprehensive type definitions

  • Modular Design: Use only what you need

  • ESM and CJS builds: Maximum compatibility

Installation

Using npm:

Using yarn:

Quick Start

Key Concepts

Chain Configuration

Access all contract addresses and token configs from chain config (no hardcoding needed):

Decimal Handling

The SDK provides utilities for safe decimal conversions:

Type
Decimals
Example

USDC

6

1000000 = 1 USDC

WETH

18

1000000000000000000 = 1 WETH

cbBTC

8

100000000 = 1 cbBTC

Strike/Price

8

185000000000 = $1850

RFQ: collateralAmount is ALWAYS 0

When creating RFQs, the collateralAmount parameter must always be 0:

Why? Collateral is NOT locked at RFQ creation. It's pulled at settlement time from both parties. The buildRFQParams helper enforces this pattern automatically.

For SELL positions, you must separately approve tokens for the OptionFactory contract before creating the RFQ. See the RFQ Workflow Guide for complete details.

With Signer (for transactions)

Referrer (Fee Sharing)

The SDK supports a referrer address for fee sharing on order fills. When a referrer is set, a portion of the trading fees is allocated to the referrer.

If no referrer is provided, the zero address (0x000...) is used (no fee sharing).

Modules

Module
Purpose
Requires Signer

client.erc20

Token approvals, balances, transfers

Write ops only

client.optionBook

Fill/cancel orders, get fees

Write ops only

client.api

Fetch orders, positions, stats

No

client.optionFactory

RFQ lifecycle management

Write ops only

client.option

Position management, payouts

Write ops only

client.events

Query blockchain events

No

client.ws

Real-time subscriptions

No

client.pricing

Option pricing, Greeks

No

client.utils

Decimal conversions, payoffs

No

See src/modules/README.md for detailed module documentation.

Supported Chains

Chain
Chain ID
Status

Base Mainnet

8453

Supported

Configuration Options

RFQ Key Management

The SDK uses ECDH (Elliptic Curve Diffie-Hellman) key pairs for encrypted offers in the RFQ system. Keys are automatically persisted based on your environment:

Environment
Default Storage
Persistence

Node.js

FileStorageProvider

Keys saved to .thetanuts-keys/ directory

Browser

LocalStorageProvider

Keys saved to localStorage

Automatic Key Management

Custom Storage Location (Node.js)

Key Backup Warning

IMPORTANT: Back up your RFQ private keys! Keys are stored in .thetanuts-keys/ with secure permissions (0o600). If lost, you cannot decrypt offers made to your public key. There is no recovery mechanism.

Memory Storage (Testing Only)

The SDK logs a warning when using MemoryStorageProvider since keys won't persist.

Examples

Check Token Balance

Get Protocol Stats

Subscribe to Real-time Updates

Calculate Option Payoff

Common Workflows

Workflow 1: Browse and Fill an Order

Workflow 2: Create a Custom Option via RFQ

See RFQ Workflow Guide for the complete RFQ lifecycle including MM offers, reveal phase, and settlement.

Workflow 2b: Create a Butterfly RFQ

Workflow 2c: Early Settlement (Accept MM Offer Before Deadline)

Real example (RFQ 784 - PUT BUTTERFLY):

  • Structure: $1700 / $1800 / $1900 PUT BUTTERFLY

  • Offer Deadline: 04:10:34 UTC

  • MM Offer: 0.000223 USDC at 04:05:45 UTC

  • Early Settle: 04:07:09 UTC (3 min before deadline)

  • TX: 0x105f75cdfb64a3796100f6d667bc4f7fec3836d2b5aa5c43b66073a1b40964ee

Workflow 2d: Create a Condor RFQ

Real example (RFQ 785 - PUT CONDOR):

  • Structure: $1600 / $1700 / $1800 / $1900 PUT CONDOR

  • MM Offer: 0.003248 USDC

  • Early Settle: 04:15:00 UTC (4 min before deadline)

  • TX: 0xa89fb6dbad43b430399bbdec878927185e602b7df9b5390f71d2d11c33e4d850

  • Option: 0x20D51d70A51Aa529eb9460a49aAC94910A1bc267

All Option Structures Summary

Structure
Strikes
Implementation
Strike Order

Vanilla

1

PUT / INVERSE_CALL

N/A

Spread

2

PUT_SPREAD / CALL_SPREAD

PUT: desc, CALL: asc

Butterfly

3

PUT_FLY / CALL_FLY

PUT: desc, CALL: asc

Condor

4

PUT_CONDOR / CALL_CONDOR

Always ascending

Workflow 3: Monitor Positions with WebSocket

Understanding Collateral vs Contracts

When viewing orders, availableAmount represents the maker's collateral budget, not the number of contracts. The actual number of purchasable contracts depends on the option type and collateral requirements.

Collateral Formulas by Option Type

Option Type
# Strikes
Formula
Example

Vanilla PUT

1

(collateral × 1e8) / strike

10,000 USDC at $95k strike = 0.105 contracts

Inverse CALL

1

collateral / 1e12

1 WETH = 1 contract

SPREAD

2

(collateral × 1e8) / spreadWidth

10,000 USDC / $10k spread = 1 contract

BUTTERFLY

3

(collateral × 1e8) / maxSpread

Based on widest strike range

CONDOR

4

(collateral × 1e8) / maxSpread

Based on widest strike range

Using previewFillOrder

Always use previewFillOrder() to see the actual contract count before filling:

Why This Matters

For a PUT option with a $95,000 strike:

  • Maker provides: 10,000 USDC collateral

  • Max contracts: 10,000 / 95,000 ≈ 0.105 contracts (not 10,000!)

The previewFillOrder() method handles these calculations automatically for all option types.

Error Handling

All SDK methods throw ThetanutsError with typed error codes:

Error Codes

Code
Description

ORDER_EXPIRED

Order has expired or will expire soon

SLIPPAGE_EXCEEDED

Price moved beyond tolerance

INSUFFICIENT_ALLOWANCE

Token approval needed

INSUFFICIENT_BALANCE

Not enough tokens

NETWORK_UNSUPPORTED

Network not supported

HTTP_ERROR

API request failed

CONTRACT_REVERT

Smart contract call failed

INVALID_PARAMS

Invalid parameters provided

ORDER_NOT_FOUND

Order not found

SIZE_EXCEEDED

Fill size exceeds available

SIGNER_REQUIRED

Signer needed for transaction

WEBSOCKET_ERROR

WebSocket connection error

Using instanceof for Typed Error Handling

The SDK exports typed error classes for precise error handling:

Retry Pattern for Transient Errors

Production Checklist

Before deploying to production, verify the following:

  • RPC Provider: Use a reliable RPC provider instead of the public https://mainnet.base.org endpoint. Public endpoints have strict rate limits and may be unreliable under load.

  • Referrer Configuration: Set the referrer address in the client config to earn fee-sharing revenue on order fills.

  • Error Logging: Pass a custom logger to the client to capture errors in your monitoring system (Sentry, Datadog, etc.).

  • Gas Buffer: The SDK adds a 20% gas buffer for Account Abstraction wallets (Coinbase Smart Wallet, Safe). If you use a standard EOA wallet, this buffer still applies for safety.

  • Collateral Approval Flow: Always call client.erc20.ensureAllowance() before fillOrder(). The SDK does not auto-approve.

  • WebSocket Reconnection: The WebSocket module auto-reconnects by default (up to 10 attempts). Configure maxReconnectAttempts and reconnectInterval for your use case.

  • Order Expiry Checks: Always check order.expiry before filling. The SDK throws OrderExpiredError but checking upfront avoids wasted gas estimates.

Compatibility

Requirement
Minimum Version

Node.js

>= 18

ethers.js

v6

TypeScript

>= 5.0

Supported Chains

Chain
Chain ID
Network

Base Mainnet

8453

Base

Build Formats

The SDK ships as both ESM and CJS with TypeScript declarations (.d.ts), built with tsuparrow-up-right.

Custom Logger

Pass a custom logger for debugging:

Directory Structure

See src/README.md for detailed source documentation.

Development

Documentation

Detailed guides and references:

Document
Description

Quick reference for all SDK modules and methods

Complete RFQ lifecycle from request to settlement

Full API documentation with examples

Guide for upgrading from previous versions

Error codes and troubleshooting

Code Examples

Copy-paste ready examples in docs/examples/:

API Reference

License

MIT

Last updated