惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
K
Kaspersky official blog
L
LangChain Blog
有赞技术团队
有赞技术团队
V
Visual Studio Blog
T
The Blog of Author Tim Ferriss
Microsoft Azure Blog
Microsoft Azure Blog
Stack Overflow Blog
Stack Overflow Blog
美团技术团队
Vercel News
Vercel News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
G
Google Developers Blog
宝玉的分享
宝玉的分享
月光博客
月光博客
爱范儿
爱范儿
The Register - Security
The Register - Security
S
SegmentFault 最新的问题
M
MIT News - Artificial intelligence
F
Full Disclosure
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
WordPress大学
WordPress大学
D
Docker
Y
Y Combinator Blog
N
News and Events Feed by Topic
P
Proofpoint News Feed
Apple Machine Learning Research
Apple Machine Learning Research
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recorded Future
Recorded Future
IT之家
IT之家
C
CXSECURITY Database RSS Feed - CXSecurity.com
Security Latest
Security Latest
Spread Privacy
Spread Privacy
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Fortinet All Blogs
AWS News Blog
AWS News Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
D
DataBreaches.Net
Recent Announcements
Recent Announcements
博客园 - Franky
Google DeepMind News
Google DeepMind News
小众软件
小众软件
B
Blog RSS Feed
I
InfoQ
Attack and Defense Labs
Attack and Defense Labs
云风的 BLOG
云风的 BLOG

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
A Self-Monetizing API in 20 Lines of Code
MPP TestKit · 2026-05-09 · via DEV Community

This is a hands-on tutorial. By the end you'll have a running pay-per-request API server, a client that pays automatically, and a test suite that covers the full payment flow - all on devnet, completely free.

The Problem With How We Monetize APIs Today

If you've ever tried to sell access to an API you built, you know the drill:

  1. Sign up for Stripe
  2. Build a subscription checkout flow
  3. Issue API keys on payment confirmation
  4. Store keys in a database
  5. Validate keys on every request
  6. Build a usage dashboard
  7. Handle expired cards, failed payments, refunds
  8. Write the billing docs

By the time you've done all that, you've built a billing product. That wasn't the thing you wanted to build.

The worst part: none of this scales to small amounts. Charging $0.001 per API call with Stripe isn't viable - the processing fee alone exceeds the charge. So you're forced into subscriptions, bundles, and credit packs. Your pricing model becomes a product decision instead of just... pricing.

There's a cleaner way to do this. It's been in the HTTP spec since 1999. It just never had the infrastructure to work.


HTTP 402: The Status Code That Was Waiting for Blockchains

402 Payment Required

Enter fullscreen mode Exit fullscreen mode

This status code has been reserved in HTTP since the original 1.1 spec. The idea: server tells the client "pay first, then retry." The client pays, retries with proof, gets the resource.

The problem was always how. How does the server specify the amount? In what form? How does the client pay programmatically? How does the server verify payment without a central authority?

Blockchains answer all of those questions. Solana specifically:

  • Specifies amount in SOL (or any token)
  • Accepts payment via a signed transaction
  • Provides on-chain verification with no intermediary
  • Confirms transactions in ~2 seconds
  • Charges fractions of a cent in fees

MPP Testkit is the SDK that wires this up. Let's build something with it.


What We're Building

A Node.js API server with:

  • /api/ping - free endpoint, no payment
  • /api/weather - costs 0.001 SOL per call
  • /api/forecast - costs 0.005 SOL per call (premium tier)

And a client script that:

  • Hits the paid endpoints automatically
  • Handles the wallet, airdrop, and payment without any manual steps
  • Logs every step of the flow

Total code: about 20 lines for the server, 10 for the client.


Setup

mkdir my-paid-api && cd my-paid-api
npm init -y
npm install express mpp-test-sdk

Enter fullscreen mode Exit fullscreen mode

Create two files: server.js and client.js.


The Server

// server.js
import express from "express";
import { createTestServer } from "mpp-test-sdk";

const app = express();
const mpp = createTestServer();

// Free - no payment needed
app.get("/api/ping", (req, res) => {
  res.json({ status: "ok", ts: Date.now() });
});

// 0.001 SOL per call
app.get("/api/weather",
  mpp.charge({ amount: "0.001" }),
  (req, res) => {
    res.json({
      city: "San Francisco",
      temp: 62,
      condition: "Partly cloudy",
      paid: true,
    });
  }
);

// 0.005 SOL per call - premium tier
app.get("/api/forecast",
  mpp.charge({ amount: "0.005" }),
  (req, res) => {
    res.json({
      city: "San Francisco",
      forecast: [
        { day: "Mon", high: 65, low: 54 },
        { day: "Tue", high: 68, low: 57 },
        { day: "Wed", high: 61, low: 52 },
      ],
      model: "v2-premium",
      paid: true,
    });
  }
);

app.listen(3001, () => {
  console.log("Server running on :3001");
  console.log("Payment recipient:", mpp.recipientAddress);
});

Enter fullscreen mode Exit fullscreen mode

Start it:

node server.js
# Server running on :3001
# Payment recipient: 7xKmPq2rNbMd...

Enter fullscreen mode Exit fullscreen mode

That's the server. mpp.charge() is Express middleware. It returns a 402 if no valid payment receipt is present, verifies on-chain if one is, and calls next() if everything checks out.


The Client

// client.js
import { createTestClient } from "mpp-test-sdk";

const client = await createTestClient({
  network: "devnet",
  onStep: ({ type, message }) => console.log(`  [${type}] ${message}`),
});

console.log("\n- Hitting /api/ping (free)");
const ping = await client.fetch("http://localhost:3001/api/ping");
console.log(await ping.json());

console.log("\n- Hitting /api/weather (0.001 SOL)");
const weather = await client.fetch("http://localhost:3001/api/weather");
console.log(await weather.json());

console.log("\n- Hitting /api/forecast (0.005 SOL)");
const forecast = await client.fetch("http://localhost:3001/api/forecast");
console.log(await forecast.json());

Enter fullscreen mode Exit fullscreen mode

Run it:

node client.js

- Hitting /api/ping (free)
{ status: 'ok', ts: 1715123456789 }

- Hitting /api/weather (0.001 SOL)
  [wallet-created] Keypair generated: 3xMn9...Wr4k
  [funded] Airdropped 2 SOL on devnet
  [request] GET http://localhost:3001/api/weather
  [payment] 402 received · paying 0.001 SOL
  [payment] tx confirmed: 5xKm7...Pq2r
  [retry] Retrying with Payment-Receipt header
  [success] 200 OK
{ city: 'San Francisco', temp: 62, condition: 'Partly cloudy', paid: true }

- Hitting /api/forecast (0.005 SOL)
  [request] GET http://localhost:3001/api/forecast
  [payment] 402 received · paying 0.005 SOL
  [payment] tx confirmed: 8xNp3...Qr1s
  [retry] Retrying with Payment-Receipt header
  [success] 200 OK
{ city: 'San Francisco', forecast: [...], model: 'v2-premium', paid: true }

Enter fullscreen mode Exit fullscreen mode

Notice: the wallet and airdrop only happen once. The second paid call reuses the same wallet - no second airdrop. The client is stateful, the calls are not.


What Just Happened Under the Hood

When the client hit /api/weather:

  1. Client sent GET /api/weather - no special headers
  2. Server returned 402 Payment Required with header:
   Payment-Request: solana; amount="0.001"; recipient="7xKmPq2r..."

Enter fullscreen mode Exit fullscreen mode

  1. SDK parsed the header, built a Solana transaction for 0.001 SOL to 7xKmPq2r...
  2. SDK signed and submitted the transaction to devnet
  3. SDK waited for confirmation (~2 seconds)
  4. Client retried with header:
   Payment-Receipt: solana; signature="5xKm7...Pq2r"

Enter fullscreen mode Exit fullscreen mode

  1. Server verified on-chain: transaction exists, recipient matches, amount ≥ 0.001 SOL
  2. Server called next(), handler returned 200

Your handler code saw none of this. It just received a request and returned JSON.


Writing Tests for Your Paid Endpoints

This is where MPP Testkit really shines. Integration testing paid APIs usually means mocking the payment layer, which means your tests don't actually test the payment logic.

With MPP Testkit on devnet, you test the real flow for free:

// server.test.js
import { createTestClient } from "mpp-test-sdk";
import { describe, test, expect, beforeAll, afterAll } from "vitest";

let client;
let server;

beforeAll(async () => {
  // Start the server
  server = await import("./server.js");

  // Create a test client - wallet + airdrop happen here once
  client = await createTestClient({ network: "devnet" });
});

afterAll(() => server.close());

describe("Free endpoints", () => {
  test("GET /api/ping returns 200 without payment", async () => {
    const res = await client.fetch("http://localhost:3001/api/ping");
    expect(res.status).toBe(200);
    const body = await res.json();
    expect(body).toHaveProperty("status", "ok");
  });
});

describe("Paid endpoints", () => {
  test("GET /api/weather: pays 0.001 SOL, returns weather data", async () => {
    const res = await client.fetch("http://localhost:3001/api/weather");
    expect(res.status).toBe(200);
    const body = await res.json();
    expect(body).toHaveProperty("temp");
    expect(body.paid).toBe(true);
  });

  test("GET /api/forecast: pays 0.005 SOL, returns 3-day forecast", async () => {
    const res = await client.fetch("http://localhost:3001/api/forecast");
    expect(res.status).toBe(200);
    const body = await res.json();
    expect(body.forecast).toHaveLength(3);
  });

  test("Direct request without payment returns 402", async () => {
    const res = await fetch("http://localhost:3001/api/weather");
    expect(res.status).toBe(402);
    const header = res.headers.get("Payment-Request");
    expect(header).toMatch(/solana/);
    expect(header).toMatch(/amount="0.001"/);
  });

  test("Request with invalid receipt returns 403", async () => {
    const res = await fetch("http://localhost:3001/api/weather", {
      headers: { "Payment-Receipt": "solana; signature=fakesig123" },
    });
    expect(res.status).toBe(403);
  });
});

Enter fullscreen mode Exit fullscreen mode

Run with:

npx vitest

Enter fullscreen mode Exit fullscreen mode

These are real integration tests. No mocks. No stubs. The payment flow runs against devnet on every test run. If your receipt verification logic breaks, the test catches it - because it actually verifies.


Handling Errors Gracefully

Real code needs error handling. The SDK throws typed errors:

import {
  mppFetch,
  MppFaucetError,
  MppPaymentError,
  MppTimeoutError,
} from "mpp-test-sdk";

async function fetchWithFallback(url) {
  try {
    return await mppFetch(url);
  } catch (err) {
    if (err instanceof MppFaucetError) {
      // Devnet faucet rate-limited - common in CI with many parallel runs
      console.warn("Faucet unavailable, retrying in 60s...");
      await sleep(60_000);
      return mppFetch(url); // retry once
    }

    if (err instanceof MppPaymentError) {
      // Transaction rejected - log and rethrow
      console.error(`Payment rejected: ${err.url}${err.status}`);
      throw err;
    }

    if (err instanceof MppTimeoutError) {
      // Flow took too long - Solana can be slow under load
      console.error(`Timed out after ${err.timeoutMs}ms`);
      throw err;
    }

    throw err;
  }
}

Enter fullscreen mode Exit fullscreen mode


Taking It to Production (Mainnet)

When you're ready to charge real SOL:

Server side - pin a stable recipient wallet:

const mpp = createTestServer({
  secretKey: process.env.SERVER_SECRET_KEY, // base64 or JSON array
  network: "mainnet",
});

Enter fullscreen mode Exit fullscreen mode

Client side - provide a funded wallet:

const client = await createTestClient({
  network: "mainnet",
  secretKey: process.env.CLIENT_SECRET_KEY, // pre-funded with real SOL
});

Enter fullscreen mode Exit fullscreen mode

The protocol is identical. The only difference is network: "mainnet" and no auto-airdrop. Your application code doesn't change.


The Creator Economy Angle

I want to zoom out for a second, because this is bigger than just APIs.

If you're a developer who creates things - libraries, datasets, AI models, tools - the standard monetization paths are:

  • Open source - free, you get nothing
  • SaaS - build a subscription billing system (Stripe, auth, database, dashboard)
  • One-time license - Gumroad, Paddle, etc. - purchase gate, license key management
  • Usage-based - Stripe metered billing - still requires subscription, monthly invoicing

All of these require you to build infrastructure around your actual product.

HTTP 402 with Solana adds a fifth option: embed payment in the protocol itself.

Your dataset endpoint charges $0.0001 per query. Your AI model charges $0.01 per inference. Your code analysis tool charges $0.005 per file. No subscription. No free tier decision. No pricing page. The price is in the API response.

Consumers - including AI agents - just pay and use. Your server accumulates SOL. You withdraw to your wallet.

The entire billing system is the blockchain.


Why This Matters for AI Agents Right Now

We're at an inflection point: AI agents are being deployed that autonomously call tools, APIs, and services. The problem is that every one of those tools currently requires a human to sign up, get an API key, and manage billing.

That doesn't scale. An agent that spins up 50 tool-calling sessions needs 50 sets of credentials managed by a human. Or one set of credentials shared across everything - which is a security disaster.

HTTP 402 with Solana gives agents a payment identity without a human in the loop:

  1. Agent generates an ephemeral keypair on first run
  2. Agent funds wallet from its operator's SOL balance
  3. Agent hits any 402-gated endpoint and pays automatically
  4. Operator monitors spending via on-chain transactions

No API keys. No credentials database. No revocation system. The wallet is the identity. The payment is the access token.

The Auton demo shows this working end-to-end - an agent that generates its own wallet, gets funded, navigates a 402 gate, pays, and retrieves premium data. Every step streams live to the browser. Watch it once and the architecture becomes obvious.


Quick Reference

Install

npm install mpp-test-sdk       # TypeScript/JavaScript
pip install mpp-test-sdk       # Python
go get github.com/mpptestkit/mpp-test-sdk-go  # Go

Enter fullscreen mode Exit fullscreen mode

Minimal server

import { createTestServer } from "mpp-test-sdk";
const mpp = createTestServer();
app.get("/paid", mpp.charge({ amount: "0.001" }), handler);

Enter fullscreen mode Exit fullscreen mode

Minimal client

import { mppFetch } from "mpp-test-sdk";
const res = await mppFetch("https://your-api.com/paid");

Enter fullscreen mode Exit fullscreen mode

Networks

Network Auto-funded Cost
devnet Yes (2 SOL) Free
testnet Yes (2 SOL) Free
mainnet No Real SOL

Error types

Error Cause
MppFaucetError Devnet/testnet faucet rate-limited
MppPaymentError On-chain transaction rejected
MppTimeoutError Full flow exceeded timeout
MppNetworkError Mainnet attempted without funded wallet

What's Next

Once you have the basics running:

  • Add multiple price tiers - mpp.charge({ amount: "0.01" }) on premium endpoints, mpp.charge({ amount: "0.001" }) on standard
  • Use the lifecycle events - stream payment status to your frontend in real-time (the playground does this)
  • Integrate with your existing auth - 402 and API keys aren't mutually exclusive; use 402 for metered access, API keys for identity
  • Move to mainnet - same code, swap network: "devnet" to network: "mainnet", provide funded wallets

The interactive playground is the fastest way to see the full flow before you build anything. It runs against a live server - no setup, no install.


Links

  • mpptestkit.com - Playground + full protocol docs
  • agent.mpptestkit.com - Auton: autonomous agent payment demo
  • npm: mpp-test-sdk
  • PyPI: mpp-test-sdk
  • Go: github.com/mpptestkit/sdk-go

The billing system your API never had to build is already in the HTTP spec. It just needed Solana to make it real.