> ## 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、ポリシー、Webhook。

## インストール

<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（環境設定をオーバーライド） |
| `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` | 支払われたネットワークガス手数料                     |

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

1回の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 },
});
```

## Webhook

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