Production Ready โ€ข v3.3.14

Build Payment Apps in Minutes, Not Weeks.

Micropay is a high-performance Solana SDK for implementing friction-free x402 protocol payments. Secure, stateless, and built for the future.

Stateless Auth

Secure x402 error handling using cryptographic signatures.

SOL & SPL Tokens

Native support for any SPL token via Jupiter integration.

AI Optimized

Designed for autonomous agents with local keypair support.

Why x402?

Micropayments,
Architected for Velocity.

Traditional payments are too slow for the AI era. x402 provides a standardized human-and-machine-readable bridge for value transfer.

Standardization

Native HTTP 402 error handling.

AI Integration

Secure agent-to-agent keypair support.

Source Code
// The x402 Magic
const res = await api.get('/premium');

if (res.status === 402) {
  const { paymentUrl } = await res.json();
  // Simply pay via SDK
  await pay(paymentUrl);
}

Live Demos

Features Demonstrated

Protocol

  • x402 Implementation
  • SOL & SPL Tokens
  • Stateless Sessions

Automation

  • AI Agent Wallets
  • PayAI Formats
  • Priority Fees

Reliability

  • On-Chain Verification
  • RPC Fallback
  • Replay Protection
๐Ÿ“ฆ

Installation

Get started in seconds with npm or yarn.

1 Install the package

Source Code
npm install @alleyboss/micropay-solana-x402-paywall @solana/web3.js

2 Set up environment variables

Source Code
# .env.local
NEXT_PUBLIC_SOLANA_NETWORK=devnet
NEXT_PUBLIC_RPC_URL=https://api.devnet.solana.com
CREATOR_WALLET_ADDRESS=your_wallet_address
SESSION_SECRET=your_32_character_secret_key
SESSION_DURATION_HOURS=24
DEFAULT_ARTICLE_PRICE_LAMPORTS=10000000

# Optional: AI Agent Demo
OPENAI_API_KEY=sk-...
AGENT_KEYPAIR_SECRET=[...]
๐Ÿ’ก

Pro Tip

Use Devnet for testing. Get free SOL from the Solana Faucet.

โšก

Quick Start

Protect your API routes with x402 middleware in just a few lines of code.

N

Next.js App Router

Protect API routes with middleware

Source Code
// app/api/premium/route.ts
import { createX402Middleware } from '@alleyboss/micropay-solana-x402-paywall/next';

const withPayment = createX402Middleware({
  walletAddress: process.env.CREATOR_WALLET_ADDRESS!,
  price: '10000000', // 0.01 SOL in lamports
  network: 'devnet',
  rpcUrl: process.env.NEXT_PUBLIC_RPC_URL
});

export const GET = withPayment(async (req) => {
  return new Response(JSON.stringify({ 
    data: 'Premium content unlocked!' 
  }), {
    headers: { 'Content-Type': 'application/json' }
  });
});
E

Express.js

Add middleware to any route

Source Code
import express from 'express';
import { x402Middleware } from '@alleyboss/micropay-solana-x402-paywall/express';

const app = express();
const server = new x402ResourceServer({
  facilitator: new LocalSvmFacilitator(process.env.RPC_URL!),
  walletAddress: process.env.CREATOR_WALLET_ADDRESS!
});

app.get('/api/premium', 
  x402Middleware(server, {
    accepts: { scheme: 'exact', amount: '10000000' }
  }), 
  (req, res) => res.json({ data: 'Unlocked!' })
);
R

React Client

Connect wallet and make payments

Source Code
import { useWallet } from '@solana/wallet-adapter-react';
import { Connection, Transaction, SystemProgram, PublicKey } from '@solana/web3.js';

function PaymentButton() {
  const { publicKey, signTransaction } = useWallet();

  const handlePayment = async () => {
    const tx = new Transaction().add(
      SystemProgram.transfer({
        fromPubkey: publicKey!,
        toPubkey: new PublicKey('CREATOR_WALLET'),
        lamports: 10_000_000 // 0.01 SOL
      })
    );

    const signed = await signTransaction!(tx);
    const signature = await connection.sendRawTransaction(signed.serialize());
    
    // Call protected API with X402 Auth
    const response = await fetch('/api/premium', {
      headers: {
        'Authorization': `x402 ${btoa(JSON.stringify({ signatures: [signature] }))}`
      }
    });
  };

  return <button onClick={handlePayment}>Pay 0.01 SOL</button>;
}

โœจThat's it!

You now have a fully functional micropayment system. The middleware handles:

โœ“ Payment verification
โœ“ Session management
โœ“ Anti-replay protection
โœ“ Error handling

Deployment

One-Click Deploy

Deploy Your Own Facilitator

For production, spin up a high-performance verification node in seconds. Zero config files to editโ€”just bring your RPC URL.

2Configuration Workflow

Initiate Deployment

Select your preferred cloud provider above. You'll be redirected to their setup wizard.

๐Ÿ’ก No account? Railway allows guest deployments.

Configure Environment Variables

โš ๏ธ Important: Default is Devnet!

The facilitator deploys with devnet by default. For mainnet production, you must change the environment variables after deployment.

https://mainnet.helius-rpc.com/?api-key=...

Default: https://api.devnet.solana.com

mainnet-beta
devnet (default)

Verify & Connect

Once deployed, verify your node is active with the health check.

GET /health
GET /metrics

Deployment FAQ

What happens when I click Deploy?

The platform (Railway/Heroku/Render) will automatically fork this open-source repository into your own account. It will then pause to ask for your Environment Variables before building the Go binaries.

Can I change networks later?

Yes. Simply go to your project dashboard's "Variables" or "Settings" tab and update SOLANA_NETWORK to mainnet-beta or devnet.

How It Works

01Lifecycle of a Payment

Request

Client hits a protected endpoint.

Challenge

Server returns 402 + payment URL.

Payment

Wallet signs and sends SOL.

Unlock

Server verifies and issues session.

Protocol Architecture

Client

Browser / Agent

x402

Middleware

Next.js / Bun

RPC

Solana

Mainnet / Devnet

Wallet Topology

Consumer to API

Standard paywall flow for web users.

Payer

User Wallet

Receiver

CREATOR_WALLET

Agent to Agent

Autonomous machine payments.

Payer

Agent Wallet

Receiver

CREATOR_WALLET

Configuration Checklist

Consumer Setup

  • CREATOR_WALLET_ADDRESS is set
  • RPC_URL is reachable
  • Devnet SOL in user wallet

Agent Setup

  • AGENT_KEYPAIR_SECRET is set
  • Fund agent wallet with SOL
  • Configure agent fee tier

AI Agent Payments

Machines playing
by human rules.

x402 allows AI agents to negotiate and fulfill payments autonomously. By using standard HTTP error 402, agents can identify payment requirements and resolve them using their own keypairs.

Try AI Agent Demo
Latency: 140ms

Detect 402 Challenge

Agent receives 402 Payment Required with metadata.

Sign & Authorize

Agent signs tx with AGENT_KEYPAIR_SECRET.

Validation

Resource server validates the on-chain signature.

Technical Implementation

Autonomous Wallets

Agents manage their own SOL balances for pay-per-request.

Cloud Integration

Deploy agents on Vercel AI SDK or similar stacks.

Usage Metrics

Track spending and efficiency per agent session.

New in v3.5

Give Your Agents
Financial Autonomy.

The createPayingAgent helper is the sexiest way to equip your AI with a wallet. It handles balance checks, x402 negotiation, and transaction signing automatically.

Zero Config
Any LLM Framework
Auto-Healing

Integration Guide

Instead of manually constructing transactions, your agent simply "fetches" URLs. If the URL is behind a paywall (402 Payment Required), the agent automatically negotiates the price, signs the transaction, and retries the request with the payment proof attached.

How it Works: The Client-Server Handshake

It takes two to tango using the x402 protocol. Your agent is the Client, but the URL it fetches must be a x402-enabled Server.

The Server (API)

Must throw 402 Payment Required when unpaid.

GET /premium
< 402 Payment Required
< WWW-Authenticate: X402 ...
// also accepts payment-required
The Client (Agent)

Catches the 402, pays on-chain, and retries.

> Pays 0.001 SOL
GET /premium
> Authorization: X402 ...

0
Prerequisite: Protect your API (Next.js)

Currently, we provide a plug-and-play middleware for Next.js App Router.

i
Other Languages: Libraries for Go, Express, Rust, and Python are on our roadmap. For now, you can implement the server-side logic manually by checking for the Authorization: X402 ... header and verifying the signature.
Source Code
// app/api/premium-data/route.ts
import { createX402Middleware } from '@alleyboss/micropay-solana-x402-paywall/next';

const withPayment = createX402Middleware({
    walletAddress: process.env.CREATOR_WALLET_ADDRESS!,
    price: '1000000', // 0.001 SOL
    network: 'devnet'
});

// This handler ONLY runs if the client (Agent) has paid!
export const GET = withPayment(async (req) => {
    return Response.json({ secret: "This data was paid for on-chain!" });
});

1
Basic Usage

Source Code
import { createPayingAgent } from '@alleyboss/micropay-solana-x402-paywall/agent';

// 1. Initialize the agent
const agent = createPayingAgent(process.env.SOLANA_PRIVATE_KEY!, {
    network: 'devnet',
    maxPaymentPerRequest: 100_000_000n // Safety cap: 0.1 SOL
});

// 2. Simply fetch premium content
// The agent handles the 402 challenge-response loop automatically
const response = await agent.get('https://api.example.com/premium-data');
const data = await response.json();

console.log('Premium Data:', data);

2
Checking Balance

Source Code
// Check if agent has enough funds before complex operations
const { sol, lamports } = await agent.getBalance();

if (sol < 0.05) {
    console.warn('Agent wallet low on funds! Please top up.');
}

3
Advanced Configuration

Protect your agent from draining its wallet on malicious sites.

Source Code
const agent = createPayingAgent(key, {
    network: 'mainnet-beta',
    rpcUrl: 'https://api.mainnet-beta.solana.com',
    
    // Security Constraints
    maxPaymentPerRequest: 5_000_000n, // Max 0.005 SOL per call
    allowedRecipients: ['H3...'],      // Only pay specific wallets
    
    // Performance
    commitment: 'confirmed'
});
โ†’
Agent Framework Compatible: This helper returns a standard fetch-compatible interface. You can pass agent.fetch directly to any library that accepts a custom fetcher (like OpenAI, LangChain, or Eliza) to seamlessly enable payments within those frameworks.

PayAI Format

The Universal Standard.

Native support for the PayAI payment format - a universal protocol that enables cross-chain payment discovery. Micropay automatically detects and transforms PayAI payloads into x402 compliant authorizations.

Multi-chain
Stateless
Async
Universal
Learn more at payai.network

PayAI Payload Structure

Source Code
{
  "scheme": "exact-svm",
  "networkId": "solana-devnet",
  "paymentDetails": {
    "amount": "10000000",
    "recipient": "YourWallet..."
  }
}
Protocol Note

The exact-svm scheme ensures sub-second verification by matching transactions directly.

Network Mapping

solana

solana:5eykt...pY1vz

solana-devnet

solana:EtWTR...U2xqa

base

eip155:8453

Cross-Chain Discovery

Enable users to pay on one chain and unlock on another. Micropay handles bridging confirmation automatically.

01
Payment Request

402 response includes PayAI bridge link.

02
Verification

Oracle network confirms cross-chain state.

03
Settlement

Resource server issues localized session.

Verification Modes

Choose Your Trust Model.

Micropay supports three distinct trust topologies. Default to the managed PayAI Network, run your own Private Facilitator, or go fully Self-Sovereign with direct RPC verification.

Source Code
const withMicropay = createX402Middleware({
    walletAddress: 'YOUR_WALLET',
    price: '1000000',
    
    // Mode 1: Hosted (Default)
    // Uses PayAI Network
    
    // Mode 2: Private Verified
    // Point to your own Railway/Docker container
    facilitatorUrl: 'https://my-facilitator.railway.app',

    // Mode 3: Self-Sovereign
    // Verify directly against Solana RPC (No Facilitator)
    rpcUrl: process.env.NEXT_PUBLIC_RPC_URL
});

Hosted (PayAI)

  • Zero Setup
  • Global Cache
  • Managed Reliability

Private (Railway)

  • Your Infrastructure
  • Custom Logic
  • Private Logs

Sovereign (RPC)

  • Trustless
  • Direct Blockchain
  • Maximum Control

Signature Registry

Micropay uses an internal registry to track and verify on-chain signatures. This prevents replay attacks and ensures each payment is only used once.

Deterministic

Signatures are hashed and stored for lookup.

High Performance

LRU caching for sub-millisecond lookups.

Source Code
// Manual Verification Example
const isValid = await server.verify(signature);
if (!isValid) throw new Error('Payment already claimed!');

Facilitator API Format

The custom facilitator accepts a standard x402 verification payload. You can use this to integrate payment verification into any backend.

Source Code
POST /verify
Content-Type: application/json

{
  "paymentPayload": {
    "x402Version": 2,
    "payload": {
      "signature": "5eykt...pY1vz"
    }
  },
  "paymentRequirements": {
    "payTo": "YOUR_WALLET",
    "amount": "1000000",
    "asset": "SOL",
    "network": "devnet"
  }
}

Installation

Start Building Today.

Source Code
npm install @alleyboss/micropay-solana-x402-paywall @solana/web3.js
Typescript Ready
Tree Shakeable
Small Bundle
โš™๏ธ

Configuration

Tweak the resource server to match your security and performance needs.

Resource Server Options

Source Code
const server = new x402ResourceServer({
  // Use your own self-hosted facilitator
  facilitator: new RemoteFacilitator('https://my-facilitator.railway.app'), 
  walletAddress: CREATOR_ADDR,
  
  // Optional config
  registry: new RedisRegistry(), // Custom storage
  ttl: 3600, // Session duration in seconds
  network: 'devnet'
});

Quick Start

The 1-Minute Protection.

Protect any API route with just a few lines of code. Micropay handles the 402 response, verification, and session persistence.

Source Code
import { createX402Middleware } from '@alleyboss/micropay-solana-x402-paywall/next';

const withPayment = createX402Middleware({
  walletAddress: process.env.CREATOR_WALLET_ADDRESS!,
  price: '10000000', // 0.01 SOL
  network: 'devnet',
  // Optional: Use your self-hosted facilitator
  facilitatorUrl: 'https://my-facilitator.railway.app'
});

export const GET = withPayment(async (req) => {
  return Response.json({ status: 'Unlocked!' });
});

Middleware

E

Express.js

For Node backends

Source Code
import { x402Middleware } from '@alleyboss/micropay-solana-x402-paywall/express';

app.get('/api/data', x402Middleware(server, {
  accepts: { amount: '1000' }
}), handler);
N

Next.js

For App Router

Source Code
import { createX402Middleware } from '@alleyboss/micropay-solana-x402-paywall/next';

export const GET = withPayment(async (req) => {
  return Response.json({ ok: true });
});

The Execution Flow

01

Interception

Middleware catches request & checks for Authorization header.

02

Validation

On-chain verification or PayAI facilitator check.

03

Persistence

Verified session is stored in an HTTP-only cookie.

04

Grant

Downstream handler receives the verified payer object.

Security

Replay Protection

Every transaction signature is registered and can only be used once per session. This prevents malicious actors from "replaying" a valid payment to unlock multiple resources.

Stateless Verification

By using Solana as the source of truth, the middleware doesn't need to maintain a database of users. If the on-chain data matches the request, access is granted.

Agent Demo Configuration

To enable the **Agent-to-Agent** payment demo using your own infrastructure:

1

Deploy Facilitator

Deploy your facilitator to Railway/Heroku using the One-Click button above.

2

Get Service URL

On Railway: Click your project โ†’ Click the Service โ†’ Copy the Public Networking URL (e.g. https://my-app.up.railway.app).

3

Set Environment Variable

Add this to your local or deployed demo environment:

PLATFORM_FACILITATOR_URL=https://your-app.up.railway.app

Verification Architecture

This demo implements a "Split Architecture" (Toly Design) to optimize for both trust and convenience:

Standard Flow

Agent โ†’ API payments use the managed PayAI Network. Zero-config, high availability for standard SaaS interactions.

Sovereign Flow

Agent โ†’ Agent payments use your Custom Railway Node. Demonstrates true p2p sovereignty and private infrastructure verification.

Priority Fees Support

Under high network congestion, Micropay supports Compute Budget instructions to ensure your payment transactions land on-chain without delay.

Activated
Always sub-second landing
Source Code
// SDK adds automatically
tx.add(ComputeBudgetProgram.setComputeUnitPrice({
  microLamports: 1000
}));

Troubleshooting

Network Error: Fetch Failed

Node 18+ resolves localhost to IPv6 (::1). Use http://127.0.0.1:3000 instead of localhost in your APP_URL.

Node.jsNetworking

Payment Not Verifying

Check CREATOR_WALLET_ADDRESS and lamport decimals. Use a better RPC provider if hits rate limits.

RPCVerification

Session Expired

Increase SESSION_DURATION_HOURS or ensure SESSION_SECRET is stable across deployments.

SessionsJWT

Common Error Codes

402 Payment RequiredResource protected by x402. Payer must provide auth header.
403 ForbiddenInvalid session or verified payment does not match price.
503 Service UnavailableRPC node failed or facilitator is offline.

Pricing

Developer-First

Free & Open Source

Micropay is MIT licensed and free to use. Zero platform fees, zero middleman. You keep 100% of your earnings.

Platform Fees0%
Network FeesSolana Gas Only
SupportCommunity Driven

Roadmap

Q1 2024

Core Protocol

Initial x402 implementation with SVM support.

Q2 2024

SPL Standard

Native support for USDC and major SPL tokens.

Q3 2024

EVM Briding

Expanding the x402 standard to Base and Arbitrum.

API Reference

@.../agent
executeAgentPaymentgetAgentBalance
@.../express
x402MiddlewareExpressAdapter
@.../next
createX402Middleware
@.../pricing
getSolPriceusdToLamports
โ˜•

Support Dev.

Micropay is open source. If you find it useful, consider supporting core development with a small donation.

7fPjNJaEHtepp1ZRr6GsaW1k22U1FupQtwuHUkTb6Xg9