Payment Orchestration

The client.payments namespace handles the full x402 payment lifecycle from parsing 402 responses to on-chain settlement and receipt indexing.

Automatic 402 Handling

import { fetchWithPayment } from '@brain-protocol/sdk';

// Drop-in replacement for fetch() — handles 402 automatically
const data = await fetchWithPayment(
  'https://api.example.com/v1/infer',
  {
    headers: { 'Agent-ID': agent.agentId },
  },
  { client, agentId: agent.agentId }
);

Manual Payment Flow

1

Parse the 402 response

// Parse a 402 response into a PaymentIntent
const intent = await client.payments.parseIntent(response);
2

Evaluate against policy

// Evaluate against policy before spending
const approval = await client.payments.evaluate(intent, agent.agentId);

if (!approval.allowed) {
  throw new Error(`Payment blocked: ${approval.reason}`);
}
3

Settle on-chain

// Settle on-chain via ERC-4337
const receipt = await client.payments.settle(intent, approval);
console.log('Tx hash:', receipt.txHash);

Query Payment History

const history = await client.payments.list({
  agentId: agent.agentId,
  from: '2025-01-01',
  to: '2025-12-31',
  limit: 50,
});

Each entry includes:

  • { intentId, txHash, amount, asset, merchant, resourceUri, timestamp }

Get a Specific Receipt

Example response:

Spending Summary

Example response:

Last updated