# @opacus/sdk

> **Opacus hosts agent infrastructure via APIs — you run your agent anywhere.**

API control plane for agent identity (DID), low-latency routing (Nitro), geo-policy (H3), storage (0G), and settlement (Pay / Escrow).

[![npm version](https://badge.fury.io/js/opacus-sdk.svg)](https://www.npmjs.com/package/opacus-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

- REST-first — every SDK call maps 1:1 to a documented endpoint
- Bootstrap + scoped token lifecycle handled automatically
- Safe defaults: retries, timeouts, request IDs, budget-safe errors

## Install

```bash
npm i opacus-sdk
```

## Quickstart (5 minutes)

**1.** Create a **Project + API Key** in [Agentboard](https://opacus.xyz/agentboard.html)

**2.** Set your key:

```bash
export OPACUS_API_KEY="op_live_..."
```

**3.** Call the API:

```typescript
import { Opacus } from "opacus-sdk";

const opacus = new Opacus({ apiKey: process.env.OPACUS_API_KEY! });

// Bootstrap: performs /challenge + /register, issues DID + scoped tokens
await opacus.bootstrap();

// Nitro routing — find the fastest execution path
const route = await opacus.routing.optimize({
  intent: "swap",
  chain: "base",
  mode: "fast",
});
console.log("route", route);

// H3 geo-policy — resolve your agent's hex cell
const loc = await opacus.h3.locate({ resolution: 8 });
console.log("h3", loc);

// 0G storage — store data on decentralized DA layer
const stored = await opacus.ogStorage.store({ key: "value" });
console.log("cid", stored.rootHash);
```

## Scoped Tokens

`bootstrap()` issues 3 scoped tokens, refreshed automatically:

| Token | TTL | Scopes |
|-------|-----|--------|
| **AGENT** | 24 h | `nitro.execute`, `h3.routing` |
| **DATA** | 24 h | `0g.upload`, `0g.download` |
| **PAY** | 1 h | `pay.gas_subsidy`, `pay.escrow` |

## Payment Rails

Use a single compute balance across all supported rails.

```typescript
const rails = await opacus.getPaymentRails();

console.log(rails.computeBalance); // { balance, currency }
console.log(rails.paymentRails.rails.map(r => ({
  id: r.id,
  enabled: r.enabled,
  providers: r.providers,
})));
```

Response shape:

```json
{
  "ok": true,
  "computeBalance": { "balance": 20, "currency": "USDC" },
  "paymentRails": {
    "provider": "0g_pay",
    "model": "three_rails_one_compute_balance",
    "rails": [
      { "id": "fiat", "enabled": true, "providers": ["stripe"] },
      { "id": "multichain_crypto", "enabled": true, "providers": ["khalani"] },
      { "id": "native_0g", "enabled": true, "providers": ["opacus"] }
    ]
  }
}
```

If your flow is MCP-first, use:

```typescript
const railsViaMcp = await opacus.getPaymentRailsViaMcp();
```

## Product Analytics

Query adoption and module usage analytics (DID, H3, OpacusPay, Data Bridge, etc.):

```typescript
const analytics = await opacus.getProductAnalytics({
  includeUsers: true,
  limit: 30,
  period: '30d',
  // adminToken: process.env.OPACUS_ADMIN_TOKEN, // optional for full user view
});

console.log(analytics.summary);
console.log(analytics.moduleStats);
```

## Optional SDK Telemetry (Opt-In)

Send anonymous usage events from SDK calls to your Opacus analytics endpoint:

```typescript
const opacus = new Opacus({
  apiKey: process.env.OPACUS_API_KEY!,
  telemetry: {
    enabled: true,
    anonymousId: 'client-123',
    appId: 'agentboard-prod',
    sdkVersion: '1.1.13',
    sampleRate: 1,
  },
});
```

Telemetry is disabled by default.

## Configuration

```typescript
const opacus = new Opacus({
  apiKey: process.env.OPACUS_API_KEY!,
  baseUrl: "https://opacus.xyz",   // default
  chain: "base",                    // default chain for operations
});
```

## Subpath Imports

Each module is tree-shakeable and independently importable:

```typescript
import { Opacus } from "opacus-sdk";          // Golden Path (recommended)
import { NitroClient } from "opacus-sdk/nitro";
import { H3RoutingClient } from "opacus-sdk/h3";
import { latLngToH3Cell } from "opacus-sdk/h3-utils"; // zero deps
import { BridgeClient } from "opacus-sdk/bridge";
import { EscrowClient } from "opacus-sdk/escrow";
```

## Error Handling

| Status | Code | Action |
|--------|------|--------|
| `402` | `BUDGET_EXHAUSTED` | Add funds / increase lock |
| `429` | `RATE_LIMITED` | Back off and retry |
| `5xx` | — | Retry with jitter |

```typescript
import { OpacusError } from "opacus-sdk";

try {
  await opacus.routing.optimize({ intent: "swap", chain: "base" });
} catch (e) {
  if (e instanceof OpacusError && e.status === 402) {
    console.error("Top up your lock in Agentboard");
  }
}
```

## REST-Only Usage

Prefer `curl`? Every SDK method maps directly to a REST endpoint:

```bash
curl -X POST https://opacus.xyz/v1/router/execute \
  -H "Authorization: Bearer $OPACUS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"intent":"swap","chain":"base","mode":"fast"}'
```

Full reference: [API Docs](https://opacus.xyz/docs/api-reference.html)

## Examples

See [`examples/`](examples/) for runnable scripts:

- [`mainnet-quick-start.ts`](examples/mainnet-quick-start.ts) — Bootstrap + route + store
- [`0g-da-storage.ts`](examples/0g-da-storage.ts) — Decentralized storage upload
- [`auto-payment-example.ts`](examples/auto-payment-example.ts) — OpacusPay automation

## Links

| | |
|-|-|
| **Docs** | [opacus.xyz/docs](https://opacus.xyz/docs) |
| **API Reference** | [opacus.xyz/docs/api-reference.html](https://opacus.xyz/docs/api-reference.html) |
| **Agentboard** | [opacus.xyz/agentboard.html](https://opacus.xyz/agentboard.html) |
| **Changelog** | [CHANGELOG.md](CHANGELOG.md) |
| **Issues** | [GitHub Issues](https://github.com/Opacus-xyz/opacus-sdk/issues) |

## License

[MIT](LICENSE)
