@mingderwang/x402
v0.1.4
Published
x402 (HTTP 402 Payment Required) client + server helpers: EIP-3009 signing, X-PAYMENT, verification and settlement. Ships an `x402` CLI.
Maintainers
Readme
@mingderwang/x402
HTTP 402 Payment Required helpers for the x402 standard — payment requirements, EIP-3009 signing, X-PAYMENT, verification, and on-chain settlement.
Built on ethers v6 + @mingderwang/wallet. Ships both a library and an x402 CLI.
Install
npm install @mingderwang/x402 # library
npm install -g @mingderwang/x402 # also gives the `x402` CLICLI
x402 requirements <url> [--method GET] [--header K:V]...
x402 sign <requirements.json> [--wallet <keystore>]
x402 pay <url> [--method GET] [--header K:V]... [--wallet <keystore>]
x402 decode <base64-or-file | payload.json>
x402 verify <payload> <requirements.json>
x402 settle <payload> <requirements.json> [--gas-key <private>] [--rpc <url>]Keystore defaults to ~/.wallet/wallet.json (create one with the wallet CLI). Password via prompt or WALLET_PASSWORD / XSIFT_WALLET_PASSWORD env. Full round trip:
x402 requirements https://api.example.com/resource # shows the 402 + accepts[]
x402 pay https://api.example.com/resource # signs + pays + retries with X-PAYMENT
x402 verify <header> requirements.json # offline sanity check
x402 settle <payload.json> requirements.json --gas-key 0x... # broadcast on-chainClient side — detect a paywall and pay
import { detectPaymentRequired, makePaymentPayload, makePaymentRequired } from '@mingderwang/x402';
const res = await fetch('https://api.example.com/resource', { headers: { authorization: 'Bearer ...' } });
if (res.status === 402) {
const reqs = detectPaymentRequired({ status: res.status, headers: res.headers, text: await res.text() });
const payload = await makePaymentPayload({ wallet, requirement: reqs.accepts[0] });
const retry = await fetch('https://api.example.com/resource', {
headers: { 'x-payment': Buffer.from(JSON.stringify(payload)).toString('base64') },
});
}Server side — issue requirements, verify, settle
import { makePaymentRequired, verifyPaymentPayload, settlePayment } from '@mingderwang/x402';
const requirement = makePaymentRequired({
resource: '/api/resource', description: 'Pay per use',
network: 'ethereum-sepolia', amount: '500000', /* 0.5 USDC (6 decimals) */
asset: usdcAddress, payTo: sellerAddress,
}).accepts[0];
const check = verifyPaymentPayload(parsedXPayment, requirement); // { isValid, payer }
if (!check.isValid) return new Response(JSON.stringify({ x402Version: 1, error: check.invalidReason }), { status: 402 });
const settled = await settlePayment(parsedXPayment, requirement, {}); // broadcasts transferWithAuthorization (needs X402_GAS_PRIVATE_KEY)- Scheme:
exact, network/asset/timeouts configurable. - Replay protection: keep signed nonces; reject repeats with
invalid_transaction_state. - Errors follow the spec:
insufficient_funds,invalid_exact_evm_payload_*, etc.
License
MIT
