SDK Reference
Complete TypeScript SDK reference for server-side integration with Wallgent.
Installation
pnpm add @wallgent/sdkInitialization
import { Wallgent } from '@wallgent/sdk';
// Production
const wg = new Wallgent('wg_live_your_key_here');
// Sandbox with custom base URL
const wg = new Wallgent('wg_test_your_key_here', {
baseUrl: 'http://localhost:3000',
});The SDK determines the environment from the key prefix: wg_live_ for production, wg_test_ for sandbox.
Wallets
Create a Wallet
const wallet = await wg.wallets.create({
name: 'Research Agent',
agentName: 'research-bot',
metadata: { department: 'engineering' },
});
// wallet.id: "wal_01J..."Get a Wallet
const wallet = await wg.wallets.get('wal_01J_wallet_id');Get Balance
const balance = await wg.wallets.getBalance('wal_01J_wallet_id');
// { available: "250.00", currency: "USD" }Fund a Wallet
await wg.wallets.fund('wal_01J_wallet_id', {
amount: '1000.00',
});List Wallets
const result = await wg.wallets.list();
// { data: Wallet[], cursor?: string, hasMore: boolean }Payments
Send a Payment
const payment = await wg.payments.send({
fromWalletId: 'wal_01J_source',
toWalletId: 'wal_01J_dest',
amount: '50.00',
description: 'Monthly SaaS subscription',
idempotencyKey: 'pay_unique_key_123',
});
// payment.id: "txn_01J..."
// payment.state: "POSTED"The idempotencyKey is optional but recommended. Duplicate requests with the same key return the cached response instead of creating a new transaction.
Get a Payment
const payment = await wg.payments.get('txn_01J_transaction_id');List Payments
const payments = await wg.payments.list();Agents
Create an Agent
Creates a new AI agent with its own wallet and a wallet-scoped API key. The apiKey secret is returned only on creation.
const agent = await wg.agents.create({
name: 'Research Bot',
permissions: ['wallets:read', 'payments:write'],
});
// agent.id: "wal_01J..." (the wallet ID doubles as the agent ID)
// agent.apiKey: "wg_test_..." (save this — shown once)
// agent.apiKeyId: "key_01J..."
// agent.balance: "0.00"List Agents
const result = await wg.agents.list({ limit: 50 });
// { data: AgentBudget[], cursor: string | null, hasMore: boolean }Retrieve an Agent
const agent = await wg.agents.retrieve('wal_01J_agent_id');
// agent.status: "ACTIVE" | "FROZEN"
// agent.balance: "125.00"Adjust Budget
Positive amounts fund the agent from the org wallet; negative amounts return funds to the org wallet.
const result = await wg.agents.adjustBudget('wal_01J_agent_id', { amount: 50 });
// { id, adjustment: 50, newBalance: "175.00", currency: "USD" }
// Claw back $25:
await wg.agents.adjustBudget('wal_01J_agent_id', { amount: -25 });Pause and Resume
// Freeze the wallet — no outgoing payments allowed
await wg.agents.pause('wal_01J_agent_id');
// Unfreeze and allow payments again
await wg.agents.resume('wal_01J_agent_id');Rotate API Key
const result = await wg.agents.rotateKey('wal_01J_agent_id');
// { apiKey: "wg_test_...", apiKeyId: "key_new...", revokedKeyId: "key_old..." }Delete Agent
Deletes the agent, sweeps remaining funds back to the org wallet, and revokes all API keys.
const result = await wg.agents.delete('wal_01J_agent_id');
// { deleted: true, sweptAmount: "125.00" }Agent Network
Pay Another Agent
Send funds to any agent by their Wallgent address (wg_...). Instant, zero fees.
const result = await wg.network.payAgent({
toAddress: 'wg_01J_recipient_address',
amount: '25.00',
description: 'Data processing fee',
});
// { transactionId, from, to, toAddress, amount: "25.00", fees: "0.00" }Search Agent Directory
const directory = await wg.network.searchDirectory('analytics');
// { data: [{ walletId, name, agentName, wallgentAddress }] }
for (const entry of directory.data) {
console.log(`${entry.name} — ${entry.wallgentAddress}`);
}Policies
Create a Policy
const policy = await wg.policies.create('wal_01J_wallet_id', {
name: 'Spending Guard',
maxTransactionAmount: '100.00',
dailySpendingLimit: '500.00',
approvedRecipients: ['wal_vendor_a', 'wal_vendor_b'],
});List Policies
const policies = await wg.policies.list('wal_01J_wallet_id');Update a Policy
await wg.policies.update('pol_01J_policy_id', {
dailySpendingLimit: '1000.00',
enabled: true,
});Delete a Policy
await wg.policies.delete('pol_01J_policy_id');Webhooks
Create a Webhook
const webhook = await wg.webhooks.create({
url: 'https://your-app.com/webhooks/wallgent',
events: ['payment.completed', 'wallet.funded', 'policy.denied'],
});List Webhooks
const webhooks = await wg.webhooks.list();Update a Webhook
await wg.webhooks.update('hook_01J_webhook_id', {
enabled: false,
});Delete a Webhook
await wg.webhooks.delete('hook_01J_webhook_id');Transfers
Deposit
const deposit = await wg.transfers.deposit({
walletId: 'wal_01J...',
amount: '1000.00',
currency: 'USD',
bankAccountId: 'ba_01J...',
});Withdraw
const withdrawal = await wg.transfers.withdraw({
walletId: 'wal_01J...',
amount: '500.00',
currency: 'USD',
bankAccountId: 'ba_01J...',
});Internal Transfer
const transfer = await wg.transfers.internal({
fromWalletId: 'wal_01J_ops',
toWalletId: 'wal_01J_savings',
amount: '250.00',
description: 'Move to savings',
});List Transfers
const result = await wg.transfers.list({
walletId: 'wal_01J...',
direction: 'DEPOSIT',
limit: 20,
});Get Transfer
const transfer = await wg.transfers.get('xfr_01J...');Cards
Create a Card
const card = await wg.cards.create({
walletId: 'wal_01J...',
type: 'PERSISTENT',
spendingLimits: [
{ amount: '500.00', interval: 'monthly' },
],
});List Cards
const cards = await wg.cards.list({ walletId: 'wal_01J...' });Get Card Details (Sensitive)
const details = await wg.cards.getDetails('crd_01J...');
// { number: "4242...", cvc: "123", expMonth: 12, expYear: 2027 }Requires cards:sensitive_read permission.
Freeze / Unfreeze
await wg.cards.update('crd_01J...', { status: 'INACTIVE' }); // freeze
await wg.cards.update('crd_01J...', { status: 'ACTIVE' }); // unfreezeCancel
await wg.cards.cancel('crd_01J...');Payment Links
Create a Payment Link
const link = await wg.paymentLinks.create({
walletId: 'wal_01J...',
amount: '250.00',
description: 'Freelance payment',
expiresAt: '2026-03-01T00:00:00Z',
});
// link.slug: "abc123"List Payment Links
const links = await wg.paymentLinks.list({
walletId: 'wal_01J...',
status: 'ACTIVE',
});Cancel a Payment Link
await wg.paymentLinks.cancel('pyl_01J...');Customers
Create a Customer
const customer = await wg.customers.create({
email: 'jane@acme.com',
name: 'Jane Smith',
companyName: 'Acme Corp',
});List Customers
const customers = await wg.customers.list();Setup Payment Method
const setup = await wg.customers.setupPaymentMethod('cus_01J...');
// setup.url: "https://checkout.stripe.com/..."Invoices
Create an Invoice
const invoice = await wg.invoices.create({
walletId: 'wal_01J...',
customerId: 'cus_01J...',
lineItems: [
{ description: 'API calls (10,000)', unitPrice: '25.00' },
{ description: 'Data processing', quantity: 3, unitPrice: '15.00' },
],
memo: 'Services for January 2026',
});List Invoices
const invoices = await wg.invoices.list({
walletId: 'wal_01J...',
status: 'FINALIZED',
});Finalize
const result = await wg.invoices.finalize('inv_01J...');
// result.slug, result.checkoutUrlAuto-Charge Customer
await wg.invoices.charge({
walletId: 'wal_01J...',
customerId: 'cus_01J...',
amount: '99.00',
description: 'Monthly subscription',
recurring: { interval: 'monthly' },
});Void / Refund
await wg.invoices.void('inv_01J...');
await wg.invoices.refund('inv_01J...');API Keys
Create an API Key
const key = await wg.apiKeys.create({
name: 'CI Deploy Key',
permissions: ['wallets:read', 'payments:write'],
environment: 'PRODUCTION',
});
// key.secret: "wg_live_..." (save this — shown once)
// key.id: "key_01J..."List API Keys
const result = await wg.apiKeys.list({ limit: 25 });
for (const key of result.data) {
console.log(`${key.name} — ${key.status} — ${key.environment}`);
}Revoke an API Key
await wg.apiKeys.revoke('key_01J_key_id');Approvals
When a policy has HUMAN_IN_THE_LOOP enabled, payments create an approval request instead of posting immediately.
List Pending Approvals
const result = await wg.approvals.list({ status: 'PENDING' });
for (const approval of result.data) {
console.log(`${approval.id}: ${approval.transactionDetails.amount} to ${approval.transactionDetails.recipient}`);
}Retrieve an Approval
const approval = await wg.approvals.retrieve('del_01J_approval_id');
// approval.status: "PENDING" | "APPROVED" | "REJECTED" | "EXPIRED"Approve or Reject
// Approve — payment executes immediately
await wg.approvals.approve('del_01J_approval_id');
// Reject with a reason
await wg.approvals.reject('del_01J_approval_id', 'Amount exceeds monthly budget review threshold');Delegations
Delegations let you grant another organization's API key scoped access to specific wallets.
List Delegations
const result = await wg.delegations.list({ walletId: 'wal_01J...' });Create a Delegation
const delegation = await wg.delegations.create({
walletId: 'wal_01J_ops',
delegateApiKeyId: 'key_01J_partner_key',
permissions: ['wallets:read', 'payments:write'],
walletScope: ['wal_01J_ops'],
expiresAt: '2026-06-01T00:00:00Z',
});Delete a Delegation
await wg.delegations.delete('del_01J_delegation_id');Audit Logs
List Audit Log Entries
const result = await wg.auditLogs.list({
action: 'wallet.created',
resource: 'wallet',
from: '2026-01-01T00:00:00Z',
to: '2026-02-01T00:00:00Z',
limit: 100,
});
for (const entry of result.data) {
console.log(`[${entry.createdAt}] ${entry.actorType} — ${entry.action} on ${entry.resource}`);
}Available filter params: action, resource, actorId, from, to, limit, cursor.
Merchants
For organizations accepting payments as a merchant (receiving invoices, collecting funds).
Settlement Overview
const overview = await wg.merchants.getSettlementOverview();
// overview.balance: { amount: "1250.00", currency: "USD", status: "AVAILABLE" }
// overview.today: { count: 12, total: "340.00" }
// overview.month: { count: 187, total: "5820.00" }List Payments
const payments = await wg.merchants.listPayments({
limit: 50,
offset: 0,
startDate: '2026-01-01',
endDate: '2026-01-31',
});
// { data: MerchantPayment[], total: number, limit: number, offset: number }Analytics
const analytics = await wg.merchants.getAnalytics();
for (const point of analytics.volumeTrend) {
console.log(`${point.date}: ${point.count} payments, $${point.volume}`);
}Pagination Utilities
The SDK includes helpers for iterating cursor-paginated endpoints without manual cursor management.
autoPaginate() — Async Generator
Yields every item across all pages. Ideal for large datasets — streams items one at a time without loading everything into memory.
import { autoPaginate } from '@wallgent/sdk';
for await (const wallet of autoPaginate((cursor) =>
wg.wallets.list({ cursor, limit: 100 })
)) {
console.log(wallet.id, wallet.name);
}collectAll() — Collect to Array
Fetches all pages and returns a flat array. Prefer autoPaginate() for large datasets.
import { collectAll } from '@wallgent/sdk';
const allWallets = await collectAll((cursor) =>
wg.wallets.list({ cursor, limit: 100 })
);
console.log(`Total wallets: ${allWallets.length}`);Both helpers work with any paginated resource: wg.wallets.list, wg.agents.list, wg.auditLogs.list, etc.
Webhook Signature Verification
Wallgent signs every webhook delivery with HMAC-SHA256. Verify the signature before processing the payload.
import { verifyWebhookSignature } from '@wallgent/sdk';
// Express example
app.post('/webhooks/wallgent', (req, res) => {
const rawBody = req.body; // must be the raw Buffer/string, not parsed JSON
const signature = req.headers['wallgent-signature'] as string;
const secret = process.env.WALLGENT_WEBHOOK_SECRET!;
const isValid = verifyWebhookSignature(rawBody, signature, secret);
if (!isValid) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(rawBody.toString());
console.log('Event:', event.type, event.data);
res.status(200).send('OK');
});The signature header format is sha256=<hex>. The function uses timingSafeEqual to prevent timing attacks.
Realtime (WebSocket)
Subscribe to real-time events via WebSocket using the WallgentRealtime class.
Constructor
import { WallgentRealtime } from '@wallgent/sdk';
const realtime = new WallgentRealtime(
'wg_test_your_key_here',
'https://api.wallgent.com', // http(s) is automatically converted to ws(s)
);Connect
connect() returns a Promise that resolves when the connection is open. The client reconnects automatically with exponential backoff (up to 10 attempts, max 30s delay).
await realtime.connect();Subscribe to Events
on(event, handler) registers a listener and returns an unsubscribe function.
const unsubscribePayment = realtime.on('payment.completed', (data) => {
console.log('Payment completed:', data.transactionId);
});
realtime.on('wallet.funded', (data) => {
console.log('Funded:', data.amount);
});
realtime.on('policy.denied', (data) => {
console.log('Policy blocked:', data.reason);
});
// Unsubscribe later
unsubscribePayment();Wildcard Listener
Use '*' to receive all events. The event name is injected as _event on the data object.
realtime.on('*', (data) => {
console.log(`Event: ${data._event}`, data);
});Disconnect
Stops reconnection, closes the socket, and clears all listeners.
realtime.disconnect();Events are delivered with the same payload structure as webhooks. See the Webhook Event Catalog for all available events.
Error Handling
The SDK throws typed errors that you can catch and inspect:
import {
WallgentError,
InsufficientFundsError,
PolicyDeniedError,
WalletFrozenError,
ApprovalRequiredError,
} from '@wallgent/sdk';
try {
await wg.payments.send({
fromWalletId: 'wal_source',
toWalletId: 'wal_dest',
amount: '10000.00',
description: 'Large purchase',
});
} catch (error) {
if (error instanceof ApprovalRequiredError) {
console.log('Awaiting approval:', error.message);
// error.code: "APPROVAL_REQUIRED" (HTTP 202)
} else if (error instanceof PolicyDeniedError) {
console.log('Policy blocked:', error.message);
// error.code: "POLICY_DENIED"
} else if (error instanceof InsufficientFundsError) {
console.log('Not enough funds:', error.message);
// error.code: "INSUFFICIENT_FUNDS"
} else if (error instanceof WalletFrozenError) {
console.log('Wallet is frozen:', error.message);
} else if (error instanceof WallgentError) {
console.log('API error:', error.code, error.message, error.statusCode);
}
}Error Classes
All errors extend WallgentError which exposes code, message, statusCode, and optional details.
| Code | HTTP Status | Class |
|---|---|---|
INSUFFICIENT_FUNDS | 402 | InsufficientFundsError |
POLICY_DENIED | 403 | PolicyDeniedError |
WALLET_NOT_FOUND | 404 | WalletNotFoundError |
INVALID_AMOUNT | 400 | InvalidAmountError |
ENVIRONMENT_MISMATCH | 403 | EnvironmentMismatchError |
RATE_LIMIT_EXCEEDED | 429 | RateLimitExceededError |
UNAUTHORIZED | 401 | UnauthorizedError |
VALIDATION_ERROR | 400 | ValidationError |
MERCHANT_NOT_FOUND | 404 | MerchantNotFoundError |
MERCHANT_SUSPENDED | 403 | MerchantSuspendedError |
CLOSED_LOOP_UNAVAILABLE | 400 | ClosedLoopUnavailableError |
WALLET_FROZEN | 403 | WalletFrozenError |
APPROVAL_REQUIRED | 202 | ApprovalRequiredError |
TRANSFER_NOT_FOUND | 404 | TransferNotFoundError |
WEBHOOK_NOT_FOUND | 404 | WebhookNotFoundError |
POLICY_NOT_FOUND | 404 | PolicyNotFoundError |
WALLET_LIMIT_EXCEEDED | 403 | WalletLimitExceededError |
API_KEY_REVOKED | 401 | ApiKeyRevokedError |
IDEMPOTENCY_KEY_REUSE | 409 | IdempotencyKeyReuseError |
REVERSAL_NOT_ALLOWED | 422 | ReversalNotAllowedError |
PAYMENT_LINK_NOT_FOUND | 404 | PaymentLinkNotFoundError |
BATCH_PARTIAL_FAILURE | 207 | BatchPartialFailureError |
SANDBOX_ONLY | 403 | SandboxOnlyError |
CARD_NOT_FOUND | 404 | CardNotFoundError |