npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@swarmforce/x402

v0.1.0

Published

x402 HTTP-402 payment integration for SwarmForce agents — Hono middleware for crypto-metered API access.

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

  1. Client makes a request to a paid endpoint
  2. Server responds with 402 Payment Required including payment details (amount, recipient, nonce, token address)
  3. Client signs an EIP-3009 transferWithAuthorization for the SWARM token
  4. Client retries the request with the signed authorization in the X-PAYMENT header
  5. Server verifies the signature and executes the on-chain transfer
  6. 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/x402

Client 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-PAYMENT header 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 clean

Dependencies

  • @swarmforce/agent-sdk -- Agent SDK for SWARM token interaction
  • viem -- Ethereum client for signature verification and on-chain execution
  • hono -- HTTP framework (middleware)