API Reference
Agent SDK

Agent SDK Reference

Complete API reference for @veridex/agentic-payments — the autonomous payment, identity, and reputation layer for AI agents.

Looking for the general-purpose runtime layer? See the Agents Framework page for @veridex/agents, React hooks, adapters, OpenClaw interop, and the control plane.

Installation

npm install @veridex/agentic-payments

Core: 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:

ParameterTypeDescription
urlstringURL to fetch
optionsRequestInitStandard 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:

ParameterTypeDescription
chainnumberWormhole 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:

ParameterTypeDescription
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:

TypeDescription
approaching_limitSpending is near the daily limit
limit_exceededTransaction was blocked by limit
session_expiringSession 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 NameDescription
veridex_payExecute a token payment (chain, token, amount, recipient)
veridex_balanceCheck wallet balance on a specific chain
veridex_statusGet session status and spending limits
veridex_historyGet 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:

  1. Agent makes HTTP request to a paid API
  2. Server responds with 402 Payment Required + PAYMENT-REQUIRED header
  3. X402Client parses payment requirements (amount, recipient, network)
  4. Agent signs and submits payment
  5. Agent retries request with PAYMENT-SIGNATURE header
  6. 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:

ParameterTypeDescription
inputstringUAI, 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.json

TrustGate

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.reason

AgentDiscovery

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');

Protocol Abstraction Layer

Supported Protocols

ProtocolCreatorPriorityDetection
UCPGoogle/Shopify100.well-known/ucp manifest or Link: rel="ucp-manifest" header
ACPOpenAI/Stripe90openai-acp-version or x-acp-checkout-url header
MPPTempo85WWW-Authenticate: Payment header (charge/session intents)
AP2Google80x-ap2-mandate-url or x-google-a2a-mandate header
x402Coinbase70HTTP 402 with PAYMENT-REQUIRED header

ProtocolRegistry

Formal capability declarations for intelligent protocol selection.

import { ProtocolRegistry } from '@veridex/agentic-payments';
 
const registry = new ProtocolRegistry();
 
// Find by capabilities
const escrowProtocols = registry.findByCapabilities(['escrow', 'refund']);
 
// Find best for requirements
const best = registry.findBest({
  capabilities: ['one_time_payment', 'cross_chain'],
  chainId: 10004,
  token: 'USDC',
  amountUSD: 5,
});
 
// Find by chain
const baseProtocols = registry.findByChain(10004);

Capabilities: one_time_payment, subscription, streaming, escrow, refund, partial_refund, prepaid_session, multi_token, cross_chain, gasless, eip712_signing, reputational_feedback, metered_billing, mandate_based.

PaymentIntent

Universal payment normalization — every protocol converts its challenge into a PaymentIntent:

import { createPaymentIntent, intentToProposedAction, isIntentExpired } from '@veridex/agentic-payments';
 
const intent = createPaymentIntent('x402', costEstimate, resourceUrl, {
  recipient: '0x...',
  ttlMs: 300_000,
  description: 'Premium API access',
});
 
// Check expiry
if (isIntentExpired(intent)) { /* handle */ }
 
// Convert for policy evaluation
const action = intentToProposedAction(intent);

PaymentSchemes: exact, upto, subscription, streaming, escrow, prepaid.

SettlementVerifier

Confirms payments settled on-chain with pluggable strategies:

import { SettlementVerifier, EVMSettlementStrategy } from '@veridex/agentic-payments';
 
const verifier = new SettlementVerifier({
  rpcEndpoints: { 10004: 'https://sepolia.base.org' },
  confirmations: 1,
  timeoutMs: 30_000,
});
 
verifier.registerStrategy(new EVMSettlementStrategy('x402', {
  10004: 'https://sepolia.base.org',
}));
 
const proof = await verifier.verify(settlement, traceHash);
// → { txHash, traceHashInCalldata, chain }

Agent-Safe Execution Control Plane

Policy Engine

Evaluates every proposed action against a versioned mandate before execution.

import {
  PolicyEngine,
  SpendingLimitRule,
  VelocityRule,
  AssetWhitelistRule,
  ChainWhitelistRule,
  ProtocolWhitelistRule,
  CounterpartyRule,
  TimeWindowRule,
  HumanApprovalRule,
} from '@veridex/agentic-payments';
 
const engine = new PolicyEngine();
engine.addRule(new SpendingLimitRule());
engine.addRule(new VelocityRule({ maxPerMinute: 5, maxPerHour: 50 }));
engine.addRule(new AssetWhitelistRule());
engine.addRule(new ChainWhitelistRule());
 
const verdict = await engine.evaluate(proposedAction, context);
// verdict.verdict: 'allow' | 'deny' | 'escalate'
// verdict.reasons: string[]

Security Firewall

import {
  InjectionDetector,
  ToolSanitizer,
  OutputGuard,
  AnomalyDetector,
} from '@veridex/agentic-payments';
 
// Prompt injection detection
const detector = new InjectionDetector();
const result = detector.detect(input);
// result.detected, result.matches: [{ category, pattern, matched }]
 
// Tool description sanitization (strips hidden instructions)
const sanitizer = new ToolSanitizer(detector);
const sanitized = sanitizer.sanitizeToolDescription(tool);
// sanitized.safe, sanitized.strippedContent
 
// Tool pinning for rug-pull detection
sanitizer.pinToolDescriptions(tools);
const validation = sanitizer.validatePins(tools);
// validation[i].valid, validation[i].reason
 
// Secret scanning on outputs
const guard = new OutputGuard();
const scan = guard.scanForSecrets(text);
// scan.found, scan.matches: [{ type, value }]
 
// Anomaly detection
const anomaly = new AnomalyDetector({
  baselineWindowMs: 7 * 24 * 60 * 60 * 1000,
  amountStdDevThreshold: 2.5,
});
const analysis = anomaly.analyze(action, history, Date.now());
// analysis.detected, analysis.anomalies, analysis.riskScore

Trace & Evidence

Cryptographically verifiable audit trail for every agent decision.

import { TraceInterceptor, EvidenceBundle } from '@veridex/agentic-payments';
 
const interceptor = new TraceInterceptor(storageAdapter);
const trace = await interceptor.captureTrace({
  traceId: 'unique-id',
  agentId: 'agent-1',
  toolCalls: [{ name: 'veridex_pay', args: {}, result: {} }],
  reasoning: { prompt: '...', response: '...' },
});
 
const bundle = new EvidenceBundle(trace);
const evidence = bundle.build();

Storage Adapters

AdapterBackendImport
MemoryStorageIn-memory@veridex/agentic-payments
JSONFileStorageLocal filesystem@veridex/agentic-payments
PostgresStoragePostgreSQL@veridex/agentic-payments
IPFSStorageIPFS (Kubo/Pinata/Infura)@veridex/agentic-payments
ArweaveStorageArweave permaweb@veridex/agentic-payments
FilecoinStorageFilecoin Cloud@veridex/agentic-payments
StorachaStorageStoracha@veridex/agentic-payments
AkaveStorageAkave@veridex/agentic-payments
import {
  MemoryStorage,
  PostgresStorage,
  FilecoinStorage,
  StorachaStorage,
} from '@veridex/agentic-payments';
 
// PostgreSQL — works with pg, postgres.js, drizzle, etc.
const postgres = new PostgresStorage({
  db: pool, // any object with query(sql, params) method
  tableName: 'veridex_traces',
  autoCreateTable: true,
});
 
// Filecoin Cloud via @filoz/synapse-sdk
import { Synapse } from '@filoz/synapse-sdk';
import { privateKeyToAccount } from 'viem/accounts';
const synapse = Synapse.create({ account: privateKeyToAccount('0x...'), source: 'veridex' });
const filecoin = new FilecoinStorage({ client: synapse.storage });
 
// Storacha via @storacha/client
import * as Client from '@storacha/client';
import * as Proof from '@storacha/client/proof';
import { Signer } from '@storacha/client/principal/ed25519';
const principal = Signer.parse(process.env.KEY);
const client = await Client.create({ principal, store: new StoreMemory() });
const proof = await Proof.parse(process.env.PROOF);
const space = await client.addSpace(proof);
await client.setCurrentSpace(space.did());
const storacha = new StorachaStorage({ client });

Escalation Manager

Human-in-the-loop escalation for high-risk actions.

import { EscalationManager } from '@veridex/agentic-payments';
 
const escalation = new EscalationManager(5 * 60 * 1000); // 5 min timeout
 
// Create ticket
const ticket = escalation.escalate(proposedAction, verdict);
// ticket.id, ticket.status: 'pending'
 
// Listen for events
escalation.on('escalated', (t) => notifyAdmin(t));
escalation.on('approved', (t) => proceedWithAction(t));
escalation.on('rejected', (t) => abortAction(t));
escalation.on('timeout', (t) => handleTimeout(t));
 
// Approve or reject
escalation.approve(ticket.id, 'admin@company.com');
escalation.reject(ticket.id, 'admin@company.com', 'Too risky');

Circuit Breaker

Halts agent operations after repeated failures.

import { CircuitBreaker } from '@veridex/agentic-payments';
 
const breaker = new CircuitBreaker({
  failureThreshold: 3,
  resetTimeoutMs: 60_000,
});
 
// Record outcomes
breaker.recordSuccess();
breaker.recordFailure();
 
// Check state before operations
if (breaker.isOpen()) {
  console.warn('Agent is halted');
}
 
// Listen for state changes
breaker.on('open', () => alertOps('Agent halted'));
breaker.on('half-open', () => log('Testing recovery'));
breaker.on('close', () => log('Agent resumed'));

Hardened MCP Server

import { MCPServer } from '@veridex/agentic-payments';
 
const server = new MCPServer(agent, {
  allowedTools: ['veridex_pay', 'veridex_check_balance'],
  toolSpendingLimits: { veridex_pay: 10 },
  sanitizeDescriptions: true,
  pinDescriptions: true,
  scanInputs: true,
  scanOutputs: true,
});
 
const tools = server.getTools();

MCPServerConfig:

OptionTypeDefaultDescription
allowedToolsstring[][] (all)Whitelist of tool names
toolSpendingLimitsRecord<string, number>{}Per-tool USD limits
sanitizeDescriptionsbooleantrueStrip hidden instructions
pinDescriptionsbooleantrueDetect rug-pulls
scanInputsbooleantrueInjection detection
scanOutputsbooleantrueSecret scanning

React Hooks

The Agent SDK provides React hooks for frontend integration.

import {
  AgentWalletProvider,
  useAgentWallet,
  useAgentWalletContext,
  usePayment,
  useSessionStatus,
  useFetchWithPayment,
  useCostEstimate,
  useProtocolDetection,
  useMultiChainBalance,
  usePaymentHistory,
  useSpendingAlerts,
  useCanPay,
} from '@veridex/agentic-payments';
HookPurpose
useAgentWallet(config)Create and manage an AgentWallet instance
useAgentWalletContext()Access wallet from context (inside AgentWalletProvider)
usePayment(wallet)Make payments with loading/error state
useSessionStatus(wallet)Get session status with auto-refresh
useFetchWithPayment(wallet)Make paid HTTP requests with protocol detection
useCostEstimate(wallet, url)Estimate cost before paying
useProtocolDetection(wallet, url)Detect which payment protocol a URL uses
useMultiChainBalance(wallet)Fetch balances across all chains
usePaymentHistory(wallet)Get payment history
useSpendingAlerts(wallet)Subscribe to spending alerts
useCanPay(wallet, amountUSD)Check if wallet can make a payment

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

CodeDescriptionRetryable
LIMIT_EXCEEDEDTransaction exceeds spending limitNo
INSUFFICIENT_BALANCENot enough tokens in walletNo
SESSION_EXPIREDSession key has expiredNo
CHAIN_NOT_SUPPORTEDChain ID not configuredNo
TOKEN_NOT_SUPPORTEDToken not available on chainNo
NETWORK_ERRORNetwork or RPC failureYes
X402_PAYMENT_FAILEDx402 payment negotiation failedYes
SIGNATURE_FAILEDTransaction signing failedNo

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);