Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

5.6 KB
Raw Blame

x402 — HTTP 402 Payment Required Protocol

The x402 sub-package implements the coinbase/x402 v2 specification for pay-gating HTTP endpoints using on-chain Pump Agent invoice payments.

import { x402 } from "@three-ws/agent-payments";
// or direct import:
import { createX402Fetch, PumpAgentFacilitator, buildPumpAgentRequirements } from "@three-ws/agent-payments/x402";

Server Side

buildPumpAgentRequirements(config)

Build the PaymentRequirements array for a 402 response body.

const requirements = x402.buildPumpAgentRequirements({
  agentMint: "YourAgentMintAddress",
  payTo: "PaymentVaultAddress",
  amount: "1000000",     // 1 USDC in minor units (6 decimals)
  asset: x402.USDC_MAINNET,
  network: x402.SOLANA_MAINNET,
  maxTimeoutSeconds: 60,
  memo: "12345",
  startTime: Math.floor(Date.now() / 1000),
  endTime: Math.floor(Date.now() / 1000) + 300,
});

PumpAgentFacilitator

Server-side facilitator that verifies and settles payments. Implements FacilitatorClient.

const facilitator = new x402.PumpAgentFacilitator({
  connection,
  // optional: override verify/settle endpoints
});

// Verify a payment payload
const result = await facilitator.verify(payload, requirements);
if (!result.isValid) throw new Error(result.invalidReason);

// Settle
const settled = await facilitator.settle(payload, requirements);

createResourceServer(config)

Creates an Express middleware that automatically handles 402 payment gating:

import express from "express";

const app = express();
const paymentMiddleware = x402.createResourceServer({
  facilitator,
  requirements,
  resource: {
    url: "https://api.agent.example/inference",
    description: "AI inference endpoint",
  },
});

app.use("/inference", paymentMiddleware, (req, res) => {
  res.json({ result: "..." });
});

Client Side

createX402Fetch(config)

Wraps fetch to automatically handle 402 responses — detects payment requirements, builds the invoice transaction, signs + sends it, then retries the original request.

const x402fetch = x402.createX402Fetch({
  payer: wallet.publicKey.toBase58(),
  signTransaction: async (txBase64) => {
    const tx = Transaction.from(Buffer.from(txBase64, "base64"));
    const signed = await wallet.signTransaction(tx);
    return Buffer.from(signed.serialize()).toString("base64");
  },
  sendTransaction: async (signedTxBase64) => {
    const sig = await connection.sendRawTransaction(
      Buffer.from(signedTxBase64, "base64")
    );
    return sig;
  },
  network: x402.SOLANA_MAINNET,
  confirmationTimeoutMs: 30_000,
});

// Use exactly like fetch — payment is handled automatically
const res = await x402fetch("https://api.agent.example/inference");
const data = await res.json();

Header Helpers

import {
  encodePaymentRequired,
  decodePaymentRequired,
  encodePaymentPayload,
  decodePaymentPayload,
  encodePaymentResponse,
  decodePaymentResponse,
  getPaymentRequiredFromResponse,
  getPaymentPayloadFromRequest,
  getPaymentResponseFromResponse,
} from "@three-ws/agent-payments/x402";

These encode/decode the three protocol headers as base64 JSON:

Header constant Value
X402_HEADER_PAYMENT "X-PAYMENT"
X402_HEADER_PAYMENT_REQUIRED "payment-required"
X402_HEADER_PAYMENT_RESPONSE "X-PAYMENT-RESPONSE"

The client sends its signed proof in the X-PAYMENT request header; the server advertises requirements on the 402 via payment-required and returns the settlement receipt in X-PAYMENT-RESPONSE. (There is no PAYMENT-SIGNATURE header — that was an earlier draft name.)


Protocol Flow

Client                          Server                        Facilitator
  │                               │                               │
  │── GET /resource ─────────────►│                               │
  │◄── 402 payment-required ──────│                               │
  │    { accepts: [...] }         │                               │
  │                               │                               │
  │  (build + sign + send tx)     │                               │
  │                               │                               │
  │── GET /resource ─────────────►│                               │
  │   X-PAYMENT: <proof>          │── verify(payload, req) ──────►│
  │                               │◄── { isValid: true } ─────────│
  │                               │── settle(payload, req) ───────►│
  │                               │◄── { success: true, tx } ─────│
  │◄── 200 X-PAYMENT-RESPONSE ────│                               │

Payment Schemes

"pump-agent" scheme

On-chain invoice via agentAcceptPayment. The client calls the Pump Agent Payments program with the invoice params from requirements.extra (memo, startTime, endTime, agentMint). Verification checks the invoiceId PDA on-chain.

"exact" scheme

Standard SPL TransferChecked — transfer tokens directly to payTo. No invoice PDA involved.


Network & Asset Constants

x402.SOLANA_MAINNET  // "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
x402.SOLANA_DEVNET   // "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"
x402.USDC_MAINNET    // "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
x402.USDC_DEVNET     // "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"
x402.X402_VERSION    // 2