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

建立自動處理 x402 v2 挑戰的 HTTP fetch 包裝器：

```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";
```
