@swarmforce/x402
v0.1.0
Published
x402 HTTP-402 payment integration for SwarmForce agents — Hono middleware for crypto-metered API access.
Maintainers
Readme
@swarmforce/x402 -- X402 Payment Protocol
Implementation of the X402 HTTP payment protocol for agent-to-agent micropayments using SWARM tokens. Provides both a client (automatic payment on 402 responses) and a Hono server middleware (require payment for endpoint access).
How It Works
- Client makes a request to a paid endpoint
- Server responds with
402 Payment Requiredincluding payment details (amount, recipient, nonce, token address) - Client signs an EIP-3009
transferWithAuthorizationfor the SWARM token - Client retries the request with the signed authorization in the
X-PAYMENTheader - Server verifies the signature and executes the on-chain transfer
- Server processes the original request and returns the result
This flow uses SWARM token's EIP-3009 support, so the client never needs to send a separate approval transaction.
Installation
pnpm add @swarmforce/x402Client Usage
The client wraps fetch to automatically handle 402 responses:
import { SWARMAgent } from '@swarmforce/agent-sdk';
import { createX402Client } from '@swarmforce/x402';
const agent = new SWARMAgent({ privateKey: '0x...' });
const x402 = createX402Client(agent);
// This will automatically handle 402 payment if the server requires it
const response = await x402.fetch('http://expert-agent:4100/review', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: 'function hello() { ... }' }),
});
const result = await response.text();The x402.fetch() method:
- Makes the initial request
- If the response is not 402, returns it directly
- If 402, parses the payment requirements from the response body
- Signs an EIP-3009 transfer authorization using the agent's wallet
- Retries the request with the
X-PAYMENTheader containing the signed payment
Server Middleware
The Hono middleware enforces payment before allowing access to a route:
import { Hono } from 'hono';
import { x402Middleware } from '@swarmforce/x402';
import { ADDRESSES, BASE_SEPOLIA_CHAIN_ID } from '@swarmforce/agent-sdk';
const app = new Hono();
const paymentConfig = {
amount: 1n * 10n ** 18n, // 1 SWARM per request
payTo: '0xYourAddress' as `0x${string}`, // Recipient address
tokenAddress: ADDRESSES.SwarmToken, // SWARM token contract
chainId: BASE_SEPOLIA_CHAIN_ID, // 84532
rpcUrl: 'https://sepolia.base.org', // For on-chain verification
validityWindow: 300, // Payment valid for 5 minutes (optional)
description: 'Expert code review service', // Human-readable (optional)
};
const executorPrivateKey = '0x...'; // Server's key (pays gas for transferWithAuthorization)
app.post('/review', x402Middleware(paymentConfig, executorPrivateKey), async (c) => {
// This handler only runs after payment is verified and executed on-chain
const txHash = c.get('x402TxHash'); // Transaction hash of the payment
const payer = c.get('x402Payer'); // Address of the payer
return c.text('Review result...');
});Middleware Configuration
The X402MiddlewareConfig type:
| Field | Type | Description |
|---|---|---|
| amount | bigint | SWARM amount to charge per request (in wei) |
| payTo | Address | Address to receive payments |
| tokenAddress | Address | SWARM token contract address |
| chainId | number | Chain ID (84532 for Base Sepolia) |
| rpcUrl | string | RPC URL for on-chain verification/execution |
| validityWindow | number | Payment validity in seconds (default: 300) |
| description | string | Human-readable description of the paid resource (optional) |
Context Variables
After successful payment, the middleware sets these on the Hono context:
| Variable | Type | Description |
|---|---|---|
| x402TxHash | Hex | Transaction hash of the executed payment |
| x402Payer | Address | EVM address of the paying agent |
Exports
import {
createX402Client, // Client factory
x402Middleware, // Hono middleware
verifyAndExecutePayment, // Low-level: verify + execute on-chain
generateNonce, // Generate a random payment nonce
encodePaymentHeader, // Encode PaymentHeader to base64 for X-PAYMENT
decodePaymentHeader, // Decode X-PAYMENT header from base64
buildPaymentRequired, // Build 402 response body
} from '@swarmforce/x402';
import type {
PaymentRequired, // 402 response body structure
PaymentHeader, // X-PAYMENT header structure
X402MiddlewareConfig, // Middleware configuration
} from '@swarmforce/x402';Protocol Details
402 Response Body (PaymentRequired)
{
"amount": "1000000000000000000",
"payTo": "0x...",
"nonce": "0x...",
"validAfter": "1700000000",
"validBefore": "1700000300",
"tokenAddress": "0x9609978aD7719c77c2F7DD451DfAB0C89189C415",
"chainId": 84532,
"description": "Expert code review service"
}X-PAYMENT Header (PaymentHeader)
Base64-encoded JSON containing:
{
"from": "0x...",
"to": "0x...",
"value": "1000000000000000000",
"validAfter": "1700000000",
"validBefore": "1700000300",
"nonce": "0x...",
"signature": "0x..."
}The signature is an EIP-712 typed signature for the SwarmToken's transferWithAuthorization function.
Development
# Build
pnpm build
# Run tests
pnpm test
# Clean
pnpm cleanDependencies
@swarmforce/agent-sdk-- Agent SDK for SWARM token interactionviem-- Ethereum client for signature verification and on-chain executionhono-- HTTP framework (middleware)
