API Reference

Complete API documentation for the Thetanuts SDK.

Table of Contents


ThetanutsClient

The main client class for interacting with the Thetanuts protocol.

Constructor

Properties

Property
Type
Description

chainConfig

ChainConfig

Chain configuration with addresses

provider

Provider

ethers.js provider instance

signer

Signer | undefined

Signer for transactions

referrer

string | undefined

Default referrer address

Modules

Access SDK modules via the client instance:

Chain Configuration


OptionFactory Module

Manages the RFQ (Request for Quotation) lifecycle.

IMPORTANT: collateralAmount must ALWAYS be 0 in RFQ params. Collateral is pulled at settlement, not at RFQ creation.

buildRFQParams()

Build RFQ parameters with automatic address resolution and decimal handling. Enforces collateralAmount = 0. Supports multi-leg options (spreads, butterflies, condors).

Parameters:

Parameter
Type
Description

requester

string

User wallet address

underlying

'ETH' | 'BTC'

Underlying asset

optionType

'CALL' | 'PUT'

Option type

strikes

number | number[]

Strike price(s). Single for vanilla, array for multi-leg (auto-sorted ascending)

strike

number

Deprecated - use strikes instead

expiry

number

Expiry timestamp (Unix seconds)

numContracts

number | bigint | string

Number of contracts. Use bigint when closing positions to preserve exact on-chain precision. See Closing Existing Positions

isLong

boolean

true = BUY, false = SELL

offerDeadlineMinutes

number

How long MMs can respond

collateralToken

'USDC' | 'WETH' | 'cbBTC'

Collateral token

isIronCondor

boolean

Optional. Set to true to use IRON_CONDOR implementation (requires 4 strikes)

existingOptionAddress

`0x${string}`

Optional. Address of existing option when closing a position. Defaults to zero address for new positions

Strike Count to Implementation:

Strike Count
Structure
Implementation

1

Vanilla

INVERSE_CALL or PUT

2

Spread

CALL_SPREAD or PUT_SPREAD

3

Butterfly

CALL_FLY or PUT_FLY

4

Condor

CALL_CONDOR or PUT_CONDOR

4 + isIronCondor

Iron Condor

IRON_CONDOR

Returns: QuotationParameters

buildSpreadRFQ()

Convenience method for creating spreads with explicit parameter names.

Returns: RFQRequest

buildButterflyRFQ()

Convenience method for creating butterflies.

Returns: RFQRequest

buildCondorRFQ()

Convenience method for creating condors.

Returns: RFQRequest

buildIronCondorRFQ()

Convenience method for creating iron condors. An iron condor combines a put spread (lower strikes) with a call spread (upper strikes), using out-of-the-money options for better liquidity.

Iron Condor Structure:

Key Differences: Iron Condor vs Call/Put Condor

Aspect
Call/Put Condor
Iron Condor

Option types

All calls OR all puts

Puts + Calls

Implementation

CALL_CONDOR or PUT_CONDOR

IRON_CONDOR

Moneyness

Mix of ITM/OTM legs

All OTM legs

Liquidity

Lower (ITM legs)

Higher (OTM legs)

Returns: RFQRequest

Using isIronCondor with buildRFQParams()

You can also create iron condors using the generic buildRFQParams() method with the isIronCondor flag:

Parameters:

Parameter
Type
Description

isIronCondor

boolean

Set to true to use IRON_CONDOR implementation. Requires exactly 4 strikes. Default: false

Validation:

  • If isIronCondor: true and strike count ≠ 4, throws INVALID_PARAMS error

Iron Condor Cost Breakdown

For a SELL (short) position:

Item
Formula
Example (strikes 2200/2400/2600/2800)

Collateral

wing_width × numContracts

$200 × 0.001 = $0.20 USDC

Gas

~0.0003-0.001 ETH

~$0.50-1.50

Premium

You RECEIVE from buyer

Depends on MM offer

Fees

min(0.06% notional, 12.5% premium)

Paid at settlement

Collateral Formula:

Important: Collateral is NOT locked at RFQ creation - it's pulled at settlement.

Iron Condor with Early Settlement Example

Physically Settled Options

Physically settled options differ from cash-settled options in how settlement occurs:

Settlement Type
CALL Outcome (ITM)
PUT Outcome (ITM)

Cash-Settled

Pay difference in USDC

Pay difference in USDC

Physically Settled

Buyer receives underlying (WETH/cbBTC), pays strike in USDC

Buyer delivers underlying, receives strike in USDC

Key Difference: The extraOptionsData field must contain the ABI-encoded delivery token address.

Important: Physical options are vanilla-only (single strike). Multi-leg structures (spreads, butterflies, condors) are only available for cash-settled options.

Implementation
Type
Strikes
Multi-Leg?

PHYSICAL_CALL

VANILLA

1

No

PHYSICAL_PUT

VANILLA

1

No

CALL_SPREAD / PUT_SPREAD

SPREAD

2

Yes (cash only)

CALL_FLY / PUT_FLY

BUTTERFLY

3

Yes (cash only)

CALL_CONDOR / PUT_CONDOR

CONDOR

4

Yes (cash only)

IRON_CONDOR

IRON_CONDOR

4

Yes (cash only)

Buy vs Sell: Physical Options Comparison

Option
Direction
Collateral
At ITM Expiry

Physical PUT

BUY

Premium only

You deliver WETH → receive strike in USDC

Physical PUT

SELL

USDC (strike × contracts)

You receive WETH → pay strike in USDC

Physical CALL

BUY

Premium only

You pay strike in USDC → receive WETH

Physical CALL

SELL

WETH (underlying)

You receive strike in USDC → deliver WETH

Use Cases:

  • SELL Physical PUT: "I want to buy ETH at $2500. If price drops below strike, I receive ETH at my target price."

  • SELL Physical CALL: "I'm holding ETH and want to sell at $3000. If price rises above strike, I sell my ETH at my target price."

Collateral and Delivery Token Rules

Option Type
Collateral (Seller Provides)
Delivery Token
Description

PHYSICAL_CALL

BASE token (WETH for ETH, cbBTC for BTC)

USDC

Buyer pays strike in USDC at delivery

PHYSICAL_PUT

QUOTE token (USDC)

Underlying (WETH/cbBTC)

Buyer delivers underlying at settlement

Chain Config: Physical Implementations

buildPhysicalOptionRFQ()

Build an RFQ request for a physically settled option. Automatically encodes the delivery token into extraOptionsData and selects the correct implementation.

Parameters:

Parameter
Type
Required
Description

requester

0x${string}

Yes

User wallet address

underlying

'ETH' | 'BTC'

Yes

Underlying asset

optionType

'CALL' | 'PUT'

Yes

Option type

strike

number

Yes

Strike price in USD

expiry

number

Yes

Expiry timestamp (Unix seconds)

numContracts

number

Yes

Number of contracts

isLong

boolean

Yes

true = BUY, false = SELL

deliveryToken

0x${string}

Yes

Token for physical delivery

requesterPublicKey

string

Yes

ECDH public key for offer encryption

collateralToken

'USDC' | 'WETH' | 'cbBTC'

No

Auto-inferred based on optionType

offerDeadlineMinutes

number

No

How long MMs can respond (default: 6)

reservePrice

number

No

Minimum acceptable price per contract

referralId

bigint

No

Referral tracking ID

eventCode

bigint

No

Event tracking code

Collateral Auto-Inference:

If collateralToken is not provided, it is automatically inferred:

  • PHYSICAL_CALL with ETH underlying -> WETH

  • PHYSICAL_CALL with BTC underlying -> cbBTC

  • PHYSICAL_PUT -> USDC

Validation:

The method validates that:

  1. optionType is either 'CALL' or 'PUT'

  2. deliveryToken is a valid address

  3. Collateral token matches the option type (CALL requires BASE, PUT requires USDC)

Returns: RFQRequest

Physical Option RFQ Example

Physical PUT Example

extraOptionsData Encoding

For physically settled options, the extraOptionsData field contains the ABI-encoded delivery token address:

This encoding is handled automatically by buildPhysicalOptionRFQ().

Physical Multi-Leg Options

In addition to vanilla physical options, the SDK supports physical multi-leg structures:

Method
Strikes
Description

buildPhysicalSpreadRFQ()

2

Physical call/put spread

buildPhysicalButterflyRFQ()

3

Physical call/put butterfly

buildPhysicalCondorRFQ()

4

Physical call/put condor

buildPhysicalIronCondorRFQ()

4

Physical iron condor

Note: Physical multi-leg contracts are not yet deployed. The SDK is ready but will throw an error until contracts are available.

buildPhysicalSpreadRFQ()

buildPhysicalButterflyRFQ()

buildPhysicalCondorRFQ()

buildPhysicalIronCondorRFQ()

buildRFQRequest()

Build a complete RFQ request including tracking and reserve price.

Returns: RFQRequest

encodeRequestForQuotation()

Encode RFQ request for transaction submission.

Parameters:

Parameter
Type
Description

request

RFQRequest

Complete RFQ request

Returns: { to: string; data: string }

requestForQuotation()

Create an RFQ directly (requires signer).

Returns: TransactionReceipt

getQuotation()

Get quotation details by ID.

Returns: Quotation

getQuotationCount()

Get total number of quotations created.

Returns: bigint

makeOfferForQuotation()

Submit an encrypted offer for a quotation (market maker function).

revealOffer()

Reveal an offer after the offer period ends.

settleQuotation()

Settle a quotation after reveal phase.

cancelQuotation()

Cancel an unfilled quotation (requester only).

settleQuotationEarly()

Accept a specific offer before the offer period ends (requester only). Requires decrypting the offer first.

Parameters:

Parameter
Type
Description

quotationId

bigint

The RFQ ID to settle

offerAmount

bigint

Offer amount from decrypted offer

nonce

bigint

Nonce from decrypted offer

offeror

string

Address of the market maker

cancelOfferForQuotation()

Cancel your offer for a quotation (market maker only).

encodeSettleQuotation()

Encode settlement transaction for wallet integration.

encodeSettleQuotationEarly()

Encode early settlement transaction for wallet integration.

encodeCancelQuotation()

Encode cancellation transaction for wallet integration.

encodeCancelOfferForQuotation()

Encode offer cancellation transaction for wallet integration.


RFQKeyManager Module

Manages ECDH keypairs for the sealed-bid auction RFQ workflow. Handles encryption and decryption of offer details.

Access via client.rfqKeys.

getOrCreateKeyPair()

Get or create an ECDH keypair for the current chain.

Returns:

encryptOffer()

Encrypt offer details for a requester (market maker function).

decryptOffer()

Decrypt an offer (requester function). Required for early settlement.

generateNonce()

Generate a random nonce for offer encryption.

importFromPrivateKey()

Import an existing keypair from a private key.

exportPrivateKey()

Export the current keypair's private key (for backup).


Option Module

Manages option positions and queries option state.

getFullOptionInfo()

Get complete option information in a single call.

Returns:

getOptionInfo()

Get basic option information.

getBuyer() / getSeller()

Get buyer or seller address.

isExpired() / isSettled()

Check option state.

getNumContracts() / getCollateralAmount()

Get position details.

calculatePayout()

Calculate payout at a given settlement price.

close()

Close a position (requires signer).

payout()

Execute payout after expiry (requires signer).

transfer()

Transfer position to another address.

split()

Split a position into two.


MM Pricing Module

Fetches and filters market maker pricing data. MM pricing includes fee adjustments and collateral costs, typically resulting in prices 10-20% different from raw exchange prices.

Collateral APR Rates

The SDK uses these APR rates for collateral cost calculations. These values match the production mm_bot.py implementation.

Collateral
Symbol
APR
Description

Bitcoin

cbBTC

1%

Lowest rate for BTC collateral

Ethereum

WETH

4%

Medium rate for ETH collateral

US Dollar

USDC

7%

Highest rate for stablecoin collateral

Source of truth: mm_bot.py (thetanuts_rfq/scripts/mm_bot.py:789-794)

Collateral Cost Formula:

Example: For a $2000 PUT with 1-month expiry using USDC collateral:

  • Collateral Amount: $2000

  • APR: 7% (USD)

  • Time to Expiry: 1/12 year

  • Collateral Cost: $2000 × 0.07 × (1/12) = $11.67 per contract

See RFQ Workflow - Collateral Handling for more details on when collateral is required.

Spread-Level Collateral Cost (Multi-Leg Structures)

For multi-leg structures (spreads, condors, butterflies), collateral cost is calculated differently than vanilla options. Instead of summing the per-leg collateral costs, the SDK uses a spread-level calculation based on the structure's width (maximum loss).

Spread Collateral Cost Formula:

Where:

  • width = spread width in USD (difference between strikes, i.e., max loss per contract)

  • USD_APR = 7% (0.07)

  • timeToExpiryYears = time to expiry in years

Why Width-Based?

The collateral required for a spread is limited to the maximum loss (the width), not the full notional of each leg. Therefore, the collateral cost should be based on the actual capital at risk.

Example: ETH Put Spread 2200/2000

For a put spread with strikes $2200/$2000 and 11 days to expiry (T ≈ 0.03 years):

Calculation Method
Formula
Result

Correct (Width-based)

$200 × 0.07 × 0.03

$0.42

Incorrect (Sum of legs)

$2200 × 0.07 × 0.03 + $2000 × 0.07 × 0.03

$8.82

The width-based calculation correctly reflects that only $200 of capital is at risk per contract, not the full strike values.

getAllPricing()

Get all option pricing for an underlying.

Returns:

getTickerPricing()

Get pricing for a specific option ticker.

getPositionPricing()

Get position pricing with collateral cost calculation.

Filter & Sort Utilities

Spread/Condor/Butterfly Pricing

Multi-leg structures use spread-level collateral cost (see Spread-Level Collateral Cost).

MMSpreadPricing Response:

Field
Type
Description

nearLeg

MMVanillaPricing

Pricing for near strike leg

farLeg

MMVanillaPricing

Pricing for far strike leg

netSpreadPrice

number

Fee-adjusted spread price WITHOUT collateral cost (in underlying terms)

spreadCollateralCost

number

Spread-level collateral cost in USD (width × 0.07 × T)

widthUsd

number

Spread width in USD (max loss per contract)

netMmAskPrice

number

Final MM ask price (netSpreadPrice + CC in underlying terms)

netMmBidPrice

number

Final MM bid price (netSpreadPrice - CC in underlying terms)

maxLoss

number

Maximum loss per contract (same as widthUsd)

collateral

bigint

Collateral required (6 decimals for USDC)

type

string

'call_spread' or 'put_spread'

MMCondorPricing Response:

Field
Type
Description

legs

MMVanillaPricing[4]

All four leg prices

netCondorPrice

number

Fee-adjusted condor price WITHOUT collateral cost

spreadCollateralCost

number

Spread-level collateral cost in USD

netMmAskPrice

number

Final MM ask price

netMmBidPrice

number

Final MM bid price

spreadWidth

number

Width of first spread in USD

collateral

bigint

Collateral required

type

string

'call_condor', 'put_condor', or 'iron_condor'

MMButterflyPricing Response:

Field
Type
Description

legs

MMVanillaPricing[3]

All three leg prices

netButterflyPrice

number

Fee-adjusted butterfly price WITHOUT collateral cost

spreadCollateralCost

number

Spread-level collateral cost in USD

netMmAskPrice

number

Final MM ask price

netMmBidPrice

number

Final MM bid price

width

number

Wing width in USD

collateral

bigint

Collateral required

type

string

'call_butterfly' or 'put_butterfly'


Utils Module

Utility functions for decimal conversions and calculations.

toBigInt()

Convert human-readable value to bigint.

fromBigInt()

Convert bigint to human-readable string.

strikeToChain()

Convert strike price to on-chain format (8 decimals). Uses string-based parsing to avoid floating-point errors.

strikeFromChain()

Convert on-chain strike to human-readable number.

Convenience Methods

calculatePayout()

Calculate option payout.

Decimal Constants


ERC20 Module

Token operations for approvals, balances, and transfers.

approve()

Approve token spending.

encodeApprove()

Encode approval for external wallet submission.

getAllowance()

Check current allowance.

ensureAllowance()

Approve if current allowance is insufficient.

getBalance()

Get token balance.

getDecimals()

Get token decimals (cached).

transfer()

Transfer tokens (requires signer).


API Module

Fetch data from Thetanuts APIs. Methods are organized by data source:

  • Indexer API: *FromIndexer suffix

  • State/RFQ API: *FromRfq suffix

fetchOrders()

Fetch all available orders.

filterOrders()

Fetch orders with filters.

getMarketData()

Get current market prices.

getUserPositionsFromIndexer()

Get user positions from Indexer API.

getUserHistoryFromIndexer()

Get user trade history from Indexer API.

getStatsFromIndexer()

Get protocol statistics.

getUserRFQsFromRfq()

Get user RFQs from State/RFQ API.

getRFQFromRfq()

Get specific RFQ by ID.

getReferrerStatsFromIndexer()

Get referrer statistics.


Key Storage Providers

The SDK provides storage providers for persisting RFQ encryption keys across sessions.

FileStorageProvider

File-based storage for Node.js environments. This is the default for Node.js applications.

Features:

  • Keys persist to disk across process restarts

  • Directory created with 0o700 permissions (owner only)

  • Key files have 0o600 permissions (owner read/write only)

  • Atomic writes prevent corruption

  • Path traversal protection via key ID sanitization

Methods:

Method
Returns
Description

get(keyId)

Promise<string | null>

Retrieve stored key

set(keyId, privateKey)

Promise<void>

Store a key

remove(keyId)

Promise<void>

Delete a key

has(keyId)

Promise<boolean>

Check if key exists

getBasePath()

string

Get storage directory path

LocalStorageProvider

Browser localStorage-based storage. This is the default for browser environments.

Features:

  • Keys persist across browser sessions

  • Requires window.localStorage availability

  • Keys stored with chain-specific identifiers

MemoryStorageProvider

In-memory storage for testing or ephemeral use.

⚠️ Warning: Keys are lost when the process exits. Only use for testing.

Additional Methods:

Method
Description

clear()

Remove all stored keys (useful for test cleanup)

Custom Storage Provider

Implement the KeyStorageProvider interface for custom storage backends:


Data Types

Greeks

Option Greeks are included in order data from the API. Access via order.rawApiData.greeks.

Usage Example:

When Greeks are null:

  • Greeks may be unavailable for illiquid options

  • Very short-dated options near expiry

  • Options outside normal trading parameters

PositionSettlement

Settlement details for closed or settled positions.

Usage Example:

Position

User position with full details from the Indexer API.

OptionStatusType

Option lifecycle status enum.

PositionPnL

Detailed PnL entry for position tracking. Supports both cash-settled and physical-settled options.

Usage Example:

TradeHistory

Trade history entry with extended details.

Usage Example:


Type Exports

Import types for TypeScript projects:


See Also

Last updated