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

> Tài liệu tham khảo đầy đủ cho gói @agentwallex/sdk — tác nhân, thanh toán, x402, chính sách và webhook.

## Cài đặt

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

## Khởi tạo Client

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

| Tham số       | Kiểu                        | Mặc định    | Mô tả                                    |
| ------------- | --------------------------- | ----------- | ---------------------------------------- |
| `apiKey`      | `string`                    | Bắt buộc    | Khóa API của bạn (`awx_...`)             |
| `environment` | `"sandbox" \| "production"` | `"sandbox"` | Môi trường đích                          |
| `baseUrl`     | `string`                    | --          | URL cơ sở tùy chỉnh (ghi đè environment) |
| `timeout`     | `number`                    | `30000`     | Timeout yêu cầu tính bằng mili giây      |

## Tác nhân

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

Tạo tác nhân mới với ví MPC được bảo mật.

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

**Trả về:**

| Trường           | Kiểu     | Mô tả                       |
| ---------------- | -------- | --------------------------- |
| `id`             | `string` | Định danh tác nhân duy nhất |
| `name`           | `string` | Tên hiển thị tác nhân       |
| `wallet.address` | `string` | Địa chỉ ví on-chain         |
| `wallet.chain`   | `string` | Định danh chuỗi CAIP-2      |
| `status`         | `string` | `"active"` hoặc `"frozen"`  |
| `createdAt`      | `string` | Dấu thời gian ISO 8601      |

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

Truy xuất tác nhân theo ID.

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

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

Liệt kê tất cả tác nhân trong tài khoản.

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

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

Đóng băng ngay lập tức ví tác nhân, ngăn chặn mọi giao dịch.

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

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

Kích hoạt lại ví tác nhân sau khi đóng băng (phải chờ 10 phút).

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

## Thanh toán

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

Gửi thanh toán on-chain trực tiếp.

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

**Trả về:**

| Trường   | Kiểu     | Mô tả                                  |
| -------- | -------- | -------------------------------------- |
| `id`     | `string` | ID giao dịch                           |
| `hash`   | `string` | Hash giao dịch on-chain                |
| `status` | `string` | `"pending"`, `"confirmed"`, `"failed"` |
| `amount` | `string` | Số tiền đã gửi                         |
| `token`  | `string` | Ký hiệu token                          |
| `fee`    | `string` | Phí gas mạng đã trả                    |

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

Lấy chi tiết và trạng thái giao dịch.

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

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

Liệt kê giao dịch cho tác nhân.

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

## Thanh toán nhỏ x402

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

Tạo phiên thanh toán x402 với ngân sách chi tiêu.

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

Kiểm tra xem URL mục tiêu có hỗ trợ thương lượng thanh toán x402 không.

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

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

Thương lượng và hoàn thành một thanh toán 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)`

Thanh toán sử dụng ngân sách phiên hiện có.

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

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

Tạo wrapper HTTP fetch tự động xử lý thách thức 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();
```

Bộ chặn:

1. Đọc header `PAYMENT-REQUIRED` từ phản hồi 402
2. Gửi thanh toán qua AgentWallex
3. Thử lại yêu cầu với header `PAYMENT-SIGNATURE`

## Chính sách

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

Cập nhật chính sách chi tiêu của tác nhân.

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

Lấy chính sách hiện tại của tác nhân.

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

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

Áp dụng mẫu chính sách cho tác nhân.

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

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

Tạo mẫu chính sách có thể tái sử dụng.

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

## Webhook

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

Đăng ký endpoint 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",
});
```

## Xử lý Lỗi

SDK cung cấp các lớp lỗi có kiểu:

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

| Lớp Lỗi                | Khi nào được ném                         |
| ---------------------- | ---------------------------------------- |
| `AgentWallexError`     | Lớp cơ sở cho tất cả lỗi API             |
| `PolicyViolationError` | Giao dịch bị chặn bởi công cụ chính sách |
| `AuthenticationError`  | Khóa API không hợp lệ hoặc bị thiếu      |
| `NotFoundError`        | Tài nguyên không tồn tại                 |
| `RateLimitError`       | Vượt quá giới hạn tốc độ                 |

## Kiểu TypeScript

Tất cả kiểu được xuất từ gói:

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