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

# SDK de TypeScript

> Referencia completa del paquete @agentwallex/sdk — agentes, pagos, x402, políticas y webhooks.

## Instalación

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

## Inicialización del cliente

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

| Parámetro     | Tipo                        | Predeterminado | Descripción                               |
| ------------- | --------------------------- | -------------- | ----------------------------------------- |
| `apiKey`      | `string`                    | Requerido      | Su clave API (`awx_...`)                  |
| `environment` | `"sandbox" \| "production"` | `"sandbox"`    | Entorno objetivo                          |
| `baseUrl`     | `string`                    | --             | URL base personalizada (anula el entorno) |
| `timeout`     | `number`                    | `30000`        | Timeout de solicitud en milisegundos      |

## Agentes

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

Cree un nuevo agente con una billetera con seguridad 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" },
});
```

**Retorna:**

| Campo            | Tipo     | Descripción                     |
| ---------------- | -------- | ------------------------------- |
| `id`             | `string` | Identificador único del agente  |
| `name`           | `string` | Nombre visible del agente       |
| `wallet.address` | `string` | Dirección de billetera on-chain |
| `wallet.chain`   | `string` | Identificador de cadena CAIP-2  |
| `status`         | `string` | `"active"` o `"frozen"`         |
| `createdAt`      | `string` | Marca de tiempo ISO 8601        |

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

Recupere un agente por ID.

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

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

Liste todos los agentes de su cuenta.

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

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

Congele inmediatamente la billetera de un agente, impidiendo todas las transacciones.

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

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

Reactive la billetera de un agente después de un congelamiento (sujeto a período de enfriamiento de 10 minutos).

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

## Pagos

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

Envíe un pago directo on-chain.

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

**Retorna:**

| Campo    | Tipo     | Descripción                            |
| -------- | -------- | -------------------------------------- |
| `id`     | `string` | ID de transacción                      |
| `hash`   | `string` | Hash de transacción on-chain           |
| `status` | `string` | `"pending"`, `"confirmed"`, `"failed"` |
| `amount` | `string` | Monto enviado                          |
| `token`  | `string` | Símbolo del token                      |
| `fee`    | `string` | Tarifa de gas de red pagada            |

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

Obtenga los detalles y estado de una transacción.

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

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

Liste las transacciones de un agente.

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

## Micropagos x402

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

Cree una sesión de pago x402 con un presupuesto de gasto.

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

Verifique si una URL objetivo soporta negociación de pago x402.

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

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

Negocie y complete un pago 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)`

Pague utilizando un presupuesto de sesión existente.

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

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

Cree un wrapper de HTTP fetch que maneja automáticamente los desafíos 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();
```

El interceptor:

1. Lee el encabezado `PAYMENT-REQUIRED` de una respuesta 402
2. Envía el pago mediante AgentWallex
3. Reintenta la solicitud con el encabezado `PAYMENT-SIGNATURE`

## Políticas

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

Actualice las políticas de gasto de un agente.

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

Obtenga las políticas actuales de un agente.

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

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

Aplique una plantilla de política a un agente.

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

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

Cree una plantilla de política reutilizable.

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

Registre un endpoint de 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",
});
```

## Manejo de errores

El SDK proporciona clases de error tipadas:

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

| Clase de error         | Cuándo se lanza                                 |
| ---------------------- | ----------------------------------------------- |
| `AgentWallexError`     | Clase base para todos los errores de API        |
| `PolicyViolationError` | Transacción bloqueada por el motor de políticas |
| `AuthenticationError`  | Clave API inválida o faltante                   |
| `NotFoundError`        | El recurso no existe                            |
| `RateLimitError`       | Límite de tasa excedido                         |

## Tipos TypeScript

Todos los tipos se exportan desde el paquete:

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