> ## 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

> @agentwallex/sdk 包的完整参考 — 代理、支付、x402、策略和 Webhooks。

## 安装

<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>

## 客户端初始化

```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)
});
```

| 参数            | 类型                          | 默认值         | 说明                        |
| ------------- | --------------------------- | ----------- | ------------------------- |
| `apiKey`      | `string`                    | 必填          | 您的 API 密钥（`awx_...`）      |
| `environment` | `"sandbox" \| "production"` | `"sandbox"` | 目标环境                      |
| `baseUrl`     | `string`                    | --          | 自定义基础 URL（覆盖 environment） |
| `timeout`     | `number`                    | `30000`     | 请求超时时间（毫秒）                |

## 代理

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

创建一个带有 MPC 安全钱包的新代理。

```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" },
});
```

**返回值：**

| 字段               | 类型       | 说明                      |
| ---------------- | -------- | ----------------------- |
| `id`             | `string` | 唯一代理标识符                 |
| `name`           | `string` | 代理显示名称                  |
| `wallet.address` | `string` | 链上钱包地址                  |
| `wallet.chain`   | `string` | CAIP-2 链标识符             |
| `status`         | `string` | `"active"` 或 `"frozen"` |
| `createdAt`      | `string` | ISO 8601 时间戳            |

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

通过 ID 获取代理。

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

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

列出您账户的所有代理。

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

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

立即冻结代理的钱包，阻止所有交易。

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

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

在冻结后重新启用代理的钱包（需遵守 10 分钟冷却期）。

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

## 支付

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

发送直接链上支付。

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

**返回值：**

| 字段       | 类型       | 说明                                   |
| -------- | -------- | ------------------------------------ |
| `id`     | `string` | 交易 ID                                |
| `hash`   | `string` | 链上交易哈希                               |
| `status` | `string` | `"pending"`、`"confirmed"`、`"failed"` |
| `amount` | `string` | 发送金额                                 |
| `token`  | `string` | 代币符号                                 |
| `fee`    | `string` | 已支付的网络 Gas 费用                        |

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

获取交易详情和状态。

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

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

列出代理的交易。

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

## x402 微支付

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

创建一个带有消费预算的 x402 支付会话。

```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)`

检查目标 URL 是否支持 x402 支付协商。

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

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

协商并完成一次 x402 支付。

```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)`

使用现有会话预算支付。

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

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

创建一个 HTTP fetch 包装器，自动处理 x402 v2 挑战：

```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();
```

拦截器会：

1. 从 402 响应中读取 `PAYMENT-REQUIRED` 头部
2. 通过 AgentWallex 提交支付
3. 使用 `PAYMENT-SIGNATURE` 头部重试请求

## 策略

### `aw.policies.update(agentId, 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)`

获取代理的当前策略。

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

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

将策略模板应用到代理。

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

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

创建可复用的策略模板。

```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)`

注册 Webhook 端点。

```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",
});
```

## 错误处理

SDK 提供了类型化的错误类：

```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}`);
  }
}
```

| 错误类                    | 触发条件         |
| ---------------------- | ------------ |
| `AgentWallexError`     | 所有 API 错误的基类 |
| `PolicyViolationError` | 交易被策略引擎阻止    |
| `AuthenticationError`  | API 密钥无效或缺失  |
| `NotFoundError`        | 资源不存在        |
| `RateLimitError`       | 超过速率限制       |

## TypeScript 类型

所有类型均从包中导出：

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