Agent Integration
Use @payai-sh/x402 to wrap an agent's paid fetch calls.
import { createPayAIFetch } from "@payai-sh/x402";
const payaiFetch = createPayAIFetch({
grant,
payer: async (request) => {
return request.fetch(request.paymentHeaders);
},
onReceipt: async (receipt) => {
console.log("paid", receipt);
}
});
const response = await payaiFetch("https://data.example.com/report", {
purpose: "research"
});
Recommended Caller Pattern
- Give each agent a narrow grant.
- Pass task purpose and resource metadata into
payaiFetch. - Treat
PayAIPolicyErroras a stop or human-review branch. - Store receipts with the agent task id in your own system.
- Keep real wallet signing inside the payer callback.
Error Handling
try {
const response = await payaiFetch(url, { purpose: "research" });
return await response.json();
} catch (error) {
if (error instanceof Error && error.name === "PayAIPolicyError") {
return { status: "payment_denied", reason: error.message };
}
throw error;
}
Production Notes
The default MemorySpendingLedger is for local demos and tests. Production agents should pass a persistent SpendingLedger implementation so budget checks survive process restarts.