Menu

Explorer & Settings

Tempo Explorer Submit Project
Back to all projects

openlibx402

by openlibx402 · Updated 3 months ago

An open-source library for AI-native x402 integrations in the Solana ecosystem. Built for Python and Node.js, distributed via PyPI and npm, with server implementations for FastAPI and Express.js. Accelerate.

In the AI payments ecosystem

openlibx402 is an early-stage TypeScript project in the AI payments / x402 ecosystem, focused on express, fastapi, langchain, langgraph. It currently has 4 GitHub stars and 1 forks, and sits alongside related tools like a2a-server, ampersend-sdk, agoragentic-integrations, x402-sdk, trust-gated-agent-example, paynode-sdk-js.

README.md View on GitHub →

OpenLibx402: Autonomous Payments for AI Agents

Enable AI agents and web APIs to autonomously pay for services using HTTP 402 "Payment Required" and Solana blockchain

License: MIT Python 3.8+ TypeScript Node.js 18+ Go 1.21+ Rust 1.70+

What is OpenLibx402?

OpenLibx402 is a library ecosystem that implements the X402 protocol - an open standard for enabling AI agents to autonomously pay for API access using HTTP 402 "Payment Required" status code and blockchain micropayments on Solana.

Key Features

One-Line Integration - Add payments to APIs with a single decorator 🤖 AI-Native - Built specifically for autonomous agent workflows ⚡ Instant Settlement - Payments settle in ~200ms on Solana 💰 Micropayments - Support payments as low as $0.001 🔐 No Accounts - No API keys, subscriptions, or manual billing 🌐 Chain-Agnostic Design - Solana first, architected for multi-chain 🛠️ Framework Integrations - FastAPI, LangChain, LangGraph, and more

Available in Multiple Languages

OpenLibx402 is available in Python, TypeScript/Node.js, Go, Rust, Java, and Kotlin, with full feature parity:

  • 🐍 Python: FastAPI, LangChain, LangGraph
  • 📦 TypeScript: Express.js, Next.js, LangChain.js, LangGraph.js
  • 🐹 Go: net/http, Echo framework
  • 🦀 Rust: Rocket, Actix Web
  • Java: HTTP client with AutoCloseable resources
  • 🎯 Kotlin: Coroutine-first API with suspend functions

All implementations provide both server and client libraries with comprehensive examples.

Quick Start

Server (Python - FastAPI)

from fastapi import FastAPI
from openlibx402_fastapi import payment_required

app = FastAPI()

@app.get("/premium-data")
@payment_required(
    amount="0.10",
    payment_address="YOUR_WALLET_ADDRESS",
    token_mint="USDC_MINT_ADDRESS"
)
async def get_premium_data():
    return {"data": "Premium content"}

Server (TypeScript - Express.js)

import express from 'express';
import { paymentRequired, initX402, X402Config } from '@openlibx402/express';

const app = express();
initX402(new X402Config({
    paymentAddress: "YOUR_WALLET_ADDRESS",
    tokenMint: "USDC_MINT_ADDRESS"
}));

app.get('/premium-data',
    paymentRequired({ amount: '0.10' }),
    (req, res) => res.json({ data: 'Premium content' })
);

app.listen(3000);

Client (Python - Auto-Payment)

from openlibx402_client import X402AutoClient
from solders.keypair import Keypair

client = X402AutoClient(wallet_keypair=keypair)

# Automatically handles 402 and pays
response = await client.fetch("https://api.example.com/premium-data")
data = response.json()

Client (TypeScript - Auto-Payment)

import { X402AutoClient } from '@openlibx402/client';
import { Keypair } from '@solana/web3.js';

const client = new X402AutoClient(keypair);

// Automatically handles 402 and pays
const response = await client.get('https://api.example.com/premium-data');
const data = response.data;

Client (TypeScript - Privy Server Wallet)

import { PrivyX402Client, PrivyX402Config } from '@openlibx402/privy';

const config = new PrivyX402Config({
  appId: process.env.PRIVY_APP_ID,
  appSecret: process.env.PRIVY_APP_SECRET,
  walletId: process.env.PRIVY_WALLET_ID,
});

const client = new PrivyX402Client(config);
await client.initialize();

// Automatically handles 402 and pays using Privy server wallet
const response = await client.get('https://api.example.com/premium-data');

LangChain Agent

from openlibx402_langchain import create_x402_agent

agent = create_x402_agent(
    wallet_keypair=keypair,
    max_payment="5.0"
)

response = agent.run("Get premium market data from the API")

Installation

Python Packages

# Using pip
pip install openlibx402-core openlibx402-fastapi openlibx402-client

# Or using uv (recommended)
uv sync

TypeScript Packages

# Using pnpm (recommended)
pnpm install

# Or using npm
npm install @openlibx402/core @openlibx402/express @openlibx402/client

Development Installation

Python (uv monorepo):

git clone https://github.com/openlibx402/openlibx402.git
cd openlibx402
uv sync

TypeScript (pnpm monorepo):

git clone https://github.com/openlibx402/openlibx402.git
cd openlibx402
pnpm install
pnpm run build

See SETUP.md for detailed setup instructions.

Project Structure

openlibx402/
├── packages/
│   ├── python/                     # Python packages (uv monorepo)
│   │   ├── openlibx402-core/          # Core protocol
│   │   ├── openlibx402-fastapi/       # FastAPI middleware
│   │   ├── openlibx402-client/        # HTTP client
│   │   ├── openlibx402-langchain/     # LangChain integration
│   │   └── openlibx402-langgraph/     # LangGraph integration
│   │
│   ├── typescript/                 # TypeScript packages (pnpm monorepo)
│   │   ├── openlibx402-core/          # Core protocol (TS)
│   │   ├── openlibx402-express/       # Express.js middleware
│   │   ├── openlibx402-client/        # HTTP client (TS)
│   │   ├── openlibx402-langchain/     # LangChain.js integration
│   │   ├── openlibx402-langgraph/     # LangGraph.js integration
│   │   └── openlibx402-privy/         # Privy server wallet integration
│   │
│   ├── go/                         # Go packages
│   │   ├── openlibx402-core/          # Core protocol (Go)
│   │   ├── openlibx402-client/        # HTTP client (Go)
│   │   ├── openlibx402-nethttp/       # net/http middleware
│   │   └── openlibx402-echo/          # Echo framework integration
│   │
│   ├── rust/                       # Rust packages (Cargo workspace)
│   │   ├── openlibx402-core/          # Core protocol (Rust)
│   │   ├── openlibx402-client/        # HTTP client (Rust)
│   │   ├── openlibx402-rocket/        # Rocket framework integration
│   │   └── openlibx402-actix/         # Actix Web integration
│   │
│   ├── java/                       # Java packages (Maven)
│   │   ├── openlibx402-core/          # Core protocol (Java)
│   │   └── openlibx402-client/        # HTTP client (Java)
│   │
│   └── kotlin/                     # Kotlin packages (Gradle)
│       ├── openlibx402-core/          # Core protocol (Kotlin)
│       └── openlibx402-client/        # HTTP client (Kotlin)
│
├── examples/
│   ├── python/
│   │   ├── fastapi-server/         # Python FastAPI demo
│   │   ├── langchain-agent/        # Python LangChain agent
│   │   └── langgraph-workflow/     # Python LangGraph workflow
│   ├── typescript/
│   │   ├── express-server/         # TypeScript Express.js demo
│   │   └── privy-agent/            # Privy server wallet agent
│   ├── go/
│   │   ├── nethttp-server/         # Go net/http demo
│   │   └── echo-server/            # Go Echo demo
│   └── rust/
│       ├── rocket-server/          # Rust Rocket demo
│       └── actix-server/           # Rust Actix Web demo
│
├── pnpm-workspace.yaml             # TypeScript monorepo config
├── pyproject.toml                  # Python monorepo config
├── package.json                    # Root TypeScript package
├── Makefile                        # TypeScript build commands
└── docs/
    ├── SETUP.md                    # Setup guide
    └── openlibx402-technical-spec.md  # Technical specification

Examples

FastAPI Server

cd examples/fastapi-server
pip install -r requirements.txt
python main.py

Visit http://localhost:8000/docs for API documentation.

LangChain Agent

cd examples/langchain-agent
pip install -r requirements.txt
export OPENAI_API_KEY='your-key-here'
python main.py

LangGraph Workflow

cd examples/langgraph-workflow
pip install -r requirements.txt
python main.py

How It Works

┌─────────────┐         ┌──────────────┐         ┌────────────┐
│  AI Agent   │  ─1─→   │  API Server  │         │ Blockchain │
│   (Client)  │         │   (Server)   │         │  (Solana)  │
└─────────────┘         └──────────────┘         └────────────┘
       │                        │                        │
       │  GET /data             │                        │
       ├───────────────────────→│                        │
       │                        │                        │
       │  402 Payment Required  │                        │
       │  + Payment Details     │                        │
       │←───────────────────────┤                        │
       │                        │                        │
       │  Create & Broadcast    │                        │
       │  Payment Transaction   │                        │
       ├────────────────────────┼───────────────────────→│
       │                        │                        │
       │                        │   Verify Transaction   │
       │                        │←───────────────────────┤
       │                        │                        │
       │  GET /data             │                        │
       │  + Payment Auth Header │                        │
       ├───────────────────────→│                        │
       │                        │                        │
       │  200 OK + Data         │                        │
       │←───────────────────────┤                        │

Documentation

📚 Setup Guide - Complete setup for all languages 🚀 Technical Specification - Complete architecture

Language-Specific Documentation

🐍 Python README - Python implementation guide 📖 TypeScript README - TypeScript implementation guide 🐹 Go README - Go implementation guide 🦀 Rust README - Rust implementation guide ☕ Java README - Java implementation guide 🎯 Kotlin README - Kotlin implementation guide

Use Cases

For API Providers

  • 💵 Monetize APIs with pay-per-use pricing
  • 🚫 Eliminate API key management
  • ⚡ Instant payment settlement
  • 🛡️ No chargebacks or fraud risk

For AI Agents

  • 🔓 Access premium data without human intervention
  • 💰 Pay exactly for what you use
  • 🌍 No geographic restrictions
  • 🤖 Fully autonomous operation

Real-World Examples

  • 📊 Research agent paying per financial data point
  • 🎯 Trading bot accessing real-time market data
  • 📰 Content aggregator paying per article
  • 🖼️ Image generation API charging per image
  • ☁️ GPU compute charged per minute

Development Status

✅ Phase 1: Python (Complete)

  • Core package (Python)
  • FastAPI integration
  • Client library
  • LangChain integration
  • LangGraph integration
  • Example implementations
  • Testing utilities

✅ Phase 2: TypeScript (Complete)

  • Core package (TypeScript)
  • Express.js middleware
  • Client library (TS)
  • LangChain.js integration
  • LangGraph.js integration
  • pnpm monorepo setup
  • Example server & clients

✅ Phase 3: Go (Complete)

  • Core package (Go)
  • Client library (Go)
  • net/http middleware
  • Echo framework integration
  • Example servers

✅ Phase 4: Rust (Complete)

  • Core package (Rust)
  • Client library (Rust)
  • Rocket framework integration
  • Actix Web framework integration
  • Cargo workspace setup
  • Example servers

✅ Phase 5: Java & Kotlin (Complete)

  • Core package (Java)
  • Client library (Java)
  • Maven project setup
  • Core package (Kotlin)
  • Client library (Kotlin)
  • Gradle project setup
  • Coroutine support (Kotlin)
  • Documentation & examples

✅ Phase 6: Chatbot & RAGBot (Complete)

  • RAG Chatbot implementation (Deno + Hono)
  • RAGBot TypeScript package
  • OpenAI GPT-4o-mini integration
  • Pinecone vector database integration
  • USDC payment integration
  • Rate limiting (3 free queries/day)
  • SSE streaming responses
  • Deno Deploy deployment
  • Comprehensive documentation (9 pages)

🔲 Phase 7: Ecosystem Expansion

  • Flask middleware
  • Django middleware
  • Hono middleware
  • Additional agent frameworks
  • CLI tools

🔲 Phase 8: Advanced Features

  • Multi-chain support (Ethereum, Base)
  • Payment batching
  • Admin dashboard
  • Analytics & monitoring

Configuration

Environment Variables

X402_PAYMENT_ADDRESS=YourSolanaWalletAddress
X402_TOKEN_MINT=USDC_MINT_ADDRESS
X402_NETWORK=solana-devnet
X402_RPC_URL=https://api.devnet.solana.com

Code Configuration

from openlibx402_fastapi import X402Config, init_x402

config = X402Config(
    payment_address="YOUR_WALLET",
    token_mint="USDC_MINT",
    network="solana-devnet"
)
init_x402(config)

Security

🔐 Key Security Features:

  • Private keys never leave client
  • On-chain transaction verification
  • Nonce-based replay protection
  • Payment expiration timestamps
  • Maximum payment limits
  • HTTPS required for production

⚠️ Security Best Practices:

  • Never log private keys
  • Use environment variables for secrets
  • Validate all payment fields
  • Set reasonable payment timeouts
  • Implement rate limiting
  • Use hardware wallets in production

Testing

from openlibx402_core.testing import MockSolanaPaymentProcessor

processor = MockSolanaPaymentProcessor()
processor.balance = 100.0

# Use in tests without real blockchain
client = X402AutoClient(wallet_keypair=test_keypair)
client.client.processor = processor

Contributing

We welcome contributions! Here's how you can help:

  1. 🐛 Report bugs via GitHub Issues
  2. 💡 Suggest features or improvements
  3. 📝 Improve documentation
  4. 🔧 Submit pull requests
  5. ⭐ Star the repository

Development Setup

# Clone repository
git clone https://github.com/openlibx402/openlibx402.git
cd openlibx402

# Install development dependencies
pip install -e "packages/python/openlibx402-core[dev]"
pip install -e "packages/python/openlibx402-fastapi[dev]"
pip install -e "packages/python/openlibx402-client[dev]"

# Run tests
pytest packages/python/*/tests

# Format code
black packages/python/

FAQ

Q: Why Solana first? A: Solana offers ~200ms transaction finality and <$0.0001 fees, making it ideal for micropayments.

Q: Will this support other blockchains? A: Yes! The architecture is designed to be chain-agnostic. Ethereum and Base L2 support is planned.

Q: Do I need crypto knowledge to use this? A: Minimal. The libraries handle blockchain complexity. You just need a wallet and some tokens.

Q: How much do transactions cost? A: On Solana devnet/mainnet, transaction fees are <$0.0001. Payment amounts are configurable.

Q: Can agents really operate autonomously? A: Yes! Once configured with a wallet, agents can discover, pay for, and use APIs without human intervention.

Resources

License

OpenLibx402 is released under the MIT License.

Acknowledgments


Built with ❤️ for the autonomous AI economy

Get Started | Documentation | Examples | Contribute

All SDKs & Clients SDKs →