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

# TypeScript SDK

> Complete reference for the @agentwallex/sdk package — agents, payments, x402, policies, and webhooks.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @agentwallex/sdk
  ```

  ```bash yarn theme={null}
  yarn add @agentwallex/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @agentwallex/sdk
  ```
</CodeGroup>

## Client Initialization

```typescript theme={null}
import { AgentWallex } from "@agentwallex/sdk";

const aw = new AgentWallex({
  apiKey: process.env.AGENTWALLEX_API_KEY!,
  environment: "sandbox",  // "sandbox" | "production"
  baseUrl: undefined,       // Custom endpoint (optional)
  timeout: 30000,           // Request timeout in ms (default: 30000)
});
```

| Parameter     | Type                        | Default     | Description                             |
| ------------- | --------------------------- | ----------- | --------------------------------------- |
| `apiKey`      | `string`                    | Required    | Your API key (`awx_...`)                |
| `environment` | `"sandbox" \| "production"` | `"sandbox"` | Target environment                      |
| `baseUrl`     | `string`                    | --          | Custom base URL (overrides environment) |
| `timeout`     | `number`                    | `30000`     | Request timeout in milliseconds         |

## Agents

### `aw.agents.create(params)`

Create a new agent with an MPC-secured wallet.

```typescript theme={null}
const agent = await aw.agents.create({
  name: "my-agent",
  chain: "eip155:8453",
  policies: {
    maxTransactionAmount: "100",
    dailyLimit: "1000",
    allowedAddresses: ["0x..."],
    allowedTokens: ["USDC"],
    requireHumanApproval: false,
  },
  metadata: { team: "growth" },
});
```

**Returns:**

| Field            | Type     | Description              |
| ---------------- | -------- | ------------------------ |
| `id`             | `string` | Unique agent identifier  |
| `name`           | `string` | Agent display name       |
| `wallet.address` | `string` | On-chain wallet address  |
| `wallet.chain`   | `string` | CAIP-2 chain identifier  |
| `status`         | `string` | `"active"` or `"frozen"` |
| `createdAt`      | `string` | ISO 8601 timestamp       |

### `aw.agents.get(agentId)`

Retrieve an agent by ID.

```typescript theme={null}
const agent = await aw.agents.get("agent_abc123");
```

### `aw.agents.list(params?)`

List all agents for your account.

```typescript theme={null}
const { agents, pagination } = await aw.agents.list({
  limit: 20,
  offset: 0,
  status: "active",
});
```

### `aw.agents.freeze(agentId)`

Immediately freeze an agent's wallet, preventing all transactions.

```typescript theme={null}
await aw.agents.freeze("agent_abc123");
```

### `aw.agents.unfreeze(agentId)`

Re-enable an agent's wallet after a freeze (subject to 10-minute cool-down).

```typescript theme={null}
await aw.agents.unfreeze("agent_abc123");
```

## Payments

### `aw.payments.send(params)`

Send a direct on-chain payment.

```typescript theme={null}
const tx = await aw.payments.send({
  agentId: "agent_abc123",
  to: "0xRecipientAddress",
  amount: "50.00",
  token: "USDC",
  memo: "Payment for API access",
});
```

**Returns:**

| Field    | Type     | Description                            |
| -------- | -------- | -------------------------------------- |
| `id`     | `string` | Transaction ID                         |
| `hash`   | `string` | On-chain transaction hash              |
| `status` | `string` | `"pending"`, `"confirmed"`, `"failed"` |
| `amount` | `string` | Amount sent                            |
| `token`  | `string` | Token symbol                           |
| `fee`    | `string` | Network gas fee paid                   |

### `aw.payments.get(transactionId)`

Get transaction details and status.

```typescript theme={null}
const tx = await aw.payments.get("tx_xyz789");
```

### `aw.payments.list(params)`

List transactions for an agent.

```typescript theme={null}
const { transactions } = await aw.payments.list({
  agentId: "agent_abc123",
  limit: 50,
  status: "confirmed",
});
```

## x402 Micropayments

### `aw.x402.createSession(params)`

Create an x402 payment session with a spending budget.

```typescript theme={null}
const session = await aw.x402.createSession({
  agentId: "agent_abc123",
  budgetLimit: "100.00",
  chain: "eip155:84532",
  ttlSeconds: 3600,
  allowedUrls: ["https://paid-api.example.com/v1/data"],
});
```

### `aw.x402.check(params)`

Check whether a target URL supports x402 payment negotiation.

```typescript theme={null}
const info = await aw.x402.check({
  url: "https://paid-api.example.com/v1/data",
});
```

### `aw.x402.pay(params)`

Negotiate and complete one x402 payment.

```typescript theme={null}
const result = await aw.x402.pay({
  agentId: "agent_abc123",
  targetUrl: "https://paid-api.example.com/v1/data",
  sessionId: session.id,     // optional
  chain: "eip155:84532",     // optional
});
```

### `aw.x402.sessionPay(sessionId, params)`

Pay using an existing session budget.

```typescript theme={null}
await aw.x402.sessionPay(session.id, {
  targetUrl: "https://paid-api.example.com/v1/data",
});
```

### `aw.x402.httpInterceptor(params)`

Create an HTTP fetch wrapper that automatically handles x402 v2 challenges:

```typescript theme={null}
const fetchWithPayment = aw.x402.httpInterceptor({
  agentId: "agent_abc123",
  chain: "eip155:84532",
});

// Automatically handles 402 -> pay -> retry flow
const response = await fetchWithPayment("https://paid-api.example.com/v1/data");
const data = await response.json();
```

The interceptor:

1. Reads the `PAYMENT-REQUIRED` header from a 402 response
2. Submits payment via AgentWallex
3. Retries the request with the `PAYMENT-SIGNATURE` header

## Policies

### `aw.policies.update(agentId, policies)`

Update an agent's spending policies.

```typescript theme={null}
await aw.policies.update("agent_abc123", {
  maxTransactionAmount: "200",
  dailyLimit: "2000",
  allowedAddresses: ["0xAddr1", "0xAddr2"],
  velocityLimit: { maxCount: 100, windowSeconds: 3600 },
});
```

### `aw.policies.get(agentId)`

Get current policies for an agent.

```typescript theme={null}
const policies = await aw.policies.get("agent_abc123");
```

### `aw.policies.applyTemplate(agentId, templateName)`

Apply a policy template to an agent.

```typescript theme={null}
await aw.policies.applyTemplate("agent_abc123", "conservative");
```

### `aw.policies.createTemplate(name, rules)`

Create a reusable policy template.

```typescript theme={null}
await aw.policies.createTemplate("my-template", {
  maxTransactionAmount: "200",
  dailyLimit: "2000",
  allowedTokens: ["USDC"],
  velocityLimit: { maxCount: 50, windowSeconds: 3600 },
});
```

## Webhooks

### `aw.webhooks.create(params)`

Register a webhook endpoint.

```typescript theme={null}
const webhook = await aw.webhooks.create({
  url: "https://your-app.com/webhooks/agentwallex",
  events: [
    "payment.completed",
    "payment.failed",
    "agent.frozen",
    "policy.violated",
  ],
  secret: "whsec_your_signing_secret",
});
```

## Error Handling

The SDK provides typed error classes:

```typescript theme={null}
import {
  AgentWallexError,
  PolicyViolationError,
} from "@agentwallex/sdk";

try {
  await aw.payments.send({ ... });
} catch (error) {
  if (error instanceof PolicyViolationError) {
    console.log(`Policy violated: ${error.rule}`);
    console.log(`Details: ${error.message}`);
  } else if (error instanceof AgentWallexError) {
    console.log(`API error: ${error.code} - ${error.message}`);
  }
}
```

| Error Class            | When Thrown                          |
| ---------------------- | ------------------------------------ |
| `AgentWallexError`     | Base class for all API errors        |
| `PolicyViolationError` | Transaction blocked by policy engine |
| `AuthenticationError`  | Invalid or missing API key           |
| `NotFoundError`        | Resource does not exist              |
| `RateLimitError`       | Rate limit exceeded                  |

## TypeScript Types

All types are exported from the package:

```typescript theme={null}
import type {
  Agent,
  Payment,
  Transaction,
  Policy,
  X402Session,
  WebhookEvent,
} from "@agentwallex/sdk";
```
