Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@
* [Filters & Utilities](pricing/filters-utilities.md)
* [Collateral Cost Reference](pricing/collateral-cost.md)

## AI Agents

* [Overview — Pick Your Route](guides/agents-overview.md)
* [MCP Server](guides/mcp-server.md)
* [Trade from Chat (Base MCP Plugin)](guides/base-mcp-plugin.md)
* [AgentKit (Autonomous Agents)](guides/agentkit.md)

## Guides

* [Position Management](guides/position-management.md)
Expand All @@ -61,7 +68,6 @@
* [Blockchain Events](guides/events.md)
* [Error Handling](guides/error-handling.md)
* [Production Checklist](guides/production-checklist.md)
* [MCP Server](guides/mcp-server.md)

## SDK Reference

Expand Down
2 changes: 1 addition & 1 deletion docs/getting-started/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

TypeScript SDK for Thetanuts Finance V4 — options trading on EVM chains.

> **Using an LLM (Claude, Cursor, ChatGPT)?** This SDK ships an MCP server that exposes ~100 tools — read state, build transactions, run pricing math. One-line install: `npx -y @thetanuts-finance/mcp`, or paste [the LLM context prompt](../resources/llm-context.md) into your LLM. See the [MCP Server guide](../guides/mcp-server.md) for details.
> **Using an LLM (Claude, Cursor, ChatGPT)?** This SDK ships an MCP server that exposes ~100 tools — read state, build transactions, run pricing math. One-line install: `npx -y @thetanuts-finance/mcp`, or paste [the LLM context prompt](../resources/llm-context.md) into your LLM. Want to actually **trade** from chat? Pair it with Base MCP and approve each transaction in your wallet ([Trade from Chat](../guides/base-mcp-plugin.md)), or run a fully autonomous agent with its own wallet ([AgentKit](../guides/agentkit.md)). Start at [AI Agents — Pick Your Route](../guides/agents-overview.md).

## Features

Expand Down
53 changes: 53 additions & 0 deletions docs/guides/agentkit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# AgentKit — Autonomous Agents

[`@thetanuts-finance/agentkit`](https://www.npmjs.com/package/@thetanuts-finance/agentkit) is a [Coinbase AgentKit](https://docs.cdp.coinbase.com/agent-kit/welcome) `ActionProvider` for agents that **own their own wallet** and trade Thetanuts options unattended — request RFQs, receive encrypted sealed-bid offers, and settle, with no human approval per transaction.

It lives in a sibling repo: [`Thetanuts-Finance/thetanuts-agentkit`](https://github.com/Thetanuts-Finance/thetanuts-agentkit). This page is the orientation; the repo's [SETUP.md](https://github.com/Thetanuts-Finance/thetanuts-agentkit/blob/main/SETUP.md) is the step-by-step guide.

> **This is the autonomous route.** The agent's wallet signs by itself — the configured `SafetyPolicy` caps are the only brake. If you want to approve each trade in your own wallet, use the [Base MCP plugin](base-mcp-plugin.md) instead. See [Pick Your Route](agents-overview.md).

## Action surface

7 write actions + 3 read actions, each Zod-validated with LLM-friendly descriptions:

| Action | Purpose |
|---|---|
| `approve` | ERC20 approval to the OptionFactory (auto-bundled for SELL RFQs) |
| `request_rfq` | Open an RFQ — puts, calls, spreads, butterflies, condors, iron condors |
| `make_offer` | Sealed-bid offer on someone's RFQ (EIP-712 signed, encrypted to the requester) |
| `settle_rfq` / `settle_rfq_early` | Settle after the window closes / accept a specific offer early |
| `cancel_rfq` / `cancel_offer` | Withdraw the agent's own RFQ / offer |
| `get_user_positions`, `get_rfq`, `get_market_prices` | Reads |

## The safety model

Every value-moving action passes a **fail-closed `SafetyPolicy`** — omit it and all writes throw `SAFETY_LIMITS_REQUIRED`:

```typescript
thetanutsActionProvider({
safetyLimits: {
maxNotionalUsdcPerAction: 50_000_000n, // $50 hard cap per action
maxApprovalAmount: 'exact', // never grant MAX_UINT256
allowedCollateral: ['USDC'],
// onWriteAction: (ctx) => 'allow' | 'reject' — host audit/review hook
},
})
```

Run it only with a **dedicated wallet** funded with what you're prepared to let an agent spend. The recommended wallet is a CDP server wallet (MPC — the agent never sees key material); viem and Privy providers also work.

## Two ways to consume it

**Embedded in your own bot** — LangChain or Vercel AI SDK, via Coinbase's framework adapters. Runnable quickstarts: [`examples/`](https://github.com/Thetanuts-Finance/thetanuts-agentkit/tree/main/examples) in the agentkit repo, plus a complete [covered-call premium hunter](https://github.com/Thetanuts-Finance/thetanuts-sdk/tree/main/examples/options-trading-agent) in this repo.

**As an autonomous-signing MCP server** — Coinbase's official [`@coinbase/agentkit-model-context-protocol`](https://docs.cdp.coinbase.com/agent-kit/core-concepts/model-context-protocol) adapter turns the ActionProvider into a stdio MCP server, so a chat client (Claude Desktop, Claude Code, Cursor, Codex) gets tools that sign on their own. Runnable server: [`examples/mcp-server-quickstart.ts`](https://github.com/Thetanuts-Finance/thetanuts-agentkit/blob/main/examples/mcp-server-quickstart.ts); client configs for all four clients are in [SETUP.md](https://github.com/Thetanuts-Finance/thetanuts-agentkit/blob/main/SETUP.md). This is deliberately a **separate server** from `@thetanuts-finance/mcp`, which never signs — the two can be installed side by side.

## Walkthrough skill

The repo ships a [SKILL.md](https://github.com/Thetanuts-Finance/thetanuts-agentkit/blob/main/SKILL.md) (`npx skills add Thetanuts-Finance/thetanuts-agentkit`, also inside the npm package) that teaches any skill-aware agent to walk a user through the kit — detection, setup, funding, a read-only demo, and a safe first trade.

## Requirements

- `@thetanuts-finance/thetanuts-client` **>= 0.3.0** — `make_offer` / `settle_rfq_early` use the `buildOfferTypedData`, `getRequesterPublicKey`, and `getOffer` APIs introduced in 0.3.0
- `@coinbase/agentkit` >= 0.10.0, `reflect-metadata`
- Base mainnet only (chainId 8453) — the provider rejects any other network
36 changes: 36 additions & 0 deletions docs/guides/agents-overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# AI Agents — Pick Your Route

Thetanuts ships two agent-facing packages on top of the SDK. Both are thin layers over the same [`@thetanuts-finance/thetanuts-client`](https://www.npmjs.com/package/@thetanuts-finance/thetanuts-client) encode helpers — the difference is **who signs the transaction and where the safety boundary lives**.

## The two packages

| | [`@thetanuts-finance/mcp`](https://www.npmjs.com/package/@thetanuts-finance/mcp) | [`@thetanuts-finance/agentkit`](https://www.npmjs.com/package/@thetanuts-finance/agentkit) |
|---|---|---|
| What it is | MCP server: ~100 tools an LLM client calls over the Model Context Protocol | Coinbase AgentKit `ActionProvider` library you embed in your own agent code |
| Who signs | **Never signs.** Pairs with a signer — Base MCP (you approve each tx in Base Account), Safe, or a CDP policy wallet | **The agent's own wallet** (CDP, viem, Privy server wallets), unattended |
| Runs in | Claude Desktop, Claude Code, Cursor, ChatGPT, Codex — any MCP client | Your backend agent process (LangChain, Vercel AI SDK), or as its own MCP server |
| Safety boundary | Outside the LLM: wallet approval UI or signer policy | In code: fail-closed `SafetyPolicy` (notional caps, collateral allowlist, host hook) |
| Use when | Human-in-the-loop chat trading; maximum client reach | Headless trading bots, MM bots, custodied agent vaults |

This split is deliberate: the MCP server can guarantee it **cannot move funds** (it holds no keys and builds calldata only), while autonomous signing stays an explicit, separately-installed opt-in. The two can run side by side.

## The three routes

| You want | You run | Guide |
|---|---|---|
| **Trade from chat, approving every transaction yourself** | `@thetanuts-finance/mcp` + [Base MCP](https://docs.base.org/ai-agents/quickstart) — calldata is prepared, you click approve in Base Account | [Trade from Chat](base-mcp-plugin.md) |
| **Trade from chat, but the agent signs by itself** | `@thetanuts-finance/agentkit` run as an MCP server (Coinbase's MCP adapter + a CDP wallet under `SafetyPolicy` caps) | [AgentKit](agentkit.md) |
| **A fully headless bot — no chat client at all** | `@thetanuts-finance/agentkit` embedded in your own code (LangChain, Vercel AI SDK) | [AgentKit](agentkit.md) |

If you're unsure, take the first route — a transaction can never leave your wallet without your click.

## Reads only?

If you just want an LLM that can *read* the protocol (markets, positions, IV, Greeks) and help you write SDK code, the MCP server alone is enough — no wallet, no signer. See [MCP Server](mcp-server.md), or skip servers entirely with the copy-paste [LLM Context](../resources/llm-context.md) prompt.

## Deeper material

- [MCP Server guide](mcp-server.md) — every tool, environment variables, the full comparison
- [Trade from Chat](base-mcp-plugin.md) — the Base MCP plugin setup
- [AgentKit guide](agentkit.md) — autonomous agents, both modes
- AgentKit repo: [SETUP.md](https://github.com/Thetanuts-Finance/thetanuts-agentkit/blob/main/SETUP.md) (end-to-end setup: CDP wallet, client configs for Claude Desktop/Code, Cursor, Codex) and [SKILL.md](https://github.com/Thetanuts-Finance/thetanuts-agentkit/blob/main/SKILL.md) (a walkthrough skill any skill-aware agent can load)
65 changes: 65 additions & 0 deletions docs/guides/base-mcp-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Trade from Chat — the Base MCP Plugin

The Base MCP plugin lets anyone trade Thetanuts options from a chat client (Claude Desktop, Claude Code, Cursor, ChatGPT, Codex) **while keeping every signature in their own hands**. The LLM prepares the trade; you approve it in [Base Account](https://docs.base.org/ai-agents/quickstart). The plugin never signs, never broadcasts, never holds keys.

Source: [`mcp-server/plugins/base-mcp/`](https://github.com/Thetanuts-Finance/thetanuts-sdk/tree/main/mcp-server/plugins/base-mcp) — it follows Base's [custom plugin spec](https://docs.base.org/ai-agents/plugins/custom-plugins).

## How it works

Two MCP servers split the job — protocol knowledge and key custody never share a process:

```
┌─────────────┐ prepare_* ┌──────────────────────────┐ encode* ┌──────────────┐
│ LLM (Claude │ ─────────────▶ │ Thetanuts MCP (stdio) │ ────────────▶ │ Thetanuts │
│ + Base MCP)│ │ v1.0.0+ │ │ SDK helpers │
│ │ ◀───────────── │ → { chain, calls[] } │ │ │
└──────┬──────┘ unsigned tx └──────────────────────────┘ └──────────────┘
│
│ send_calls
▼
┌─────────────┐
│ Base Account│ → user approval → tx broadcast on Base 8453
└─────────────┘
```

The Thetanuts MCP's `prepare_*` tools return Base-MCP-ready `{ chain, calls }` envelopes; the LLM hands them to Base MCP's `send_calls`; you review and confirm in Base Account.

## Install

1. **Base MCP** in your client — see the [Base quickstart](https://docs.base.org/ai-agents/quickstart).
2. **Thetanuts MCP** (v1.0.0+):

```bash
claude mcp add thetanuts-mcp \
-e KEYSTORE_MASTER_KEY="$(openssl rand -hex 32)" \
-- npx -y @thetanuts-finance/mcp
```

(Equivalent config-file entries for Claude Desktop / Cursor / Codex.)
3. **The plugin skill**:

```bash
npx skills add Thetanuts-Finance/thetanuts-sdk \
--skill mcp-server/plugins/base-mcp \
-a claude-code # or: cursor | codex | hermes
```

For Claude Desktop / claude.ai or ChatGPT, zip the plugin directory and upload it as a custom skill.
4. A funded Base Account on Base mainnet (USDC for collateral/premium, a little ETH for gas).

## What it can do

RFQ is the only write path: request quotes (all 9 products — puts, calls, spreads, butterflies, condors, iron condors), make sealed-bid offers, settle (normal or early), cancel, and standalone approvals. OptionBook fills are deliberately not surfaced — their silent-rejection failure modes (maker offline, indexer lag, race-loss) make poor first-trade UX in chat. Reads (orderbook, positions, IV surface, pricing) come from the same Thetanuts MCP.

## RFQ keys, handled for you

Sealed-bid RFQs need an ECDH keypair so market makers can encrypt offers to you. The Thetanuts MCP manages this server-side: keys are derived per wallet, stored AES-256-GCM-encrypted in a local SQLite keystore rooted in your `KEYSTORE_MASTER_KEY`, and **never enter the LLM transcript**. These are encryption keys only — they cannot move funds.

## Out of scope (v1)

Vault deposits/withdrawals, Ethereum mainnet (chainId 1), physical multi-leg options, and loan flows.

## See also

- [AI Agents overview](agents-overview.md) — how this route compares to autonomous AgentKit trading
- [MCP Server guide](mcp-server.md) — the full tool reference behind this plugin
2 changes: 2 additions & 0 deletions docs/guides/mcp-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ For full details, see [mcp-server/README.md](../../mcp-server/README.md) and [mc

## This MCP vs `@thetanuts-finance/agentkit`

> Full landscape, including the trade-from-chat and headless-bot routes: [AI Agents — Pick Your Route](agents-overview.md).

Both are thin layers over the same `@thetanuts-finance/thetanuts-client` encode helpers — the difference is who signs and where the safety boundary lives:

| | `@thetanuts-finance/mcp` | [`@thetanuts-finance/agentkit`](https://github.com/Thetanuts-Finance/thetanuts-agentkit) |
Expand Down
27 changes: 26 additions & 1 deletion docs/resources/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ Version history for the Thetanuts Finance SDK.

## Current Version

**v0.2.3** — [View all releases on GitHub](https://github.com/Thetanuts-Finance/thetanuts-sdk/releases)
**v0.3.0** — [View all releases on GitHub](https://github.com/Thetanuts-Finance/thetanuts-sdk/releases)

Companion packages: [`@thetanuts-finance/mcp`](https://www.npmjs.com/package/@thetanuts-finance/mcp) **v1.0.0** (MCP server) and [`@thetanuts-finance/agentkit`](https://www.npmjs.com/package/@thetanuts-finance/agentkit) **v0.2.x** (autonomous agents) — see [AI Agents](../guides/agents-overview.md).

This SDK follows [Semantic Versioning](https://semver.org/): `MAJOR.MINOR.PATCH`. Patch releases contain bug fixes and non-breaking improvements. Minor releases add new functionality in a backwards-compatible manner. Major releases may contain breaking changes and will be accompanied by a migration guide.

Expand All @@ -17,6 +19,29 @@ This SDK follows [Semantic Versioning](https://semver.org/): `MAJOR.MINOR.PATCH`

## Release History

### v0.3.0 — RFQ agent helpers, multi-leg payout math, hardening

Minor release, no breaking changes.

**Added:**
- **RFQ sealed-bid agent helpers** — `optionFactory.buildOfferTypedData()` (EIP-712 `Offer` envelope with live `OFFER_TYPEHASH` verification, fails closed on drift), `api.getRequesterPublicKey(quotationId)`, and `api.getOffer(...)`. These power [`@thetanuts-finance/agentkit`](../guides/agentkit.md) and the MCP prepare service; agentkit's peer range requires `>=0.3.0`.
- **Off-chain payout + collateral math for all multi-leg structures.** `client.utils.calculatePayout()` / `calculateCollateral()` now cover `call_fly`, `put_fly`, `call_condor`, `put_condor`, `iron_condor`, and `ranger` — pure bigint, no RPC, usable for pre-trade UI previews. Previously multi-leg types threw `INVALID_PARAMS`.

**Fixed:** MCP `validate_ranger` schema matched to the SDK validator (4 strikes); `calculateMaxPayout` / `calculatePayoutAtPrice` no longer fall through to spread math for 3- and 4-strike orders.

**Security:** write methods assert the connected network before building transactions; OptionBook swap paths validate router/token addresses and swap data; MCP prepare tools tighten auth and redact URLs from errors.

### v0.2.5 — loan indexer r12 fixes

- Loan indexer URL repointed to the r12 worker — consumers were reading r12 contract state but querying the legacy v1 indexer, seeing archived loans and missing every r12 RFQ/offer/loan.
- `LoanModule` backfills the r12 indexer's missing fields (`strike`, `expiryTimestamp`, `buyer`, `seller`) from on-chain `getOptionInfo()`, so `getLendingOpportunities()` and `getUserLoans()` return complete rows.
- 9 collar types re-exported from the package barrel (they shipped in 0.2.4 but weren't reachable from the public API).

### v0.2.4 — Collar Loan module + security audit closeout

- **`client.collar`** — zero-interest, capped-upside loans via RFQ (buy put at `K_lo` + sell call at `K_hi`; MM funds an up-front USDC loan from the call premium). Pricing/read methods work today against live Deribit quotes; write methods throw `NETWORK_UNSUPPORTED` until the coordinator contract deploys.
- **Security audit closeout** — remediates the full `SECURITY_AUDIT_BETA.md` backlog (1 Critical, 24 High, 73 Medium/Low/Informational): admin-only entrypoints removed from SDK ABIs, WheelVault allowance + event-log filtering fixes, `marketFill` swap-router validation made unconditional, `splitOption`/`reclaimCollateral` fee-forwarding wrappers, and more — see the per-finding tracker in the repo.

### v0.2.3 — strategyVault rename (BREAKING)

Renames two public symbols on `client.strategyVault`. Behavior, ABIs, and contract addresses are unchanged.
Expand Down
2 changes: 1 addition & 1 deletion docs/resources/llm-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ The file is generated at the same time as the npm package, so what you see match
The two LLM files track the latest published SDK release. To pin to a specific version, replace `main` in the URL with a version tag:

```
https://raw.githubusercontent.com/Thetanuts-Finance/thetanuts-sdk/v0.2.3/llms-full.txt
https://raw.githubusercontent.com/Thetanuts-Finance/thetanuts-sdk/v0.3.0/llms-full.txt
```

See [GitHub Releases](https://github.com/Thetanuts-Finance/thetanuts-sdk/releases) for the available tags.
Expand Down
11 changes: 11 additions & 0 deletions docs/resources/migration-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Upgrade guide for existing users moving to the latest SDK patterns and APIs.

## Table of Contents

- [Migrating to v0.3.0](#migrating-to-v030)
- [Migrating to v0.2.1 (Base_r12 deployment)](#migrating-to-v021-base_r12-deployment)
- [Breaking Changes](#breaking-changes)
- [New Helper Methods](#new-helper-methods)
Expand All @@ -13,6 +14,16 @@ Upgrade guide for existing users moving to the latest SDK patterns and APIs.

---

## Migrating to v0.3.0

**No breaking changes** — 0.3.0 is additive over 0.2.x. Upgrade with a plain `npm install @thetanuts-finance/thetanuts-client@^0.3.0`. One heads-up between the 0.2.x patches: v0.2.3 renamed two `strategyVault` symbols (see [Changelog](changelog.md)) — if you're jumping from ≤0.2.2, apply that find-and-replace.

What you gain:

- **RFQ sealed-bid agent helpers** — `optionFactory.buildOfferTypedData()`, `api.getRequesterPublicKey()`, `api.getOffer()`. Required by [`@thetanuts-finance/agentkit`](../guides/agentkit.md) (its peer range is `>=0.3.0`).
- **Off-chain multi-leg payout/collateral math** — `client.utils.calculatePayout()` / `calculateCollateral()` for flies, condors, iron condors, and rangers (previously `INVALID_PARAMS`).
- **Hardened write paths** — pre-write network assertions and stricter swap-parameter validation. Code that previously passed malformed swap params to `swapAndFillOrder` / `marketFill` now fails fast with `INVALID_PARAMS` instead of reverting on-chain.

## Migrating to v0.2.1 (Base_r12 deployment)

v0.2.1 is the first 0.2.x release published to npm. It bundles the Base_r12 deployment cutover with 22 fixes that three adversarial code-review passes found in the staged surface. v0.2.0 was prepared internally but never published — there is no v0.2.0 on npm.
Expand Down
Loading