> ## Documentation Index
> Fetch the complete documentation index at: https://docs.skia.money/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> @skia-money/sdk — the hardened TypeScript client for the Skia settlement API: one-shot swaps, edge payments with PaymentGuard, crash recovery, and an MCP client.

# TypeScript SDK

`@skia-money/sdk` is the hardened TypeScript client for the Skia settlement
API — commit/reveal swaps, edge-layer payments, portfolio/tier reads, and an
MCP (JSON-RPC 2.0) client. It is built **against the live server contracts**,
not a spec guess: where the incoming skeleton and the server disagreed, the
server won, and every hardening decision is recorded.

> [!NOTE]
>
> This page is the overview. The full package-level reference — configuration,
> authentication, the error taxonomy, advanced usage, and migration guides —
> lives at the SDK docs site [sdk.skia.money](https://sdk.skia.money)
> (Docusaurus).

## Install

The package is not published to npm yet; consume it from the monorepo (bun
resolves TS directly):

```ts theme={null}
import SkiaClient from "@skia-money/sdk";
// or, from within this repo:
import { SkiaClient } from "../../packages/skia-sdk/src/index";
```

Build declarations (dist/ with .d.ts):

```bash theme={null}
cd packages/skia-sdk && bun run build
```

## One-shot sovereign swap

```ts theme={null}
const skia = new SkiaClient({ baseUrl: "http://localhost:3000" });

// 1. Create + fund a testnet custodial taker
const wallet = await skia.createWallet({ label: "agent-1" });
await skia.faucet(wallet.address, "arbitrum");

// 2. One-shot swap: quote -> commit -> reveal, single-fire, idempotent by key
const result = await skia.swap({
  chainId: "arbitrum",
  tokenIn: "USDC",
  tokenOut: "DAI",
  amountIn: "100",
  senderWallet: wallet.address,
  idempotencyKey: "swap-2026-11-30-001", // replay-safe
});

console.log(result.txHash, result.explorerUrl, result.entryPoint);
```

The taker address is the auth bearer (simulated ethSigAuth — commit/reveal
authenticate as `senderWallet`). Pass `bearerToken` in the config to pin it.

## Chain keys and settlement ids

The **wire** accepts twelve app-chain keys — eight live (each backed by a
canonical testnet deployment) and four dormant
(`taiko`, `bsc`, `polygon`, `hyperevm`; hyperevm staged). Dormant keys carry
`status: "dormant"` everywhere and are refused client-side by the SDK.

> [!NOTE]
>
> SDK drift note: the SDK as of v0.2.1 carries ten keys (seven live + three
> dormant) and does not yet know `monad` or `hyperevm`. The catch-up toward the
> twelve-key wire is tracked in the drift ledger
> (`docs/ops/sdk-hardening-drift.md`). The wire truth above is what the server
> answers today.

Labels, statuses, and settlement ids are **not the same thing**:

* `SKIA_CHAINS[key].chainIdNumeric` is the production id the label derives
  from — do NOT build signature domains or explorer links from it.
* The real settlement ids live in `SKIA_CHAINS[key].settlementChainIdNumeric`
  and, authoritatively, in `WalletSummary.settlementNetwork.chainIdNumeric`.

```ts theme={null}
import { SKIA_LIVE_CHAINS, SKIA_DORMANT_CHAINS, isDormantChain, settlementNumericIdFor } from "@skia-money/sdk";

SKIA_LIVE_CHAINS;             // the live labels
SKIA_DORMANT_CHAINS;          // ["taiko", "bsc", "polygon"]
settlementNumericIdFor("xlayer"); // 1952 — use for domains/explorers (NOT the dead 195 pin)
```

## Simulated settlements — txHash is nullable, always labeled

A swap can succeed without touching a chain (DB-simulated settlement on
non-backed lanes). Every reveal response is normalized by the SDK:

```ts theme={null}
const result = await skia.swap({ /* ... */ });
result.settlementMode; // "on-chain" | "simulated"
result.txHash;         // null when simulated — NEVER link it to an explorer
result.onChain;        // wire flag (server)
```

The server historically wired a synthetic hash on the simulated path; the SDK
normalizes it away so front ends cannot link a fake hash.

## Reliability semantics

* **Idempotency**: `swap()` and `commit()` accept an `idempotencyKey`, cached
  in a pluggable store (`MemoryIdempotencyStore` by default — inject your own
  for persistence across restarts).
* **Single-fire**: `reveal()` never transport-retries (an already-revealed
  commit throws). `commit()` is single-fire by default too — the server
  ignores the `Idempotency-Key` header today (CONTRACT-1), so an automatic
  mid-timeout retry could double-commit. Opt in with
  `retryMutatingRequests: true` if you accept that trade.
* **Crash recovery**: died between commit and reveal — `resumeSwap({ commit })`
  reveals once and recovers from order history on ALREADY\_REVEALED; died
  right after reveal — the next call recovers the txHash from
  `GET /api/wallets/{address}/orders`, matched by window + token hints and
  marked `recovered: true`. Zero or multiple candidates refuse to guess —
  money is never matched ambiguously.
* **Retries**: exponential backoff with full jitter (base 500ms, cap 8s,
  3 retries), honoring `Retry-After`. Transport errors and 429/5xx retry —
  including 5xx with no JSON body. Protocol errors (402, hash mismatch,
  single-fire semantics) never do.

## Edge payments with a guard

Skia's edge lane is a **custom pay-and-resubmit protocol, honestly named not
x402**: a 402 carries a `X-Payment-Request` header (base64 JSON), the payment
settles out of band via `POST /api/payment/verify`, and the identical quote
request is resubmitted. Auto-pay is **capped or refused** — enabling
`autoPayX402` without a `paymentGuard` throws at construction time:

```ts theme={null}
const skia = new SkiaClient({
  baseUrl,
  autoPayX402: true,
  paymentGuard: {
    maxAmountPerPayment: "1000000",   // 1 USDC (base units, 6 decimals)
    maxTotalSpend: "10000000",        // 10 USDC lifetime on this client
    maxPayments: 25,
    allowedAssets: ["USDC"],
    allowedPayTo: [SERVER_REVENUE_WALLET],
    allowedNetworks: ["base"],
    allowedPurposes: ["quote"],
  },
});
```

The guard checks amount caps, cumulative spend, payment count, and
asset/recipient/network/purpose allow-lists **before** the executor runs.
Violations raise `PaymentGuardViolationError` with the reason and `paymentId`.

## MCP client

```ts theme={null}
import { SkiaMcpClient } from "@skia-money/sdk";

const mcp = new SkiaMcpClient({
  baseUrl: "http://localhost:3000",
  bearerToken: taker,
  clientInfo: { name: "my-agent", version: "1.2.0" }, // sent in the handshake
});
await mcp.initialize();                     // + notifications/initialized
const tools = await mcp.listTools();
const res = await mcp.callTool("skia_quote", {
  chainId: "arbitrum", tokenIn: "USDC", tokenOut: "DAI", amountIn: "100",
});
```

## Error taxonomy at a glance

`SkiaApiError` (status + server code + retryable + details) with
specializations: `RateLimitError`, `PaymentRequiredError`, `AlreadyRevealedError`,
`CommitExpiredError`, `OrderSenderMismatchError`, `SkiaNetworkError`,
`PaymentGuardViolationError`, `McpRpcError`/`McpProtocolError`, and
client-side fail-fast `InvalidParamError`. Server codes map 1:1
(`COMMITMENT_HASH_MISMATCH`, `QUOTE_EXPIRED`, `SIGNER_MISMATCH`, ...). A 2xx
with a non-JSON body raises `MALFORMED_RESPONSE` — never a null that crashes
downstream. The full table with retry rules is at
[sdk.skia.money](https://sdk.skia.money/docs/error-handling).

## Posture (read before quoting custody or auth)

* `WalletSummary.custody` is one of `server-custodial | simulated | external`;
  **server-custodial is the only production path in Phase 1**.
* The bearer is an UNSIGNED address (simulated ethSigAuth) — fine for testnet
  due diligence, a **mainnet blocker**. Auth stays pluggable; nothing in the
  SDK stores or transmits key material — signers are injected.

## Where to next

* Full package reference: [sdk.skia.money](https://sdk.skia.money).
* Wire truth and the generated endpoint pages: [API Reference](https://docs.skia.money/api-reference/overview.md).
* Drive the same flows from an LLM agent: [MCP Server](https://docs.skia.money/mcp-server.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.