Skip to content

Repository files navigation

402chainz

A micropayment layer using the x402 protocol. Companies register API keys (Anthropic, Midjourney) mapped to Coinbase wallet addresses. Users pay per request via x402 headers instead of companies footing demo costs.

Tech Stack

  • Server: Node.js + Express + TypeScript
  • Database: MongoDB Atlas
  • Payments: x402 protocol + @coinbase/cdp-sdk
  • Proxy: Axios for API forwarding

Features

  • x402 payment protocol implementation
  • Pay-per-use API proxy for Anthropic and Midjourney
  • MongoDB-backed company and usage tracking
  • TypeScript with strict type safety
  • Graceful shutdown handling
  • Web-based company signup page
  • Chrome extension for automatic x402 payments

Getting Started

Prerequisites

  • Node.js 18+ and npm
  • MongoDB Atlas account (or local MongoDB)
  • (Optional) Coinbase CDP API credentials for future blockchain verification

Installation

  1. Clone the repository
git clone <repo-url>
cd 402chainz
  1. Install dependencies
npm install
  1. Configure environment
cp .env.example .env
# Edit .env and add your MONGODB_URI
  1. Seed the database with test companies
npm run seed
  1. Start the development server
npm run dev

The server will start on http://localhost:3000.

Company Signup Page

A web-based interface for companies to register and manage their API configurations.

Access

Visit http://localhost:3000/signup.html after starting the server.

Features

  • Create company profile with wallet address
  • Add API keys for supported providers (OpenAI, Anthropic, Perplexity)
  • Set custom pricing per request
  • Auto-generates company slug from name
  • Validates Ethereum wallet addresses

Files

  • public/signup.html - Registration form
  • public/signup.css - Styling
  • public/signup.js - Form handling and API calls

Chrome Extension

An MVP Chrome extension that automatically handles x402 payments.

Quick Start

  1. Navigate to the extension directory:

    cd chrome-extension
  2. Add placeholder icons to icons/ directory (or remove icon references from manifest.json)

  3. Load in Chrome:

    • Go to chrome://extensions/
    • Enable "Developer mode"
    • Click "Load unpacked"
    • Select the chrome-extension directory
  4. Click the extension icon and enter your Coinbase wallet address

Features

  • Automatic detection of HTTP 402 responses
  • User-controlled payment approvals via notifications
  • Real-time spending tracker (floating widget)
  • Session spending analytics
  • Mock payment signing (for MVP demonstration)

How It Works

  1. Background service worker monitors requests for 402 responses
  2. Shows notification asking user to approve payment
  3. On approval, creates signed payment header
  4. Retries request with X-PAYMENT header
  5. Updates spending tracker and floating widget

See chrome-extension/README.md for detailed documentation.

API Endpoints

Company Management

POST /api/companies - Register a new company

curl -X POST http://localhost:3000/api/companies \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My Company",
    "slug": "my-company",
    "description": "Company description",
    "coinbaseWalletAddress": "0x..."
  }'

GET /api/companies/:slug - Get company info

curl http://localhost:3000/api/companies/ai-research-lab

POST /api/companies/:slug/keys - Add API key

curl -X POST http://localhost:3000/api/companies/my-company/keys \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "anthropic",
    "apiKey": "sk-ant-...",
    "costCentsPerRequest": 10
  }'

Pricing

GET /api/pricing/:slug - Get pricing info

curl http://localhost:3000/api/pricing/ai-research-lab

x402-Protected Proxy

ALL /api/proxy/:slug/:provider/* - Proxy with payment

Without payment header (returns 402):

curl -X POST http://localhost:3000/api/proxy/ai-research-lab/anthropic/v1/messages \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 100,
    "messages": [{"role": "user", "content": "Hello"}]
  }'

With payment header:

curl -X POST http://localhost:3000/api/proxy/ai-research-lab/anthropic/v1/messages \
  -H "Content-Type: application/json" \
  -H "X-PAYMENT: <base64-encoded-payment>" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 100,
    "messages": [{"role": "user", "content": "Hello"}]
  }'

x402 Payment Flow

Step 1: Request Without Payment

Client sends request without X-PAYMENT header → Server returns 402 with payment requirements:

{
  "x402Version": 1,
  "error": "X-PAYMENT header is required",
  "accepts": [{
    "scheme": "exact",
    "network": "base-sepolia",
    "maxAmountRequired": "100000",
    "payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1",
    "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
    "resource": "/api/proxy/ai-research-lab/anthropic/v1/messages",
    "description": "API request to anthropic via AI Research Lab",
    "mimeType": "application/json",
    "maxTimeoutSeconds": 60,
    "extra": { "name": "USDC", "version": "2" }
  }]
}

Step 2: Request With Payment

Client generates payment header and retries → Server validates payment → Forwards to API → Records usage → Returns response

Payment Header Structure

{
  signature: string,
  authorization: {
    from: string,      // User's wallet
    to: string,        // Company wallet
    value: string,     // Amount in atomic units (USDC: 6 decimals)
    validAfter: number,   // Unix timestamp
    validBefore: number,  // Unix timestamp
    nonce: string
  }
}

Base64 encode this JSON and send as X-PAYMENT header.

MVP Scope

  • ✅ Payment header validation (structure, amount, time bounds)
  • ✅ API proxy for Anthropic and Midjourney
  • ✅ Usage tracking in MongoDB
  • ❌ Blockchain signature verification (future)
  • ❌ Nonce replay protection (future)
  • ❌ API key encryption (future)

Project Structure

402chainz/
├── src/
│   ├── server.ts                    # Entry point
│   ├── app.ts                       # Express configuration
│   ├── config/
│   │   ├── database.ts              # MongoDB singleton
│   │   ├── environment.ts           # Env validation
│   │   └── constants.ts             # x402 constants
│   ├── routes/
│   │   ├── company.routes.ts        # Company CRUD
│   │   ├── pricing.routes.ts        # Pricing endpoint
│   │   ├── proxy.routes.ts          # x402-protected proxy
│   │   └── index.ts                 # Route aggregator
│   ├── middleware/
│   │   ├── errorHandler.ts          # Error handling
│   │   ├── x402Payment.ts           # x402 middleware
│   │   └── asyncHandler.ts          # Async wrapper
│   ├── services/
│   │   ├── payment.service.ts       # x402 validation
│   │   ├── company.service.ts       # Company logic
│   │   ├── proxy.service.ts         # API forwarding
│   │   └── usage.service.ts         # Usage tracking
│   └── types/
│       ├── x402.types.ts            # x402 protocol types
│       ├── api.types.ts             # API types
│       └── express.d.ts             # Express augmentation
├── public/
│   ├── signup.html                  # Company registration page
│   ├── signup.css                   # Signup page styles
│   └── signup.js                    # Signup page logic
├── chrome-extension/
│   ├── manifest.json                # Extension manifest (v3)
│   ├── popup.html                   # Extension popup UI
│   ├── popup.js                     # Popup logic
│   ├── background.js                # Service worker (402 detection)
│   ├── content.js                   # Content script (widget)
│   ├── content.css                  # Widget styles
│   ├── icons/                       # Extension icons
│   └── README.md                    # Extension documentation
├── scripts/
│   └── seed.ts                      # Database seed
└── package.json

Development

Build

npm run build

Start production

npm start

Seed database

npm run seed

Test Companies

After running npm run seed, you'll have:

  1. ai-research-lab

    • Anthropic API at $0.10/request
    • Wallet: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1
  2. creative-studio

    • Midjourney at $0.25/request
    • Anthropic at $0.15/request
    • Wallet: 0x8626f6940E2eb28930eFb4CeF49B2d1F2C9C1199

Environment Variables

# Server
PORT=3000
NODE_ENV=development

# MongoDB
MONGODB_URI=mongodb+srv://...

# x402 Configuration
X402_NETWORK=base-sepolia
X402_USDC_CONTRACT=0x036CbD53842c5426634e7929541eC2318f3dCF7e
X402_TIMEOUT_SECONDS=60

Future Enhancements

  • Blockchain signature verification (ERC-3009)
  • Nonce replay protection
  • API key encryption in database
  • Rate limiting
  • Additional API providers (OpenAI, etc.)
  • WebSocket support for streaming
  • Analytics dashboard
  • Admin UI

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages