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

# TypeScript SDK

> Install, configure, and get started with the @grantex/sdk TypeScript SDK.

## Installation

Published release: **`@grantex/sdk@0.8.2`**. The npm tarball matches the
validated CI artifact; see [Release Status](/release-status).

```bash theme={null}
npm install @grantex/sdk@0.8.2
```

The unpinned `npm install @grantex/sdk` command follows npm's current `latest`
tag. Keep the exact version above in reproducible builds. See
[Release Status](/release-status) before upgrading.

Version `0.7.0` adds `grantex.webauthn.createEnrollmentSession()` for
principal-authenticated hosted passkey registration and
`grantex.anomalies.getResponsePolicy()` / `setResponsePolicy()` for the
account-level irregularity response mode. Both server capabilities are
default-off for self-hosted deployments and require explicit operator rollout;
both are enabled on the Grantex-hosted service.

Version `0.7.1` adds typed `WebAuthnGrantEvidence` references to grant and
verification responses and the updated VC WebAuthn attestation. It does not
enable hosted server flags or add custom assertion UI helper methods.

<Warning>
  Version `0.8.2` requires Node.js 22.12+ and retains the 0.8.0 breaking enforcement
  defaults: audience binding, denial of capped calls without trusted amounts,
  and online revocation checks. Register allowed resource servers before
  audience-bound authorization. Signature-only verification is not current-state
  enforcement. Follow [the migration guide](/migration-enforcement).
</Warning>

<Note>
  SDK `0.6.0` introduced `PrepaidWalletAgentClient`,
  `PrincipalPrepaidWalletClient`, and `DeveloperPrepaidWalletPolicyClient` with
  safe assignment defaults, layered policy, exact approval, semantic context, and
  reload governance. Version `0.6.0` also adds EVM payment responses and
  `reconcileReservation()` to principal and agent wallet clients. Pair it with
  `@grantex/x402@0.4.1` for opt-in Base USDC 402/sign/retry. External custody
  remains fail-closed until the operator configures the Base custody/RPC adapter
  or supplies another verified provider. See [x402
  Prepaid Wallets](/integrations/x402) and [Agent Wallet
  Governance](/guides/agent-wallet-governance).
</Note>

## Requirements

* **Node.js 22.12+** (uses native `fetch` and `crypto`)
* **ESM only** -- the package ships as `"type": "module"` with TypeScript `NodeNext` resolution

## Configuration

```typescript theme={null}
import { Grantex } from '@grantex/sdk';

const grantex = new Grantex({
  apiKey: process.env.GRANTEX_API_KEY,  // required (or set GRANTEX_API_KEY env var)
  baseUrl: 'https://api.grantex.dev',   // optional, defaults to production
  timeout: 30_000,                       // optional, request timeout in ms
});
```

### Options

<ParamField body="apiKey" type="string" required>
  Your Grantex API key. Falls back to the `GRANTEX_API_KEY` environment variable if omitted.
</ParamField>

<ParamField body="baseUrl" type="string" default="https://api.grantex.dev">
  Base URL for the Grantex API. Override for self-hosted or local development.
</ParamField>

<ParamField body="timeout" type="number" default="30000">
  Request timeout in milliseconds. The SDK uses `AbortController` to enforce the deadline.
</ParamField>

## Quick start

The complete authorization flow in one script:

```typescript theme={null}
import { Grantex, verifyGrantToken } from '@grantex/sdk';

const grantex = new Grantex({ apiKey: process.env.GRANTEX_API_KEY });

// 1. Register an agent
const agent = await grantex.agents.register({
  name: 'travel-booker',
  description: 'Books flights and hotels on behalf of users',
  scopes: ['calendar:read', 'payments:initiate:max_500', 'email:send'],
});
console.log(agent.did);
// → did:grantex:ag_01HXYZ123abc...

// 2. Request user authorization
const authRequest = await grantex.authorize({
  agentId: agent.id,
  userId: 'user_abc123',
  scopes: ['calendar:read', 'payments:initiate:max_500'],
  expiresIn: '24h',
  redirectUri: 'https://yourapp.com/auth/callback',
});
// Redirect the user to authRequest.consentUrl

// 3. Exchange the authorization code for a grant token
const token = await grantex.tokens.exchange({
  code,                  // from the redirect callback
  agentId: agent.id,
});
console.log(token.grantToken);  // RS256 JWT
console.log(token.scopes);      // ['calendar:read', 'payments:initiate:max_500']

// 4. Verify signature and claims locally after fetching the remote JWKS
const grant = await verifyGrantToken(token.grantToken, {
  jwksUri: 'https://api.grantex.dev/.well-known/jwks.json',
  requiredScopes: ['calendar:read'],
});
console.log(grant.principalId); // 'user_abc123'

// 5. Revoke the token when done
await grantex.tokens.revoke(grant.tokenId);
```

## Available resources

The `Grantex` client exposes the following sub-clients:

| Property | Description | Reference |
| - | - | - |
| `grantex.agents` | Register, list, update, and delete agents | [Agents](/sdks/typescript/agents) |
| `grantex.tokens` | Exchange, verify, and revoke tokens | [Tokens](/sdks/typescript/tokens) |
| `grantex.grants` | Manage grants, delegate to sub-agents | [Grants](/sdks/typescript/grants) |
| `grantex.audit` | Log and query the tamper-evident audit trail | [Audit](/sdks/typescript/audit) |
| `grantex.webhooks` | Create and manage webhook endpoints | [Webhooks](/sdks/typescript/webhooks) |
| `grantex.policies` | Define authorization policies | [Policies](/sdks/typescript/policies) |
| `grantex.compliance` | Compliance summaries, exports, evidence packs | [Compliance](/sdks/typescript/compliance) |
| `grantex.anomalies` | Detect and acknowledge anomalies | [Anomalies](/sdks/typescript/anomalies) |
| `grantex.billing` | Subscription management via Stripe | [Billing](/sdks/typescript/billing) |
| `grantex.scim` | SCIM 2.0 user provisioning | [SCIM](/sdks/typescript/scim) |
| `grantex.sso` | OIDC single sign-on | [SSO](/sdks/typescript/sso) |
| `grantex.principalSessions` | End-user dashboard sessions | [Principal Sessions](/sdks/typescript/principal-sessions) |
| `grantex.vault` | Store, retrieve, and exchange service credentials | [Vault](/sdks/typescript/vault) |
| `grantex.budgets` | Per-grant spending budgets and transactions | [Budgets](/sdks/typescript/budgets) |
| `grantex.events` | SSE event streaming | [Events](/sdks/typescript/events) |
| `grantex.usage` | Usage metering and history | [Usage](/sdks/typescript/usage) |
| `grantex.domains` | Custom domain verification | [Domains](/sdks/typescript/domains) |
| `grantex.webauthn` | FIDO2/WebAuthn passkey management | [WebAuthn](/sdks/typescript/webauthn) |
| `grantex.credentials` | Verifiable Credentials and SD-JWT | [Credentials](/sdks/typescript/credentials) |
| `grantex.passports` | MPP agent passport credentials | [Passports](/sdks/typescript/passports) |
| `grantex.commerce` | Commerce V1 / OACP merchant discovery, catalog, consent, passport, payment, checkout, webhooks, and ops | [Commerce V1](/sdks/typescript/commerce) |
| `grantex.dpdp` | DPDP Act 2023 records — consent, grievances, erasure, exports | [DPDP](/features/dpdp-compliance) |

## Standalone exports

These functions can be used without instantiating a `Grantex` client:

| Export | Description | Reference |
| - | - | - |
| `verifyGrantToken()` | Local JWT verification with a JWKS fetch per standalone call | [Offline Verification](/sdks/typescript/offline-verification) |
| `generatePkce()` | Generate PKCE S256 challenge pairs | [PKCE](/sdks/typescript/pkce) |
| `verifyWebhookSignature()` | Verify webhook payload signatures | [Webhooks](/sdks/typescript/webhooks) |

## Error handling

All errors extend `GrantexError`. See the [Error Handling](/sdks/typescript/errors) reference for the full hierarchy and usage patterns.

## Ownership

Grantex is owned by Orchestrum Technologies LLP. Inventor and owner: Sanjeev Kumar. Ownership contact: [sanjeev@orchestrum.in](mailto:sanjeev@orchestrum.in) or [mishra.sanjeev@gmail.com](mailto:mishra.sanjeev@gmail.com).


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