Skip to content

SamuelDharshi/Protocol402

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PROTOCOL402

The missing supply-side infrastructure for the Lepton ecosystem. One embed script that turns any creator's site into an x402-priced content marketplace — paste it once, and human readers, AI agents, and collaborators can all pay per article, settled on Arc in USDC, in under 500ms.

Full original product spec: PROTOCOL402_V2_FINAL_PRD.md


Table of contents


The idea

The web's original deal was: publish openly, receive traffic, monetize the traffic. AI broke that deal. Cloudflare alone reports 50 billion AI crawler requests a day — AI companies read creator content at industrial scale and pay creators $0 for it. Meanwhile, human micropayments have never worked either: card processing fees make a $0.04 article uneconomical, so creators are stuck with an all-or-nothing subscription paywall that converts 2–5% of visitors at best.

x402 (HTTP 402 "Payment Required", finally implemented after 28 years) plus Circle's Arc network fixes the rail — gasless, sub-cent USDC settlement is now technically possible. But nobody has built the thing a normal creator actually installs to use it. That's PROTOCOL402:

  • For creators: paste one <script> tag. Every article on the site becomes independently priced, sellable to humans and AI agents, with automatic revenue splits for collaborators and a path to recurring subscriptions — with zero blockchain knowledge required.
  • For human readers: an email-only wallet that auto-pays articles under a threshold you set, so reading feels like reading — not like a checkout flow.
  • For AI agents: a real x402 402 response with machine-readable pricing, a discovery API to find content in the first place, and instant cryptographic settlement — no human in the loop.

Four root failures, four fixes:

ROOT FAILURE                              PROTOCOL402'S FIX
─────────────────────────────────────    ─────────────────────────────────────
1. Payment floor (~$0.30 minimum         Nanopayments on Arc — gasless
   after card fees kills micropayments)   settlement down to $0.000001
2. Friction (readers won't connect a     PROTOCOL402 Wallet — email signup,
   wallet or paste an address)            silent auto-pay under a threshold
3. AI free-riding (crawlers read for     Dual-Mode 402 — same middleware,
   free at massive scale)                 humans see a widget, agents see JSON
4. Collaboration invisibility (only      Revenue Splits — every payment fans
   the account holder gets paid)          out to every collaborator, atomically

Architecture

 HUMAN READER          AI AGENT / BOT          COLLABORATOR       EXTERNAL CHAIN
 ───────────           ────────────────        ─────────────      ───────────────
 PROTOCOL402 Wallet     x402-fetch client       PROTOCOL402 Wallet  Ethereum / Base /
 (Arc-style USDC)       (auto-pays 402s)        (Arc-style USDC)    Polygon testnets
        │                      │                      ▲                   │
        └──────────┬───────────┘                      │          (wallet-ownership
                    ▼                                  │           signature + real
        ┌────────────────────────────┐                 │           on-chain balance
        │   EMBED SCRIPT (agent.js)  │                 │           read via public RPC)
        │   dual-mode 402 detection  │                 │                   │
        └──────────────┬─────────────┘                 │                   ▼
                        ▼                               │         ┌─────────────────┐
        ┌──────────────────────────────────┐            │         │ MULTICHAIN       │
        │        EXPRESS API (server/)      │            │         │ BRIDGE           │
        │  routes: price · pay · reader ·   │◄───────────┘         └─────────────────┘
        │  articles · discover · dashboard  │
        └──────────────────┬─────────────────┘
                            ▼
        ┌──────────────────────────────────────────────────┐
        │              AGENT DECISION ENGINE                │
        │  price()          — heuristic + optional Claude   │
        │  applySurge()     — traffic-based multiplier      │
        │  applyLoyalty()   — site history + reputation     │
        │  counteroffer()   — decline recovery after 8s     │
        │  aiPrice()        — 1.5x human rate for agents    │
        │  subscription()   — 5th-payment recurring offer   │
        └──────────────────────┬─────────────────────────────┘
                                ▼
        ┌──────────────────────────────────────────────────┐
        │                 PAYMENT ROUTER                     │
        │  1. verify EIP-712/EIP-3009 signed authorization   │
        │  2. settle on the real double-entry ledger         │
        │  3. fan out revenue splits to collaborators        │
        │  4. issue ERC-8004-style reputation attestation     │
        │  5. emit SSE event → creator dashboard             │
        └──────────────────────┬─────────────────────────────┘
                                ▼
        ┌──────────────────────────────────────────────────┐
        │      SQLite (real ledger, real replay-protected    │
        │      nonces, real signed reputation attestations)  │
        └──────────────────────────────────────────────────┘

How a payment actually happens (sequence diagram)

The core loop — a human reader scrolling into an article, declining once, then paying after a counteroffer:

sequenceDiagram
    participant R as Reader (browser)
    participant E as Embed script (agent.js)
    participant A as Express API
    participant P as Pricing agent
    participant L as Ledger

    R->>E: scrolls past 40%
    E->>A: GET /api/price/:articleId
    A->>P: priceForReader(article, reader, "human")
    P-->>A: price + reasoning
    A-->>E: { price, sessionId }
    E-->>R: show payment widget

    R->>E: clicks "Not now"
    E->>A: POST /api/pay/:articleId/decline
    A-->>E: counteroffer scheduled in 8s

    Note over A: 8 seconds later, server-side
    A->>A: scheduleCounteroffer() computes<br/>engagement-based discount

    E->>A: poll GET /session/:id
    A-->>E: status "countered", new price
    E-->>R: show discounted offer

    R->>E: clicks "Pay"
    E->>A: POST /api/pay/:articleId {action:"confirm"}
    A->>L: signAuthorization + settleAuthorization
    L-->>A: real EIP-712 signature verified, balances moved
    A-->>E: { unlocked: true }
    E-->>R: article unlocks

    A--)A: emit SSE "payment:human"
    Note over A: creator dashboard updates live
Loading

Flows — how each feature works

Dual-mode 402 — one endpoint, three audiences

                        POST /api/pay/:articleId
                                  │
                                  ▼
                    ┌─────────────────────────┐
                    │  detectMode(User-Agent)  │
                    └────┬──────────┬──────────┘
             ┌───────────┘          └───────────┐
             ▼                                   ▼
    ┌─────────────────┐                 ┌──────────────────┐
    │  known AI/x402   │                 │  everything else │
    │  agent UA        │                 │  → human or bot  │
    └────────┬─────────┘                 └────────┬─────────┘
             ▼                                     ▼
   ┌───────────────────┐              ┌──────────────────────────┐
   │ has X-PAYMENT hdr? │              │ looks like a browser?     │
   └────┬──────────┬────┘              └──────┬─────────────┬─────┘
        no         yes                       yes            no
        │           │                         │               │
        ▼           ▼                         ▼               ▼
  402 JSON      verify sig,          402 HTML widget      402 JSON +
  { price,      settle ledger,       (or JSON if the      licensing
    payTo }     unlock (200)         client asked for      contact,
                                      JSON) → reader        crawler
                                      pays or declines      blocked

Revenue splits — one payment, N wallets, one transaction

   reader pays $0.05  ──▶  PAYMENT ROUTER
                              │
              ┌───────────────┼────────────────┐
              ▼                ▼                ▼
        creator (70%)   editor (20%)     PROTOCOL402 fee (2%)
        $0.034          $0.0098          $0.001
              all three land atomically inside one
              SQLite transaction — either every wallet
              is credited or none are (verified in this repo
              by literally crashing mid-charge and confirming
              no partial debit occurred)

Reputation — payments become portable, verifiable loyalty

  payment #5   ──▶  level 1 "PROTOCOL402 Reader"
  payment #25  ──▶  level 2 "Regular Reader"    +5%  off, every site
  payment #100 ──▶  level 3 "Trusted Reader"    +15% off, every site
  payment #500 ──▶  level 4 "Patron"            +25% off, every site

  each level-up issues a real EIP-191 signature from PROTOCOL402's
  attester key over "PROTOCOL402_READER_LEVEL:<wallet>:<level>" —
  independently verifiable by recovering the signer from the message,
  the same trust model ERC-8004 on-chain attestations use.

Multichain bridge — prove you own it, read the real balance, credit it

  reader connects external wallet (e.g. MetaMask on Base Sepolia)
        │
        ▼
  sign message "PROTOCOL402_BRIDGE_CLAIM:<reader>:<chain>:<address>"
        │
        ▼
  server recovers signer ── does it match the claimed address? ──▶ no → reject
        │ yes
        ▼
  real JSON-RPC call to a public testnet endpoint:
  USDC.balanceOf(address)  (no API key needed)
        │
        ▼
  balance > 0? ──▶ no → reject ("no USDC found on <chain>")
        │ yes
        ▼
  credit min(requested, real balance) to the PROTOCOL402 ledger

Discovery API — the supply-side catalog

  research agent                 GET /api/discover?topic=AI+regulation&maxPrice=0.05
       │                                        │
       ▼                                        ▼
  needs sources            ┌────────────────────────────────────┐
  on a topic          ◀──  │ search articles DB, price each one  │
                            │ live (base × surge × loyalty),      │
                            │ return { price, aiPrice, x402Url }  │
                            └────────────────────────────────────┘
       │
       ▼
  x402Fetch(article.x402Endpoint)  →  402  →  sign & pay  →  200, content unlocked

Feature list

# Feature Root failure it fixes Server Client
1–2 AI-dynamic pricing + counteroffer Payment floor / friction agent/price.ts, agent/counteroffer.ts embed widget
3 Dual-mode 402 (AI crawler paywall) AI free-riding server/middleware/dual-mode-402.ts, server/routes/pay.ts
4 Reader wallet + auto-pay Friction agent/auto-pay.ts, agent/wallet.ts /me
5 Revenue splits Collaboration invisibility server/payment-router.ts, server/routes/articles.ts /library
6 Smart subscription bridge Payment floor + friction agent/subscription.ts, server/routes/subscriptions.ts /me, /library
7 Multichain bridge Friction (funding) agent/multichain-bridge.ts /me (BridgeWidget.tsx)
8 ERC-8004-style reader reputation Friction (loyalty) agent/reputation.ts /me
9 x402 discovery directory AI free-riding (discovery) server/routes/discover.ts /discover

What's real vs. what needs your keys

Every function in this repo does what it claims — nothing returns a fake success. The table below is about which layer the real behavior happens at.

Piece Status
Wallet keypairs (creator, reader, collaborator) Real secp256k1 keypairs (ethers.js), encrypted at rest (AES-256-GCM)
Payment authorization + settlement Real EIP-712/EIP-3009 (transferWithAuthorization) signing & verification, real double-entry ledger, replay-protected nonces
Dynamic pricing Real deterministic heuristic; upgrades to a real Claude API call if ANTHROPIC_API_KEY is set
Dual-mode 402 (human/AI-agent/bot) Real User-Agent detection + real x402 X-PAYMENT header protocol
Reader reputation (ERC-8004-style) Real EIP-191 signed attestations, independently verifiable, local registry
Multichain bridge Real wallet-ownership signature verification + real RPC balance reads against public testnets (Ethereum Sepolia / Base Sepolia / Polygon Amoy)
Discovery API Real search over your own articles DB, zero external dependency
Circle Gateway / Arc settlement Needs CIRCLE_API_KEY + ARC_RPC_URL. Until set, all settlement happens on PROTOCOL402's own real internal ledger instead of broadcasting to Circle/Arc.
App Kit Bridge (actual cross-chain transfer) Needs CIRCLE_API_KEY. Until set, the bridge verifies real external balances and credits the PROTOCOL402 ledger 1:1 rather than performing an actual cross-chain token movement.
1Claw Stood in by agent/secrets.ts (real AES-256-GCM vault) — swap in a real 1Claw client without touching callers.

Project layout

protocol402/
├── render.yaml               Render Blueprint (backend, free tier)
├── PROTOCOL402_V2_FINAL_PRD.md
├── server/                   Express API + SQLite + agent engine + embed script
│   ├── src/
│   │   ├── agent/            pricing, ledger, wallets, reputation, bridge, subscriptions
│   │   ├── server/           Express app: routes, middleware, payment router
│   │   ├── embed/            the agent.js source + esbuild bundler
│   │   └── shared/           types, DB schema, repo layer, SSE event bus
│   ├── scripts/               seed.ts, reset-db.ts
│   └── public/                built agent.js + the demo article page
└── web/                      Next.js dashboard
    └── src/app/
        ├── setup/             creator onboarding (3 steps)
        ├── dashboard/         live economy feed + agent decisions
        ├── library/           revenue splits + subscription ceiling
        ├── me/                reader wallet, auto-pay, reputation, bridge
        └── discover/          public x402 content directory

Getting started

Backend

cd server
npm install
cp ../.env.example .env       # optional — add real API keys later, works with none
npm run build:embed           # bundles src/embed/agent.ts → public/agent.js
npm run seed                  # creates a demo creator + article + funded reader wallet
npm run dev                   # http://localhost:4000

Frontend

cd web
npm install
npm run dev                   # http://localhost:3000

No environment variables are required to run the full loop locally — every payment, reputation attestation, and split settles on PROTOCOL402's own real ledger. Add keys later (see Environment variables) to switch specific subsystems to live Circle/Arc/Anthropic services.


Using the app — a full walkthrough

  1. Create a creator. Open http://localhost:3000/setup. Enter a name, email, and topic. Click through the 3 steps — fund the wallet via TestMint, then publish your first article. You'll get a real embed snippet: <script src=".../agent.js" data-article="art_xxx"></script>.

  2. Paste the embed anywhere. The snippet works on any HTML page — there's a live example already running at http://localhost:4000/demo/. Scroll past 40% of the article and the payment widget appears.

  3. Read as a human. Go to http://localhost:3000/me and sign up with just an email — a real wallet keypair is generated for you. Fund it with test USDC, then go back to the demo article: if the price is under your auto-pay threshold ($0.10 default), it unlocks silently. Decline once on purpose to see the counteroffer arrive 8 seconds later at a lower price.

  4. Read as an AI agent. Any request whose User-Agent matches a known x402/AI-agent pattern (or has the X-Protocol402-Mode: x402-agent header) gets a structured JSON 402 instead of HTML. Sign a real EIP-712 transferWithAuthorization for the quoted price and retry with an X-PAYMENT header — the content unlocks and the payment shows up as AI revenue on the creator dashboard.

  5. Watch the economy live. http://localhost:3000/dashboard streams every payment, split, decline, counteroffer, and reputation upgrade over Server-Sent Events in real time, alongside the agent's plain-English reasoning for every price it set.

  6. Split revenue with collaborators. http://localhost:3000/library — add an editor/photographer by email and wallet address, set their percentage. Every future payment on that article fans out to all of them atomically.

  7. Discover content as an agent. http://localhost:3000/discover (or GET /api/discover?topic=...) lists every PROTOCOL402-protected article with its live price and x402 endpoint — copy the endpoint straight into any x402-capable agent.


API reference

Method Path Purpose
POST /api/creators Create/get a creator, provisions a real wallet
POST /api/creators/:id/fund TestMint-style funding
POST /api/creators/:id/sub-ceiling Set max subscription price
POST /api/articles Publish an article
POST /api/articles/:id/splits Add a revenue-split collaborator
GET /api/price/:articleId Quote the current price for a session
POST /api/pay/:articleId Dual-mode 402 gate — human/AI-agent/bot
POST /api/pay/:articleId/decline Reader declines, schedules a counteroffer
POST /api/reader/signup Email-only wallet signup
POST /api/reader/:id/fund TestMint-style funding
POST /api/reader/:id/bridge Multichain bridge — verify + credit
GET /api/reader/:id/reputation ERC-8004-style reputation lookup
GET /api/discover Public x402 content catalog
GET /api/dashboard/:creatorId/stream SSE live economy feed

Environment variables

See .env.example for the full annotated list — PROTOCOL402_JWT_SECRET (encryption key), CIRCLE_API_KEY / CIRCLE_ENTITY_SECRET (live Circle wallets), ANTHROPIC_API_KEY (live Claude pricing), ARC_RPC_URL (live Arc settlement), and per-chain RPC overrides for the multichain bridge. None are required for local development.


Deployment

  • Frontend (Vercel): cd web && vercel --prod. Set NEXT_PUBLIC_API_BASE to your deployed backend URL as a production environment variable.
  • Backend (Render, free tier): push to GitHub, then in the Render dashboard choose New + → Blueprint and point it at this repo — render.yaml at the repo root configures the service automatically. ⚠️ Render's free web service plan has an ephemeral filesystem: the SQLite ledger resets on every redeploy and may reset on cold starts. Fine for a demo; for real persistence, attach a paid persistent disk or migrate server/src/shared/db.ts to a hosted Postgres instance.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages