> ## 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, 정책, 웹훅을 포함합니다.

## 설치

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

하나의 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 },
});
```

## 웹훅

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

웹훅 엔드포인트를 등록합니다.

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