Skip to content

AlleyBo55/micropay-solana-x402-paywall

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

131 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SolanaPaywall πŸ”

A production-ready, per-article paywall system using the x402 protocol and Solana micropayments. No subscriptions needed β€” readers pay only for what they want to read.

License Solana x402

Read Docs One-Click Deploy View Demo

πŸ† Why Choose SolanaPaywall?

Building a robust crypto payment system is hard. We made it 10x easier.

  • πŸš€ Save 100+ Hours β€” Don't reinvent the wheel. We handled the edge cases, wallet connections, and verification logic.
  • πŸ›‘οΈ Bank-Grade Security β€” Implements the full x402 standard with server-side validation and anti-replay protection.
  • 🧩 Plug & Play β€” Drop-in React components and Next.js middleware. Get running in minutes, not weeks.
  • πŸ“± Mobile Optimized β€” Built-in Solana Pay QR support for seamless mobile wallet payments.

✨ Features

Turn any content into paid content with one-time micropayments on Solana. No subscriptions, no recurring chargesβ€”just pay to unlock.

Feature Description
πŸ’° SOL & USDC Payments Native SOL and SPL tokens (USDC, USDT)
πŸ” x402 Protocol Full HTTP 402 compliance with X-Payment-Required headers
πŸ”‘ JWT Sessions Secure unlock tracking with anti-replay
πŸ›‘οΈ Signature Store Prevent double-spend at app layer
πŸ”Œ Express & Next.js Zero-boilerplate middleware
πŸ’΅ Price Conversion USD↔SOL with multi-provider fallback
🌳 Tree-Shakeable Import only what you need
πŸ”„ RPC Fallback Automatic failover on RPC errors
⚑ Priority Fees Land transactions faster
πŸ“¦ Versioned Tx Full v0 transaction support

πŸš€ Quick Start

Prerequisites

  • Node.js 18+
  • npm or yarn
  • A Solana wallet (Phantom, Solflare, etc.)
  • An RPC URL (Tatum, Helius, QuickNode, etc.)

Installation

# Clone the repository
git clone https://github.com/AlleyBo55/micropay-solana-x402-paywall.git
cd solanapaywall

# Install dependencies
npm install

# Copy environment template
cp .env.example .env.local

# Edit .env.local with your configuration
nano .env.local

Environment Variables

# Network Configuration
NEXT_PUBLIC_SOLANA_NETWORK=devnet

# RPC Configuration (See "Flexible RPC Providers" below)
NEXT_PUBLIC_RPC_URL=https://api.devnet.solana.com
# Optional: Enable automatic fallback
ENABLE_RPC_FALLBACK=true
FALLBACK_RPC_URLS=https://api.devnet.solana.com,https://devnet.helius-rpc.com/your-key

# Payment Configuration
CREATOR_WALLET_ADDRESS=your_solana_wallet_address

# Session Configuration (JWT)
SESSION_SECRET=your_32_character_minimum_secret_key
SESSION_DURATION_HOURS=24

🌐 Flexible RPC Providers

This project is compatible with any Solana RPC provider. While the demo references Tatum.io for its free tier, you can use high-performance nodes from any provider:

  • Helius β€” Specialized Solana RPCs & APIs
  • QuickNode β€” Enterprise-grade infrastructure
  • Tatum β€” Multi-chain developer platform
  • Alchemy β€” Reliable blockchain infrastructure
  • GenesysGo β€” Shadow generic RPCs

Configuring Your RPC

In packages/lib/src/config.ts or via environment variables, you can set your primary and fallback options:

const config = {
  network: 'mainnet-beta',
  
  // Primary RPC (e.g. Helius)
  rpcUrl: 'https://mainnet.helius-rpc.com/?api-key=...',
  
  // Enable automatic fallback
  enableFallback: true,
  fallbackRpcUrls: [
    'https://api.mainnet-beta.solana.com', // Public node (rate limited but free)
    'https://solana-mainnet.gateway.tatum.io/...'
  ]
};

πŸ“– How It Works

x402 Protocol Flow

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                      USER'S BROWSER                          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                              β”‚
β”‚  1. User visits /article/premium-content                     β”‚
β”‚                          β”‚                                   β”‚
β”‚                          β–Ό                                   β”‚
β”‚  2. Server checks session β†’ Not unlocked                     β”‚
β”‚                          β”‚                                   β”‚
β”‚                          β–Ό                                   β”‚
β”‚  3. Page renders with blurred content + paywall overlay      β”‚
β”‚                          β”‚                                   β”‚
β”‚                          β–Ό                                   β”‚
β”‚  4. User clicks "Unlock" β†’ Connects wallet                   β”‚
β”‚                          β”‚                                   β”‚
β”‚                          β–Ό                                   β”‚
β”‚  5. User signs transaction β†’ SOL sent to creator             β”‚
β”‚                          β”‚                                   β”‚
β”‚                          β–Ό                                   β”‚
β”‚  6. Frontend sends signature to /api/payment/verify          β”‚
β”‚                          β”‚                                   β”‚
β”‚                          β–Ό                                   β”‚
β”‚  7. Server verifies on-chain β†’ Creates session cookie        β”‚
β”‚                          β”‚                                   β”‚
β”‚                          β–Ό                                   β”‚
β”‚  8. Content unlocks! Access valid for 24 hours               β”‚
β”‚                                                              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ€– Agent Chat Demo (NEW!)

Experience autonomous AI agent payments in action! The Agent Chat Demo showcases an AI agent that autonomously pays for premium API access using x402 micropayments on Solana.

Try It Out

cd packages/demo
npm install
npm run dev
# Visit http://localhost:3001/agent-chat

Features

Feature Description
🧠 AI Agent Chat with an agent that can pay for premium features
πŸ’³ Autonomous Payments Agent pays SOL micropayments without human interaction
πŸ”„ Live Streaming Watch payment steps in real-time during chat
πŸ“Š Premium Content Premium queries trigger actual Devnet payments

How It Works

  1. User asks a free question β†’ Agent responds normally
  2. User asks for "premium crypto analysis" β†’ Agent detects premium request
  3. Agent autonomously pays 0.002 SOL via x402 protocol
  4. Payment confirmed on-chain β†’ Premium content delivered
  5. All steps shown transparently in chat UI

Setup Agent Wallet

# Generate a new keypair
node -e "console.log(require('@solana/web3.js').Keypair.generate().secretKey.toString())"

# Add to .env.local
AGENT_KEYPAIR_SECRET=<comma-separated-bytes>

# Fund on Devnet
solana airdrop 2 <agent-address> --url devnet

🚒 Deploy to Vercel

Deploy with Vercel

Add these variables in your Vercel project settings:

Variable Description
NEXT_PUBLIC_SOLANA_NETWORK devnet or mainnet-beta
NEXT_PUBLIC_RPC_URL Your RPC URL (Tatum, Helius, etc.)
CREATOR_WALLET_ADDRESS Your Solana wallet
SESSION_SECRET Random 32+ char string
SESSION_DURATION_HOURS 24 (default)
DEFAULT_ARTICLE_PRICE_LAMPORTS 10000000 (0.01 SOL)

πŸ“ Project Structure

solanapaywall/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”‚   β”œβ”€β”€ payment/verify/    # Payment verification endpoint
β”‚   β”‚   β”‚   └── session/validate/  # Session validation endpoint
β”‚   β”‚   β”œβ”€β”€ article/[slug]/        # Dynamic article pages
β”‚   β”‚   β”œβ”€β”€ dashboard/             # Creator dashboard
β”‚   β”‚   β”œβ”€β”€ layout.tsx             # Root layout with providers
β”‚   β”‚   └── page.tsx               # Landing page
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ article/               # Article content renderer
β”‚   β”‚   β”œβ”€β”€ paywall/               # Paywall overlay & modal
β”‚   β”‚   └── providers/             # Wallet provider context
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── articles.ts            # Demo article configuration
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ session/               # JWT session management
β”‚   β”‚   β”œβ”€β”€ solana/                # Solana client & verification
β”‚   β”‚   └── x402/                  # x402 protocol helpers
β”‚   └── types/                     # TypeScript type definitions
β”œβ”€β”€ .env.example                   # Environment template
β”œβ”€β”€ vercel.json                    # Vercel deployment config
└── README.md                      # This file

πŸ”’ Security Architecture

We take security seriously. Here's why you can trust this library:

  1. Zero-Trust Verification
    We never trust the client. All payment signatures are verified on-chain (or via high-performance RPCs) by your backend before issuing access tokens.

  2. Anti-Replay Protection
    We implement a Signature Store (Redis/Memory) to ensure every transaction signature can only be used ONCE. This prevents "replay attacks" where a user tries to use the same payment proof multiple times.

  3. Stateless JWT Sessions
    Access is granted via signed HTTP-only cookies. No database required for session management. The proof of payment is cryptographically sealed in the token.

  4. No Private Keys Stored
    The library is designed to be non-custodial for the payment flow. User wallets sign transactions directly. Your server only needs a public key to verify.

πŸ”’ Security Best Practices

  • βœ… No hardcoded private keys
  • βœ… Session cookies are HTTP-only and secure
  • βœ… On-chain verification for all payments
  • βœ… Environment variables for sensitive config
  • βœ… CORS headers configured properly

Caution

SPL Token Validation Note: The library currently validates that tokens are sent to a valid token account, but does not perform the extra RPC call to verify that token account is owned by expectedRecipient. For high-value transactions, we recommend implementing a strict verification step server-side.

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

πŸ“„ License

MIT License - see LICENSE for details.

πŸ”— Resources


Built with ❀️ using x402 Protocol on Solana

About

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages