GTRADEDocs
AI & agents

x402 (pay per request)

Charge AI agents and other API clients per request in USDC on Base with the open x402 protocol. GTRADE issues the payment requirements, verifies and settles the payment on-chain, and records every paid request as a normal payment.

#What x402 is

x402 is an open protocol that revives the HTTP status code 402 Payment Required. It lets a program, typically an AI agent, pay for a single HTTP request without an account, a checkout page or a subscription:

  1. The agent calls your endpoint.
  2. Your endpoint answers 402 Payment Required with a JSON body that says what to pay: amount, token, network and recipient.
  3. The agent signs a USDC transfer authorization (EIP-3009) with its wallet and repeats the request with an X-PAYMENT header.
  4. GTRADE verifies the authorization and submits it to the blockchain. Your endpoint then returns the content with an X-PAYMENT-RESPONSE header that contains the transaction hash.

The agent never needs ETH for gas: GTRADE submits the transaction and pays the network fee.

GTRADE implements x402 protocol version 1, scheme exact, network base (Base mainnet), token USDC, as specified in the official x402 repository (specs/x402-specification-v1.md, specs/transports-v1/http.md, specs/schemes/exact/scheme_exact_evm.md). Any client that speaks x402 v1 can pay you.

#Protect an endpoint (Node.js)

Install the Node.js SDK version 1.1.0 or later:

bash
npm install https://docs.gtradegateway.io/sdk/gtrade-payments-1.1.0.tgz

Add the middleware to any Express or Connect route. The price is per request, in USD:

js
const express = require('express');
const { Gtrade } = require('gtrade-payments');

const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY });
const app = express();

app.get('/premium', gtrade.x402.requirePayment({ amountUsd: 0.05, description: 'Premium quote' }), (req, res) => {
  // Runs only for a verified payment.
  res.json({ quote: 42, paidBy: req.x402.payer, payment: req.x402.paymentId });
});

app.listen(3000);

Inside your handler, req.x402 contains payer (the agent's wallet address), paymentId (the GTRADE payment id) and requirements.

#What the middleware does

RequestMiddleware behaviour
No X-PAYMENT headerAsks GTRADE for payment requirements and answers 402 with { "x402Version": 1, "error": "X-PAYMENT header is required", "accepts": [ … ] }.
X-PAYMENT presentChecks that the payment was issued for this URL at this price, then calls GTRADE to verify it. If it is not valid, answers 402 with the reason in error (for example insufficient_funds).
Valid paymentRuns your handler but holds its response back, settles the payment on-chain, and only then sends your response with X-PAYMENT-RESPONSE.
Your handler answers 4xx or 5xxYour error response is sent and nothing is settled: the agent is not charged.
Settlement failsYour response is discarded and the agent gets 402 with the reason.

This is the order used by the reference x402 middleware: verify, serve, settle, then deliver. Content is never delivered before the money has moved, and the agent is never charged for an error. The cost is latency (settlement waits for the Base transaction receipt, usually 2 to 4 seconds) and the fact that your handler's work is done even if settlement fails. Because the response is held in memory until settlement, do not stream large bodies from paid routes.

#Options

OptionDefaultDescription
amountUsd(required)Price per request in USD, paid in USDC. Minimum 0.01, maximum 1000, at most 6 decimals.
description""Shown to the agent in the requirements.
mimeTypeapplication/jsonMIME type of your response.
maxTimeoutSeconds300How long the agent's authorization stays valid (10 to 3600).
outputSchemanoneOptional JSON schema of your response.
metadatanoneCopied onto every GTRADE payment created for this route.
resourcerequest URLAbsolute URL that the payment is bound to (query string excluded). Set it explicitly if a proxy rewrites the host or protocol.

#Other frameworks

gtrade.x402.handle(request, options) works with a Node.js request or a Fetch API Request (Next.js route handlers, Hono, Cloudflare-style handlers):

js
const r = await gtrade.x402.handle(request, { amountUsd: 0.05, description: 'Premium quote' });
if (!r.paid) {
  return new Response(JSON.stringify(r.body), { status: r.status, headers: r.headers });
}
const body = JSON.stringify(await buildPremiumResponse());   // do the paid work
const out = await r.settle();                                  // settle on-chain
if (!out.success) {
  return new Response(JSON.stringify(out.body), { status: out.status, headers: out.headers });
}
return new Response(body, { status: 200, headers: { 'Content-Type': 'application/json', ...out.headers } });

#How agents pay

Agents use the official x402 client libraries; nothing GTRADE-specific is needed on their side. For example with x402-fetch:

js
import { wrapFetchWithPayment, createSigner, decodeXPaymentResponse } from 'x402-fetch';

const signer = await createSigner('base', process.env.AGENT_PRIVATE_KEY);
const pay = wrapFetchWithPayment(fetch, signer, BigInt(1_000_000)); // spend at most 1 USDC per request
const res = await pay('https://api.example.com/premium');
console.log(await res.json(), decodeXPaymentResponse(res.headers.get('x-payment-response')));

x402-axios (JavaScript) and x402 (Python, with httpx and requests adapters) work the same way. The agent's wallet needs USDC on Base; it does not need ETH.

#Fees and settlement

  • Each paid request creates a normal GTRADE payment with its own Base deposit address. The address is the payTo in the requirements, and the payment id is in req.x402.paymentId.
  • GTRADE submits the agent's authorization on Base and pays the gas. The USDC moves directly from the agent's wallet to that deposit address; GTRADE cannot change the amount or the recipient.
  • After the deposit is confirmed on Base, the payment becomes paid and you receive the usual payment.paid webhook. The payment's metadata contains x402_requirement_id and x402_resource.
  • Funds are then swept from the deposit address to your wallet together with your other payments, minus the standard GTRADE fee of 1%, deducted on-chain by the sweep contract. Sweeps are batched, so small payments can take a few hours to reach your wallet.

#Limits

  • Network and token: Base mainnet, USDC only (0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913). Other x402 networks (Base Sepolia, Solana, Avalanche…) are not supported.
  • Amount: at least $0.01 and at most $1,000 per request, with up to 6 decimals. Smaller amounts are refused with amount_too_small because the network fee would exceed the payment's fee.
  • One payment per requirements: every 402 issues fresh requirements with a dedicated deposit address, and each can be paid exactly once. A replayed X-PAYMENT header is rejected with duplicate_settlement.
  • Requirements that were not paid expire after one hour; the agent simply receives new ones.
  • Scheme exact only: the authorization must be for exactly the requested amount.
  • Rate limits: the middleware makes up to three API calls per paid request (requirements, verify, settle) and one per unpaid request, all counted in your API key's rate limit.
  • Each 402 answered to an unpaid request creates an open payment in your dashboard. Requests that are never paid simply stay open.

#Facilitator API

The middleware uses these endpoints; you can also call them directly. They require your API key like the rest of the API. verify, settle and supported follow the x402 v1 facilitator interface, so the bodies are exactly the spec's.

EndpointPurpose
POST /v1/x402/requirementsCreate requirements: { amount_usd, resource, description?, mime_type?, max_timeout_seconds?, output_schema?, metadata? }. Returns payment_requirements (one x402 PaymentRequirements) and payment_id.
GET /v1/x402/requirements/{id or payTo}Look up requirements and their status (open or settled, with transaction and payer).
POST /v1/x402/verify{ x402Version, paymentPayload, paymentRequirements } → { isValid, invalidReason?, payer }.
POST /v1/x402/settleSame body → { success, transaction, network, payer, errorReason? }. Idempotent: the same authorization always returns the same result.
GET /v1/x402/supported{ "kinds": [{ "x402Version": 1, "scheme": "exact", "network": "base" }] }

Verification checks the EIP-712 signature, that the payment matches requirements GTRADE issued to your account (recipient, amount, token, network, resource), the validity window, that the authorization has not been used on-chain, the payer's USDC balance, and simulates the transfer. Common reasons: insufficient_funds, invalid_exact_evm_payload_signature, invalid_exact_evm_payload_recipient_mismatch, invalid_exact_evm_payload_authorization_value, invalid_exact_evm_payload_authorization_valid_before, invalid_exact_evm_nonce_already_used, invalid_payment_requirements, payment_expired, duplicate_settlement. Settlement can also fail with facilitator_insufficient_gas or settlement_pending (the transaction was sent but not yet confirmed; repeat the settle call to get the final result).

Only GTRADE-issued requirements are accepted. Facilitator-only setups in which a fixed payTo address is configured in the official x402 server middleware are not supported; use the SDK middleware above.

#Status

x402 is new on GTRADE. Requirements, verification and the complete 402 flow have been tested on Base mainnet with the official x402-fetch client, including on-chain signature, nonce, balance and simulation checks. The first real-money settlement test is scheduled, and this note will be updated once it has passed. Only the Node.js SDK includes the middleware so far; from Python or PHP, call the facilitator endpoints directly.