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

# Client Libraries

> Backend SDKs and frontend integration packages for KeyStone OS.

KeyStone provides two types of client libraries, each designed for a different part of your stack:

## Backend SDKs vs Frontend Packages

|                    | Backend SDKs                                                             | Frontend Packages                                                 |
| ------------------ | ------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| **Packages**       | `@keystoneos/sdk` (TypeScript), `keystoneos` (Python)                    | `@keystoneos/react`, `@keystoneos/elements-core`                  |
| **Runs in**        | Your server (Node.js, Python backend)                                    | Your user's browser (React app)                                   |
| **Authentication** | M2M credentials (client\_id + client\_secret)                            | Session tokens (short-lived, scoped JWTs)                         |
| **Purpose**        | Full API access - create settlements, manage webhooks, handle compliance | Display settlement data, collect user decisions, trigger deposits |
| **Credentials**    | Must be kept secret (never in browser)                                   | Safe for browser (scoped, short-lived, revocable)                 |

```mermaid theme={null}
flowchart LR
    subgraph Backend
        SDK["@keystoneos/sdk\n(M2M credentials)"]
        Node["@keystoneos/node\n(session token creation,\nwebhook middleware)"]
    end

    subgraph Frontend
        React["@keystoneos/react\n(hooks + provider)"]
        Core["@keystoneos/elements-core\n(session token auth)"]
    end

    SDK -->|"POST /v1/sessions"| KS[KeyStone API]
    KS -->|session token| Node
    Node -->|token passed to frontend| React
    React -->|session token| KS
    Core --> React
```

***

## Backend SDKs

For server-side integration. Use M2M credentials to access the full API.

<CardGroup cols={2}>
  <Card title="TypeScript / Node.js" icon="js" href="/sdks/typescript">
    `@keystoneos/sdk` - Node.js 20+, zero dependencies. Handles auth, retries, idempotency, and webhook verification.
  </Card>

  <Card title="Python" icon="python" href="/sdks/python">
    `keystoneos` - Python 3.10+, async and sync clients. Full Pydantic models for all types.
  </Card>
</CardGroup>

### What the SDKs handle

| Feature                  | Details                                                                        |
| ------------------------ | ------------------------------------------------------------------------------ |
| **Authentication**       | Auth0 M2M token fetch, caching, and automatic refresh before expiry            |
| **Retries**              | Exponential backoff with jitter on 429 and 5xx. Respects `Retry-After` headers |
| **Idempotency**          | Built-in `generateIdempotencyKey()` for safe retries on creation endpoints     |
| **Webhook verification** | HMAC-SHA256 signature verification with timing-safe comparison                 |
| **Type safety**          | Full TypeScript types / Pydantic models for all request and response objects   |
| **Pagination**           | Typed paginated responses with `items`, `total`, `limit`, `offset`             |

***

## Frontend Integration

Embed settlement UI into your platform's web app. The frontend packages use session tokens (created by your backend) for scoped API access.

<CardGroup cols={3}>
  <Card title="React Hooks" icon="react" href="/elements/overview">
    `@keystoneos/react` - Headless hooks for settlements, instructions, deposits. Bring your own UI.
  </Card>

  <Card title="Server Setup" icon="server" href="/node/create-session-token">
    `@keystoneos/node` - The backend side of the frontend integration: session tokens and webhook verification.
  </Card>

  <Card title="Components" icon="puzzle-piece" href="/components/keystone-provider">
    `KeystoneProvider` - Wrap your app to enable all hooks.
  </Card>
</CardGroup>

### What the frontend integration covers

| Layer             | Package                     | What it does                                                   |
| ----------------- | --------------------------- | -------------------------------------------------------------- |
| **Your backend**  | `@keystoneos/node`          | Creates session tokens, verifies webhook signatures            |
| **Your frontend** | `@keystoneos/react`         | React hooks for settlements, instructions, deposits, templates |
| **Core**          | `@keystoneos/elements-core` | Framework-agnostic primitives (auth, events, state machine)    |

***

## When to use what

| Scenario                                          | Use                                     |
| ------------------------------------------------- | --------------------------------------- |
| Create settlements from your backend              | `@keystoneos/sdk`                       |
| Handle webhooks on your server                    | `@keystoneos/sdk` or `@keystoneos/node` |
| Show settlement status to traders in your web app | `@keystoneos/react`                     |
| Let traders submit instructions from your web app | `@keystoneos/react`                     |
| Create session tokens for your frontend           | `@keystoneos/node`                      |
| Build a non-React frontend                        | `@keystoneos/elements-core`             |
| Call the API from a language without an SDK       | Raw HTTP (cURL, httpx, fetch)           |

Every endpoint in the [API Reference](/api-reference/overview) works with any HTTP client. The SDKs and packages are convenience layers, not a separate API.

***

## Quick comparison

<CodeGroup>
  ```typescript Backend SDK (Node.js) theme={null}
  import { KeystoneClient } from "@keystoneos/sdk";

  // M2M auth - for your backend
  const client = new KeystoneClient({
    clientId: process.env.KEYSTONE_CLIENT_ID!,
    clientSecret: process.env.KEYSTONE_CLIENT_SECRET!,
  });

  const instruction = await client.instructions.submit({
    templateSlug: "dvp-bilateral",
    role: "seller",
    party: { externalReference: "ACC-001", walletAddress: "0x..." },
    legs: [
      { legType: "asset_delivery", instrumentId: "0xTokenAddress", quantity: "1000000", direction: "deliver", chainId: 11155111 },
      { legType: "payment", instrumentId: "0xUSDCAddress", quantity: "1000000", direction: "receive", chainId: 11155111 },
    ],
    timeoutAt: new Date(Date.now() + 86400000).toISOString(),
    idempotencyKey: client.generateIdempotencyKey(),
  });
  ```

  ```tsx Frontend Hooks (React) theme={null}
  import { KeystoneProvider, useSettlement, useDeposit } from "@keystoneos/react";

  // Session token auth - for your frontend
  function SettlementView({ id }) {
    const { settlement } = useSettlement(id);
    const { deposit, status } = useDeposit(id, 0);

    return (
      <div>
        <p>State: {settlement?.state}</p>
        <button onClick={deposit}>Deposit</button>
      </div>
    );
  }
  ```

  ```python Backend SDK (Python) theme={null}
  from keystoneos import KeystoneClient

  # M2M auth - for your backend
  client = KeystoneClient(
      client_id="YOUR_CLIENT_ID",
      client_secret="YOUR_CLIENT_SECRET",
  )

  instruction = await client.instructions.submit({
      "template_slug": "dvp-bilateral",
      "role": "seller",
      "party": {"external_reference": "ACC-001", "wallet_address": "0x..."},
      "legs": [
          {"leg_type": "asset_delivery", "instrument_id": "0xTokenAddress", "quantity": "1000000", "direction": "deliver", "chain_id": 11155111},
          {"leg_type": "payment", "instrument_id": "0xUSDCAddress", "quantity": "1000000", "direction": "receive", "chain_id": 11155111},
      ],
      "timeout_at": "2026-12-01T00:00:00Z",
      "idempotency_key": client.generate_idempotency_key(),
  })
  ```
</CodeGroup>
