跳轉到主要內容

安裝

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)

建立自動處理 x402 v2 挑戰的 HTTP fetch 包裝器:
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交易被策略引擎阻止
AuthenticationError無效或缺少 API 金鑰
NotFoundError資源不存在
RateLimitError超過速率限制

TypeScript 型別

所有型別都從套件中匯出:
import type {
  Agent,
  Payment,
  Transaction,
  Policy,
  X402Session,
  WebhookEvent,
} from "@agentwallex/sdk";