Agent SDK Reference
Complete API reference for @veridex/agentic-payments — the autonomous payment, identity, and reputation layer for AI agents.
Installation
npm install @veridex/agentic-paymentsCore: AgentWallet
The AgentWallet is the central orchestration class. It manages session keys, multi-protocol payment negotiation, on-chain identity (ERC-8004), reputation, trust gates, agent discovery, and monitoring.
createAgentWallet
Factory function that creates and initializes an AgentWallet.
import { createAgentWallet } from '@veridex/agentic-payments';
const agent = await createAgentWallet(config);Parameters:
interface AgentWalletConfig {
masterCredential: {
credentialId: string;
publicKeyX: bigint;
publicKeyY: bigint;
keyHash: string;
};
session: {
dailyLimitUSD: number;
perTransactionLimitUSD: number;
expiryHours: number;
allowedChains: number[]; // Wormhole chain IDs
};
erc8004?: ERC8004Config;
relayerUrl?: string;
relayerApiKey?: string;
x402?: X402ClientConfig;
mcp?: { enabled: boolean };
}
interface ERC8004Config {
enabled: boolean;
testnet?: boolean; // Use testnet registry addresses (default: false)
registryProvider?: any; // Custom ethers provider for registry chain
agentId?: bigint; // Pre-registered agent ID
minReputationScore?: number; // Minimum reputation (0-100) for trust gate
trustedReviewers?: string[]; // Only count feedback from these addresses
}Example:
const agent = await createAgentWallet({
masterCredential: {
credentialId: 'abc123',
publicKeyX: BigInt('0x...'),
publicKeyY: BigInt('0x...'),
keyHash: '0x...',
},
session: {
dailyLimitUSD: 100,
perTransactionLimitUSD: 25,
expiryHours: 24,
allowedChains: [10004], // Base Sepolia
},
erc8004: {
enabled: true,
testnet: true,
minReputationScore: 30,
},
relayerUrl: 'https://relayer.veridex.network',
});agent.fetch
Make an HTTP request with automatic x402 payment handling. If the server responds with 402 Payment Required, the agent automatically negotiates and pays.
const response = await agent.fetch(url, options?);Parameters:
| Parameter | Type | Description |
|---|---|---|
url | string | URL to fetch |
options | RequestInit | Standard fetch options |
Returns: Promise<Response>
Example:
// Agent automatically handles 402 Payment Required responses
const response = await agent.fetch('https://paid-api.example.com/market-data');
const data = await response.json();
console.log('Market data:', data);agent.pay
Execute a direct token payment.
const receipt = await agent.pay(params);Parameters:
interface PaymentParams {
chain: number; // Wormhole chain ID (e.g., 10004 for Base Sepolia)
token: string; // Token symbol ('ETH', 'USDC', 'native')
amount: string; // Amount in smallest unit (e.g., '1000000' for 1 USDC)
recipient: string; // Recipient address
protocol?: string; // Payment protocol (default: 'direct')
}Returns:
interface PaymentReceipt {
txHash: string;
status: 'confirmed' | 'pending' | 'failed';
chain: number;
token: string;
amount: bigint;
recipient: string;
protocol: string;
timestamp: number;
}Example:
const receipt = await agent.pay({
chain: 10004, // Base Sepolia
token: 'USDC',
amount: '5000000', // 5 USDC (6 decimals)
recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f5A234',
});
console.log('Tx:', receipt.txHash);
console.log('Status:', receipt.status);agent.getSessionStatus
Get the current session's status including spending limits and usage.
const status = agent.getSessionStatus();Returns:
interface SessionStatus {
isValid: boolean;
keyHash: string;
expiry: number; // Unix timestamp
remainingDailyLimitUSD: number;
totalSpentUSD: number;
masterKeyHash: string;
address: string; // Session wallet address
limits: {
dailyLimitUSD: number;
perTransactionLimitUSD: number;
};
}Example:
const status = agent.getSessionStatus();
console.log('Session valid:', status.isValid);
console.log('Spent today:', `$${status.totalSpentUSD.toFixed(2)}`);
console.log('Remaining:', `$${status.remainingDailyLimitUSD.toFixed(2)}`);
console.log('Wallet:', status.address);agent.getBalance
Get token balances for the session wallet.
const balances = await agent.getBalance(chain?);Parameters:
| Parameter | Type | Description |
|---|---|---|
chain | number | Wormhole chain ID (default: 30 for Base) |
Returns: Promise<TokenBalance[]>
Example:
const balances = await agent.getBalance(10004);
for (const entry of balances) {
console.log(`${entry.token.symbol}: ${entry.formatted}`);
}agent.getMultiChainBalance
Get balances across all supported chains.
const portfolio = await agent.getMultiChainBalance();Returns: Promise<PortfolioBalance>
agent.getPaymentHistory
Get the agent's payment history with optional filtering.
const history = await agent.getPaymentHistory(options?);Parameters:
interface HistoryOptions {
limit?: number;
offset?: number;
chain?: number;
token?: string;
since?: number; // Unix timestamp
}Returns: Promise<PaymentRecord[]>
agent.revokeSession
Revoke the current session key.
await agent.revokeSession();agent.exportAuditLog
Export the agent's payment audit log for compliance.
const log = await agent.exportAuditLog(format?);Parameters:
| Parameter | Type | Description |
|---|---|---|
format | 'json' | 'csv' | Export format (default: 'json') |
Returns: Promise<string>
agent.onSpendingAlert
Register a callback for spending limit alerts.
agent.onSpendingAlert((alert) => {
console.log('Alert:', alert.type, alert.message);
});Alert types:
| Type | Description |
|---|---|
approaching_limit | Spending is near the daily limit |
limit_exceeded | Transaction was blocked by limit |
session_expiring | Session key is about to expire |
agent.getMCPTools
Get MCP tools for integration with AI models (Gemini, Claude, GPT, Cursor). Each tool has a name, description, input schema, and handler function. This is the primary integration point used by the veri_agent to give Gemini function-calling access to wallet operations.
const tools = agent.getMCPTools();Returns: MCPTool[]
interface MCPTool {
name: string; // e.g., 'veridex_pay', 'veridex_balance'
description: string; // Human-readable description
inputSchema: {
type: 'object';
properties: Record<string, any>;
required?: string[];
};
handler: (args: any) => Promise<any>; // Execute the tool
}Available tools:
| Tool Name | Description |
|---|---|
veridex_pay | Execute a token payment (chain, token, amount, recipient) |
veridex_balance | Check wallet balance on a specific chain |
veridex_status | Get session status and spending limits |
veridex_history | Get payment history |
Example — Mapping to Gemini function declarations:
import { FunctionDeclaration, SchemaType } from '@google/generative-ai';
const mcpTools = agent.getMCPTools();
const geminiTools = mcpTools.map(tool => ({
declaration: {
name: tool.name,
description: tool.description,
parameters: {
type: SchemaType.OBJECT,
properties: tool.inputSchema.properties,
required: tool.inputSchema.required || [],
},
},
execute: async (args: any) => {
const result = await tool.handler(args);
// Serialize BigInts for JSON compatibility
return JSON.parse(JSON.stringify(result, (key, value) =>
typeof value === 'bigint' ? value.toString() : value
));
},
}));Example — Mapping to OpenAI/Claude tool format:
const openaiTools = mcpTools.map(tool => ({
type: 'function' as const,
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
},
}));agent.importSession
Import a session key that was provisioned from a frontend dashboard. This enables the human-in-the-loop provisioning flow where a user creates a passkey wallet, configures spending limits, generates a session key, and sends it to the agent backend.
await agent.importSession(sessionData);Parameters:
interface SessionData {
keyHash: string;
encryptedPrivateKey: string;
publicKey: string;
config: {
dailyLimitUSD: number;
perTransactionLimitUSD: number;
expiryTimestamp: number;
allowedChains: number[];
};
masterKeyHash: string;
}Example (from veri_agent):
// Backend receives session data from frontend
app.post('/api/provision', async (req, res) => {
const { sessionData } = req.body;
const wallet = await getAgentWallet();
await wallet.importSession(sessionData);
console.log('Session injected into Wallet.');
res.json({ success: true });
});Session Management
SessionKeyManager
Manages session key lifecycle, spending tracking, and limit enforcement.
import { SessionKeyManager } from '@veridex/agentic-payments';
const manager = new SessionKeyManager();
// Create a session
const session = await manager.createSession(masterCredential, {
dailyLimitUSD: 50,
perTransactionLimitUSD: 10,
expiryTimestamp: Date.now() + 24 * 60 * 60 * 1000,
});
// Check limits before payment
const check = manager.checkLimits(session, amountUSD);
if (check.allowed) {
// Execute payment...
await manager.recordSpending(session, amountUSD);
}
// Revoke when done
await manager.revokeSession(session.keyHash);x402 Protocol
X402Client
Handles automatic negotiation of HTTP 402 "Payment Required" responses.
import { X402Client } from '@veridex/agentic-payments';The x402 flow:
- Agent makes HTTP request to a paid API
- Server responds with
402 Payment Required+PAYMENT-REQUIREDheader X402Clientparses payment requirements (amount, recipient, network)- Agent signs and submits payment
- Agent retries request with
PAYMENT-SIGNATUREheader - Server verifies payment and returns data
PaymentParser
Parses x402 payment requirement headers.
import { PaymentParser } from '@veridex/agentic-payments';
const parser = new PaymentParser();
const requirements = parser.parse(response.headers);
// { amount, recipient, network, token, ... }Chain Clients
The Agent SDK provides chain-specific clients for multi-chain operations.
Available Clients
import {
EVMChainClient,
SolanaChainClient,
AptosChainClient,
SuiChainClient,
StarknetChainClient,
StacksChainClient,
ChainClientFactory,
} from '@veridex/agentic-payments';StacksChainClient
Stacks-specific client with native STX/sBTC pricing via Pyth.
import { StacksChainClient } from '@veridex/agentic-payments';
const client = new StacksChainClient({
network: 'testnet',
});
// Get STX price
const stxPrice = await client.getNativeTokenPriceUSD();
// Get vault balance
const balance = await client.getVaultBalance(address);StacksSpendingTracker
USD-aware spending tracker for Stacks with real-time Pyth pricing.
import { StacksSpendingTracker } from '@veridex/agentic-payments';
const tracker = new StacksSpendingTracker({
dailyLimitUSD: 100,
network: 'testnet',
});
// Convert STX amount to USD
const usdValue = await tracker.convertToUSD(1000000n, 'STX');
// Check if payment is within limits
const allowed = await tracker.checkPayment(amountMicroSTX);Oracle
PythOracle
Real-time price feeds from Pyth Network's Hermes API.
import { PythOracle, PYTH_FEED_IDS } from '@veridex/agentic-payments';
const oracle = new PythOracle();
// Get price by symbol (auto-resolves feed ID)
const ethPrice = await oracle.getPrice('ETH');
const stxPrice = await oracle.getPrice('STX');
const btcPrice = await oracle.getPrice('BTC');
// Get price by feed ID
const price = await oracle.getPrice(PYTH_FEED_IDS.SOL);
// Get native token price for a chain
const nativePrice = await oracle.getNativeTokenPrice('stacks');Supported symbols: ETH, BTC, SOL, STX, APT, SUI, STRK, USDC, USDT
Monitoring
AuditLogger
Records all payment activity for compliance and debugging.
import { AuditLogger } from '@veridex/agentic-payments';
const logger = new AuditLogger();
// Get recent logs
const logs = await logger.getLogs({ limit: 50 });
// Filter by chain
const baseLogs = await logger.getLogs({ chain: 10004 });AlertManager
Monitors spending and triggers alerts.
import { AlertManager } from '@veridex/agentic-payments';
const alerts = new AlertManager();
alerts.onAlert((alert) => {
if (alert.type === 'approaching_limit') {
console.warn('Approaching daily limit!');
}
});ComplianceExporter
Export audit logs in standard formats.
import { ComplianceExporter } from '@veridex/agentic-payments';
const exporter = new ComplianceExporter();
const csv = exporter.exportToCSV(logs);
const json = exporter.exportToJSON(logs);ERC-8004 Identity & Reputation
The Agent SDK provides full ERC-8004 integration for on-chain agent identity, reputation, and discovery.
agent.register
Register the agent on-chain by minting an ERC-721 identity NFT.
const result = await agent.register(options);Parameters:
interface RegisterAgentOptions {
name: string;
description: string;
services?: Array<{ name: string; endpoint: string }>;
x402Support?: boolean;
ipfsConfig?: { gateway: string; apiKey: string; provider: 'pinata' | 'web3.storage' };
}Returns: Promise<{ agentId: bigint; agentURI: string }>
Example:
const { agentId, agentURI } = await agent.register({
name: 'Sentiment Analyzer',
description: 'NLP-powered sentiment analysis for crypto markets',
services: [{ name: 'analyze', endpoint: 'https://my-agent.com/analyze' }],
x402Support: true,
});
console.log(`Registered as agent #${agentId}`);
console.log(`URI: ${agentURI}`);agent.getIdentity
Get the on-chain registration for this agent.
const identity = await agent.getIdentity();Returns: Promise<AgentRegistration | null>
agent.getAgentId
Get the stored agent ID (set after register() or via config).
const agentId = agent.getAgentId();Returns: bigint | undefined
agent.submitFeedback
Submit reputation feedback for another agent.
await agent.submitFeedback(agentId, options);Parameters:
interface FeedbackOptions {
score: number; // 0-100
tags?: string[]; // e.g., ['fast', 'accurate']
comment?: string;
feedbackURI?: string; // Optional URI with detailed feedback
}Example:
await agent.submitFeedback(42n, {
score: 85,
tags: ['fast', 'accurate', 'reliable'],
comment: 'Excellent sentiment analysis results',
});agent.getReputation
Get the reputation summary for an agent.
const summary = await agent.getReputation(agentId, trustedReviewers?);Returns: Promise<FeedbackSummary>
interface FeedbackSummary {
feedbackCount: number;
normalizedScore: number; // 0-100
tags: string[];
recentFeedback: FeedbackEntry[];
}agent.getReputationScore
Get a normalized reputation score (0-100) for an agent.
const score = await agent.getReputationScore(agentId, trustedReviewers?);Returns: Promise<number> — Score from 0 to 100.
agent.discover
Discover agents by capability, category, or chain.
const agents = await agent.discover(query);Parameters:
interface DiscoveryQuery {
category?: string;
chain?: string;
minReputation?: number;
tags?: string[];
limit?: number;
}Returns: Promise<AgentRegistration[]>
Example:
const sentimentAgents = await agent.discover({
category: 'sentiment',
minReputation: 30,
limit: 10,
});
for (const a of sentimentAgents) {
console.log(`Agent #${a.agentId}: ${a.name}`);
}agent.resolveAgent
Resolve an agent from a UAI, endpoint URL, chain address, or search term.
const resolved = await agent.resolveAgent(input);Parameters:
| Parameter | Type | Description |
|---|---|---|
input | string | UAI, URL, address, or search term |
Returns: Promise<ResolvedAgent | null>
interface ResolvedAgent {
agentId: bigint;
name: string;
agentURI: string;
reputationScore: number;
resolvedFrom: 'uai' | 'url' | 'address' | 'search';
}agent.checkMerchantTrust
Check a merchant's reputation before making a payment.
const trust = await agent.checkMerchantTrust(endpoint);Returns: Promise<TrustCheckResult>
interface TrustCheckResult {
trusted: boolean;
score: number; // 0-100
agentId?: bigint;
reason?: string; // Why trusted/untrusted
}Example:
const trust = await agent.checkMerchantTrust('https://data-provider.com');
if (trust.trusted) {
console.log(`Trusted (score: ${trust.score}/100)`);
} else {
console.log(`Untrusted: ${trust.reason}`);
}agent.getIdentityClient / getReputationClient / getAgentDiscovery
Access the underlying modular clients directly.
const identityClient = agent.getIdentityClient();
const reputationClient = agent.getReputationClient();
const discovery = agent.getAgentDiscovery();Identity Clients (Standalone)
These clients can be used independently of AgentWallet.
IdentityClient
Chain-agnostic client for the ERC-8004 Identity Registry.
import { IdentityClient } from '@veridex/agentic-payments';
import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');
const signer = new ethers.Wallet(privateKey, provider);
const identity = new IdentityClient(provider, signer, { testnet: false });
// Register with auto-built registration file
const { agentId, agentURI } = await identity.registerWithFile({
name: 'My Agent',
description: 'Does cool things',
services: [{ name: 'api', endpoint: 'https://my-agent.com/api' }],
});
// Query an agent
const agent = await identity.getAgent(agentId);
console.log(agent.name, agent.agentURI, agent.agentWallet);
// Get agent URI
const uri = await identity.getAgentURI(agentId);ReputationClient
Chain-agnostic client for the ERC-8004 Reputation Registry.
import { ReputationClient } from '@veridex/agentic-payments';
const reputation = new ReputationClient(provider, signer, { testnet: false });
// Submit feedback
await reputation.submitFeedback(agentId, {
score: 85,
tags: ['fast', 'accurate'],
});
// Get summary
const summary = await reputation.getSummary(agentId, []);
// Get normalized score (0-100)
const score = await reputation.getReputationScore(agentId);
// Revoke feedback
await reputation.revokeFeedback(agentId);RegistrationFileManager
Build, validate, and publish ERC-8004 registration files.
import { RegistrationFileManager } from '@veridex/agentic-payments';
// Build a registration file
const file = RegistrationFileManager.buildRegistrationFile({
name: 'My Agent',
description: 'Does cool things',
services: [{ name: 'api', endpoint: 'https://my-agent.com/api' }],
});
// Validate against ERC-8004 schema
const { valid, errors } = RegistrationFileManager.validate(file);
// Encode as data URI (no external deps)
const dataURI = RegistrationFileManager.buildDataURI(file);
// Publish to IPFS
const manager = new RegistrationFileManager({
ipfs: { gateway: 'https://api.pinata.cloud', apiKey: '...', provider: 'pinata' },
});
const ipfsURI = await manager.publishToIPFS(file);
// Fetch from URI
const fetched = await RegistrationFileManager.fetchFromURI(ipfsURI);
// Add/remove services
const updated = RegistrationFileManager.addService(file, {
name: 'new-service',
endpoint: 'https://my-agent.com/new',
});
// Build well-known file for zero-lookup resolution
const wellKnown = RegistrationFileManager.buildWellKnownFile(agentId, uai, ipfsURI);
// Serve at: /.well-known/agent-registration.jsonTrustGate
Pre-payment reputation checks.
import { TrustGate } from '@veridex/agentic-payments';
const gate = new TrustGate(reputationClient, identityClient, {
minReputation: 30,
trustedReviewers: ['0x...'],
trustModel: 'reputation',
mode: 'reject', // 'reject' throws, 'warn' logs
});
const result = await gate.check(agentId);
// result.trusted, result.score, result.reasonAgentDiscovery
Resolve agents from multiple input types.
import { AgentDiscovery } from '@veridex/agentic-payments';
const discovery = new AgentDiscovery(identityClient, reputationClient);
// Resolve from URL (checks /.well-known/agent-registration.json)
const fromUrl = await discovery.resolve('https://my-agent.com');
// Resolve from UAI (CAIP-2 extended format)
const fromUai = await discovery.resolve('eip155:8453:0x8004A169...:42');
// Resolve from chain address
const fromAddr = await discovery.resolve('0x742d35Cc6634C0532925a3b844Bc9e7595f5A234');React Hooks
The Agent SDK provides React hooks for frontend integration.
import {
useAgentWallet,
useSpendingStatus,
useFetchWithPayment,
useCostEstimate,
useProtocolDetection,
} from '@veridex/agentic-payments';Error Handling
import { AgentPaymentError, AgentPaymentErrorCode } from '@veridex/agentic-payments';
try {
await agent.pay({ ... });
} catch (error) {
if (error instanceof AgentPaymentError) {
switch (error.code) {
case AgentPaymentErrorCode.LIMIT_EXCEEDED:
console.log('Spending limit exceeded:', error.message);
break;
case AgentPaymentErrorCode.INSUFFICIENT_BALANCE:
console.log('Not enough tokens:', error.message);
console.log('Suggestion:', error.suggestion);
break;
case AgentPaymentErrorCode.SESSION_EXPIRED:
console.log('Session expired, creating new one...');
break;
case AgentPaymentErrorCode.NETWORK_ERROR:
if (error.retryable) {
console.log('Retryable error, will retry...');
}
break;
}
}
}Error Codes
| Code | Description | Retryable |
|---|---|---|
LIMIT_EXCEEDED | Transaction exceeds spending limit | No |
INSUFFICIENT_BALANCE | Not enough tokens in wallet | No |
SESSION_EXPIRED | Session key has expired | No |
CHAIN_NOT_SUPPORTED | Chain ID not configured | No |
TOKEN_NOT_SUPPORTED | Token not available on chain | No |
NETWORK_ERROR | Network or RPC failure | Yes |
X402_PAYMENT_FAILED | x402 payment negotiation failed | Yes |
SIGNATURE_FAILED | Transaction signing failed | No |
Full Example: Autonomous Data Agent
import { createAgentWallet } from '@veridex/agentic-payments';
async function runDataAgent() {
// 1. Initialize agent with spending limits
const agent = await createAgentWallet({
masterCredential: {
credentialId: process.env.CREDENTIAL_ID!,
publicKeyX: BigInt(process.env.PUBLIC_KEY_X!),
publicKeyY: BigInt(process.env.PUBLIC_KEY_Y!),
keyHash: process.env.KEY_HASH!,
},
session: {
dailyLimitUSD: 50,
perTransactionLimitUSD: 5,
expiryHours: 8,
allowedChains: [10004],
},
});
// 2. Set up spending alerts
agent.onSpendingAlert((alert) => {
console.warn(`[ALERT] ${alert.type}: ${alert.message}`);
});
// 3. Fetch paid data (x402 handled automatically)
const priceData = await agent.fetch('https://data-provider.example.com/api/v1/prices');
const prices = await priceData.json();
console.log('Fetched price data:', prices);
// 4. Make a direct payment
const receipt = await agent.pay({
chain: 10004,
token: 'USDC',
amount: '1000000',
recipient: '0x...',
});
console.log('Payment confirmed:', receipt.txHash);
// 5. Check session status
const status = agent.getSessionStatus();
console.log(`Spent: $${status.totalSpentUSD} / $${status.limits!.dailyLimitUSD}`);
// 6. Export audit log
const auditLog = await agent.exportAuditLog('json');
console.log('Audit:', auditLog);
// 7. Clean up
await agent.revokeSession();
}
runDataAgent().catch(console.error);