Skip to content

Repository files navigation

402fly: 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 402fly?

402fly 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

402fly is available in Python, TypeScript/Node.js, Go, and Rust, 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

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

Quick Start

Server (Python - FastAPI)

from fastapi import FastAPI
from fly402fastapi import payment_required, Fly402Config, init_fly402

app = FastAPI()

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

Server (TypeScript - Express.js)

import express from 'express';
import { paymentRequired, initFly402, Fly402Config } from '@x402fly/express';

const app = express();
initFly402(new Fly402Config({
    paymentAddress: "YOUR_WALLET_ADDRESS",
    tokenMint: "FLY402_TOKEN_MINT"
}));

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

app.listen(3000);

Client (Python - Auto-Payment)

from fly402client import Fly402AutoClient
from solders.keypair import Keypair

client = Fly402AutoClient(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 { Fly402AutoClient } from '@x402fly/client';
import { Keypair } from '@solana/web3.js';

const client = new Fly402AutoClient(keypair);

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

LangChain Agent

from fly402langchain 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 fly402core fly402client fly402fastapi

# Or using uv (recommended)
uv sync

TypeScript Packages

# Using pnpm (recommended)
pnpm install

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

Development Installation

Python (uv monorepo):

git clone https://github.com/SerPepe/402fly.git
cd 402fly
uv sync

TypeScript (pnpm monorepo):

git clone https://github.com/SerPepe/402fly.git
cd 402fly
pnpm install
pnpm run build

See SETUP.md for detailed setup instructions.

Project Structure

402fly/
├── packages/
│   ├── python/                     # Python packages (uv monorepo)
│   │   ├── 402flycore/          # Core protocol (PyPI: fly402core)
│   │   ├── 402flyfastapi/       # FastAPI middleware (PyPI: fly402fastapi)
│   │   ├── 402flyclient/        # HTTP client (PyPI: fly402client)
│   │   ├── 402flylangchain/     # LangChain integration (PyPI: fly402langchain)
│   │   └── 402flylanggraph/     # LangGraph integration (PyPI: fly402langgraph)
│   │
│   ├── typescript/                 # TypeScript packages (pnpm monorepo)
│   │   ├── fly402-core/          # Core protocol (npm: @x402fly/core)
│   │   ├── fly402-express/       # Express.js middleware (npm: @x402fly/express)
│   │   ├── fly402-client/        # HTTP client (npm: @x402fly/client)
│   │   ├── fly402-nextjs/        # Next.js integration (npm: @x402fly/nextjs)
│   │   ├── fly402-langchain/     # LangChain.js integration (npm: @x402fly/langchain)
│   │   └── fly402-langgraph/     # LangGraph.js integration (npm: @x402fly/langgraph)
│   │
│   ├── go/                         # Go packages
│   │   ├── fly402-core/          # Core protocol (Go)
│   │   ├── fly402-client/        # HTTP client (Go)
│   │   ├── fly402-nethttp/       # net/http middleware (Go)
│   │   └── fly402-echo/          # Echo framework integration (Go)
│   │
│   └── rust/                       # Rust packages (Cargo workspace)
│       ├── fly402-core/          # Core protocol (crates.io: fly402-core)
│       ├── fly402-client/        # HTTP client (crates.io: fly402-client)
│       ├── fly402-rocket/        # Rocket framework integration (crates.io: fly402-rocket)
│       └── fly402-actix/         # Actix Web integration (crates.io: fly402-actix)
│
├── examples/
│   ├── python/
│   │   ├── fastapi-server/         # Python FastAPI demo
│   │   ├── langchain-agent/        # Python LangChain agent
│   │   └── langgraph-workflow/     # Python LangGraph workflow
│   ├── typescript/
│   │   └── express-server/         # TypeScript Express.js demo
│   ├── 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
    └── 402fly-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

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: Ecosystem

  • Flask middleware
  • Django middleware
  • Next.js integration
  • Additional agent frameworks
  • CLI tools

🔲 Phase 6: Advanced

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

Configuration

Environment Variables

FLY402_PAYMENT_ADDRESS=YourSolanaWalletAddress
FLY402_TOKEN_MINT=YOUR_TOKEN_MINT_ADDRESS
FLY402_NETWORK=solana-devnet
FLY402_RPC_URL=https://api.devnet.solana.com

Code Configuration

from fly402fastapi import Fly402Config, init_fly402

config = Fly402Config(
    payment_address="YOUR_WALLET",
    token_mint="USDC_MINT",
    network="solana-devnet"
)
init_fly402(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 fly402core.testing import MockSolanaPaymentProcessor

processor = MockSolanaPaymentProcessor()
processor.balance = 100.0

# Use in tests without real blockchain
client = Fly402AutoClient(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/SerPepe/402fly.git
cd 402fly

# Install development dependencies
pip install fly402core[dev] fly402client[dev] fly402fastapi[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

402fly is released under the MIT License.

Acknowledgments


Built with ❤️ for the autonomous AI economy

Get Started | Documentation | Examples | Contribute

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages