Chuyển đến nội dung chính

Cài đặt

npm install @agentwallex/sdk

Khởi tạo Client

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)
});
Tham sốKiểuMặc địnhMô tả
apiKeystringBắt buộcKhóa API của bạn (awx_...)
environment"sandbox" | "production""sandbox"Môi trường đích
baseUrlstringURL cơ sở tùy chỉnh (ghi đè environment)
timeoutnumber30000Timeout yêu cầu tính bằng mili giây

Tác nhân

aw.agents.create(params)

Tạo tác nhân mới với ví MPC được bảo mật.
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" },
});
Trả về:
TrườngKiểuMô tả
idstringĐịnh danh tác nhân duy nhất
namestringTên hiển thị tác nhân
wallet.addressstringĐịa chỉ ví on-chain
wallet.chainstringĐịnh danh chuỗi CAIP-2
statusstring"active" hoặc "frozen"
createdAtstringDấu thời gian ISO 8601

aw.agents.get(agentId)

Truy xuất tác nhân theo ID.
const agent = await aw.agents.get("agent_abc123");

aw.agents.list(params?)

Liệt kê tất cả tác nhân trong tài khoản.
const { agents, pagination } = await aw.agents.list({
  limit: 20,
  offset: 0,
  status: "active",
});

aw.agents.freeze(agentId)

Đóng băng ngay lập tức ví tác nhân, ngăn chặn mọi giao dịch.
await aw.agents.freeze("agent_abc123");

aw.agents.unfreeze(agentId)

Kích hoạt lại ví tác nhân sau khi đóng băng (phải chờ 10 phút).
await aw.agents.unfreeze("agent_abc123");

Thanh toán

aw.payments.send(params)

Gửi thanh toán on-chain trực tiếp.
const tx = await aw.payments.send({
  agentId: "agent_abc123",
  to: "0xRecipientAddress",
  amount: "50.00",
  token: "USDC",
  memo: "Payment for API access",
});
Trả về:
TrườngKiểuMô tả
idstringID giao dịch
hashstringHash giao dịch on-chain
statusstring"pending", "confirmed", "failed"
amountstringSố tiền đã gửi
tokenstringKý hiệu token
feestringPhí gas mạng đã trả

aw.payments.get(transactionId)

Lấy chi tiết và trạng thái giao dịch.
const tx = await aw.payments.get("tx_xyz789");

aw.payments.list(params)

Liệt kê giao dịch cho tác nhân.
const { transactions } = await aw.payments.list({
  agentId: "agent_abc123",
  limit: 50,
  status: "confirmed",
});

Thanh toán nhỏ x402

aw.x402.createSession(params)

Tạo phiên thanh toán x402 với ngân sách chi tiêu.
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)

Kiểm tra xem URL mục tiêu có hỗ trợ thương lượng thanh toán x402 không.
const info = await aw.x402.check({
  url: "https://paid-api.example.com/v1/data",
});

aw.x402.pay(params)

Thương lượng và hoàn thành một thanh toán 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)

Thanh toán sử dụng ngân sách phiên hiện có.
await aw.x402.sessionPay(session.id, {
  targetUrl: "https://paid-api.example.com/v1/data",
});

aw.x402.httpInterceptor(params)

Tạo wrapper HTTP fetch tự động xử lý thách thức 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();
Bộ chặn:
  1. Đọc header PAYMENT-REQUIRED từ phản hồi 402
  2. Gửi thanh toán qua AgentWallex
  3. Thử lại yêu cầu với header PAYMENT-SIGNATURE

Chính sách

aw.policies.update(agentId, policies)

Cập nhật chính sách chi tiêu của tác nhân.
await aw.policies.update("agent_abc123", {
  maxTransactionAmount: "200",
  dailyLimit: "2000",
  allowedAddresses: ["0xAddr1", "0xAddr2"],
  velocityLimit: { maxCount: 100, windowSeconds: 3600 },
});

aw.policies.get(agentId)

Lấy chính sách hiện tại của tác nhân.
const policies = await aw.policies.get("agent_abc123");

aw.policies.applyTemplate(agentId, templateName)

Áp dụng mẫu chính sách cho tác nhân.
await aw.policies.applyTemplate("agent_abc123", "conservative");

aw.policies.createTemplate(name, rules)

Tạo mẫu chính sách có thể tái sử dụng.
await aw.policies.createTemplate("my-template", {
  maxTransactionAmount: "200",
  dailyLimit: "2000",
  allowedTokens: ["USDC"],
  velocityLimit: { maxCount: 50, windowSeconds: 3600 },
});

Webhook

aw.webhooks.create(params)

Đăng ký endpoint 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",
});

Xử lý Lỗi

SDK cung cấp các lớp lỗi có kiểu:
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}`);
  }
}
Lớp LỗiKhi nào được ném
AgentWallexErrorLớp cơ sở cho tất cả lỗi API
PolicyViolationErrorGiao dịch bị chặn bởi công cụ chính sách
AuthenticationErrorKhóa API không hợp lệ hoặc bị thiếu
NotFoundErrorTài nguyên không tồn tại
RateLimitErrorVượt quá giới hạn tốc độ

Kiểu TypeScript

Tất cả kiểu được xuất từ gói:
import type {
  Agent,
  Payment,
  Transaction,
  Policy,
  X402Session,
  WebhookEvent,
} from "@agentwallex/sdk";