跳转到主要内容

安装

npm install @agentwallex/sdk

客户端初始化

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)
});
参数类型默认值说明
apiKeystring必填您的 API 密钥(awx_...
environment"sandbox" | "production""sandbox"目标环境
baseUrlstring自定义基础 URL(覆盖 environment)
timeoutnumber30000请求超时时间(毫秒)

代理

aw.agents.create(params)

创建一个带有 MPC 安全钱包的新代理。
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" },
});
返回值:
字段类型说明
idstring唯一代理标识符
namestring代理显示名称
wallet.addressstring链上钱包地址
wallet.chainstringCAIP-2 链标识符
statusstring"active""frozen"
createdAtstringISO 8601 时间戳

aw.agents.get(agentId)

通过 ID 获取代理。
const agent = await aw.agents.get("agent_abc123");

aw.agents.list(params?)

列出您账户的所有代理。
const { agents, pagination } = await aw.agents.list({
  limit: 20,
  offset: 0,
  status: "active",
});

aw.agents.freeze(agentId)

立即冻结代理的钱包,阻止所有交易。
await aw.agents.freeze("agent_abc123");

aw.agents.unfreeze(agentId)

在冻结后重新启用代理的钱包(需遵守 10 分钟冷却期)。
await aw.agents.unfreeze("agent_abc123");

支付

aw.payments.send(params)

发送直接链上支付。
const tx = await aw.payments.send({
  agentId: "agent_abc123",
  to: "0xRecipientAddress",
  amount: "50.00",
  token: "USDC",
  memo: "Payment for API access",
});
返回值:
字段类型说明
idstring交易 ID
hashstring链上交易哈希
statusstring"pending""confirmed""failed"
amountstring发送金额
tokenstring代币符号
feestring已支付的网络 Gas 费用

aw.payments.get(transactionId)

获取交易详情和状态。
const tx = await aw.payments.get("tx_xyz789");

aw.payments.list(params)

列出代理的交易。
const { transactions } = await aw.payments.list({
  agentId: "agent_abc123",
  limit: 50,
  status: "confirmed",
});

x402 微支付

aw.x402.createSession(params)

创建一个带有消费预算的 x402 支付会话。
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 支付协商。
const info = await aw.x402.check({
  url: "https://paid-api.example.com/v1/data",
});

aw.x402.pay(params)

协商并完成一次 x402 支付。
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)

使用现有会话预算支付。
await aw.x402.sessionPay(session.id, {
  targetUrl: "https://paid-api.example.com/v1/data",
});

aw.x402.httpInterceptor(params)

创建一个 HTTP fetch 包装器,自动处理 x402 v2 挑战:
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)

更新代理的消费策略。
await aw.policies.update("agent_abc123", {
  maxTransactionAmount: "200",
  dailyLimit: "2000",
  allowedAddresses: ["0xAddr1", "0xAddr2"],
  velocityLimit: { maxCount: 100, windowSeconds: 3600 },
});

aw.policies.get(agentId)

获取代理的当前策略。
const policies = await aw.policies.get("agent_abc123");

aw.policies.applyTemplate(agentId, templateName)

将策略模板应用到代理。
await aw.policies.applyTemplate("agent_abc123", "conservative");

aw.policies.createTemplate(name, rules)

创建可复用的策略模板。
await aw.policies.createTemplate("my-template", {
  maxTransactionAmount: "200",
  dailyLimit: "2000",
  allowedTokens: ["USDC"],
  velocityLimit: { maxCount: 50, windowSeconds: 3600 },
});

Webhooks

aw.webhooks.create(params)

注册 Webhook 端点。
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 提供了类型化的错误类:
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交易被策略引擎阻止
AuthenticationErrorAPI 密钥无效或缺失
NotFoundError资源不存在
RateLimitError超过速率限制

TypeScript 类型

所有类型均从包中导出:
import type {
  Agent,
  Payment,
  Transaction,
  Policy,
  X402Session,
  WebhookEvent,
} from "@agentwallex/sdk";