Skill: jimmyclanker/x402-quickstart (version 1.0.0)

--- name: x402-quickstart version: 1.0.0 description: Deploy x402 pay-per-call API endpoints in minutes. Turn any OpenClaw skill or service into a monetized endpoint accepting USDC on Base. Includes payment verification, pricing, and Cloudflare Tunnel integration. Use when deploying x402 endpoints, setting up agent payments, monetizing APIs, or building pay-per-call services. --- # x402 Quickstart Deploy x402-compatible pay-per-call endpoints that accept USDC payments from AI agents on Base. ## What is x402? HTTP 402 ("Payment Required") is the standard for machine-to-machine payments. An agent sends a request, gets a `402` response with pricing info, pays in USDC on Base, and receives the data. No API keys, no accounts, no subscriptions. **Ecosystem (Q1 2026)**: Stripe, Cloudflare, Google (AP2), Coinbase all ship native x402 support. ## Quick Deploy ### 1. Generate endpoint scaffold ```bash bash scripts/scaffold.sh my-service "My cool API" 0.01 ``` Creates a ready-to-run Express server with x402 payment middleware at `./my-service/`. ### 2. Configure wallet Set your Base wallet address to receive payments: ```bash # In the generated .env file WALLET_ADDRESS=0xYourBaseWalletAddress USDC_CONTRACT=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 CHAIN_ID=8453 PORT=3402 ``` ### 3. Run locally ```bash cd my-service && npm install && node server.js ``` ### 4. Expose via Cloudflare Tunnel (zero cost) ```bash cloudflared tunnel --url http://localhost:3402 ``` ## How It Works ### Agent Flow ``` Agent → GET /api/data → 402 Payment Required ├── price: "0.01 USDC" ├── payTo: "0x..." └── network: "base" Agent → pays USDC on Base → gets tx hash Agent → GET /api/data (X-Payment-Tx: 0x...) → 200 OK + data ``` ### Server Flow 1. Request arrives without payment → respond `402` with pricing 2. Request arrives with `X-Payment-Tx` header → verify on-chain 3. If payment confirmed → serve data 4. If payment fails → respond `402` again ## Endpoint Ideas High-value endpoints AI agents will pay for: | Endpoint | Price | Description | |----------|-------|-------------| | `/alpha/scan` | $0.50-1.00 | Token/project analysis with scoring | | `/market/signal` | $0.10 | Real-time trading signals | | `/research/report` | $1.00 | Deep research on any topic | | `/data/portfolio` | $0.05 | Multi-chain portfolio snapshot | | `/tools/scrape` | $0.02 | Clean web content extraction | | `/ai/inference` | $0.04 | LLM inference routing | ## Payment Verification The scaffold includes `scripts/verify-payment.js` for on-chain verification: ```javascript // Verifies USDC transfer on Base const verified = await verifyPayment(txHash, expectedAmount, recipientAddress); ``` Uses Base RPC (free tier) — no API key needed for basic verification. ## Integration with OpenClaw ### As a skill endpoint Add to your agent's capabilities: ```json5 // In SKILL.md or agent config { tools: [{ name: "my_x402_service", endpoint: "https://my-service.example.com/api", payment: { currency: "USDC", network: "base" } }] } ``` ### With Cloudflare Tunnel Zero-cost hosting on your existing machine: ```bash # One-time setup cloudflared tunnel create my-x402 cloudflared tunnel route dns my-x402 api.mydomain.com # Run cloudflared tunnel run --url http://localhost:3402 my-x402 ``` ## Spraay Gateway Integration Register your endpoint on [Spraay](https://gateway.spraay.app) to get discovered by agents automatically: ```bash curl -X POST https://gateway.spraay.app/register \ -H "Content-Type: application/json" \ -d '{"url": "https://api.mydomain.com", "category": "data", "price": "0.01"}' ``` ## Pricing Strategy - **Data endpoints**: $0.005-0.05 (commodity, high volume) - **Analysis endpoints**: $0.10-1.00 (value-add, medium volume) - **Research endpoints**: $1.00-5.00 (premium, low volume) - **GPU/compute**: $0.05-0.50 (resource-based pricing) Start low, raise prices when you have traction. Better to have 1000 calls at $0.01 than 0 calls at $1.00.

path: scripts/scaffold.sh
content: #!/bin/bash
# scaffold.sh — Generate an x402 pay-per-call endpoint project
# Usage: bash scaffold.sh <name> <description> <price_usdc>

set -euo pipefail

NAME="${1:?Usage: scaffold.sh <name> <description> <price_usdc>}"
DESC="${2:-My x402 API}"
PRICE="${3:-0.01}"
DIR="./$NAME"

if [ -d "$DIR" ]; then
    echo "❌ Directory $DIR already exists"
    exit 1
fi

echo "🚀 Scaffolding x402 endpoint: $NAME"
mkdir -p "$DIR"

# package.json
cat > "$DIR/package.json" << EOF
{
  "name": "$NAME",
  "version": "1.0.0",
  "description": "$DESC",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.21.0",
    "ethers": "^6.13.0"
  }
}
EOF

# .env
cat > "$DIR/.env" << EOF
# x402 Configuration
WALLET_ADDRESS=0xYOUR_BASE_WALLET_ADDRESS
USDC_CONTRACT=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
CHAIN_ID=8453
PORT=3402
PRICE_USDC=$PRICE
BASE_RPC=https://mainnet.base.org
EOF

# server.js
cat > "$DIR/server.js" << 'SERVEREOF'
require("dotenv").config();
const express = require("express");
const { ethers } = require("ethers");

const app = express();
app.use(express.json());

const {
  WALLET_ADDRESS,
  USDC_CONTRACT,
  CHAIN_ID,
  PORT = 3402,
  PRICE_USDC = "0.01",
  BASE_RPC = "https://mainnet.base.org",
} = process.env;

const provider = new ethers.JsonRpcProvider(BASE_RPC);

// USDC has 6 decimals
const priceWei = ethers.parseUnits(PRICE_USDC, 6);

// ERC-20 Transfer event
const TRANSFER_TOPIC = ethers.id("Transfer(address,address,uint256)");

async function verifyPayment(txHash) {
  try {
    const receipt = await provider.getTransactionReceipt(txHash);
    if (!receipt || receipt.status !== 1) return false;

    for (const log of receipt.logs) {
      if (
        log.address.toLowerCase() === USDC_CONTRACT.toLowerCase() &&
        log.topics[0] === TRANSFER_TOPIC
      ) {
        const to = ethers.getAddress("0x" + log.topics[2].slice(26));
        const amount = BigInt(log.data);
        if (
          to.toLowerCase() === WALLET_ADDRESS.toLowerCase() &&
          amount >= priceWei
        ) {
          return true;
        }
      }
    }
    return false;
  } catch {
    return false;
  }
}

// Track used tx hashes to prevent replay
const usedTxHashes = new Set();

// x402 middleware
function x402Middleware(req, res, next) {
  const txHash = req.headers["x-payment-tx"] || req.query.tx;

  if (!txHash) {
    return res.status(402).json({
      error: "Payment Required",
      price: `${PRICE_USDC} USDC`,
      currency: "USDC",
      network: "base",
      chainId: parseInt(CHAIN_ID),
      payTo: WALLET_ADDRESS,
      [REDACTED_SECRET],
      instructions:
        "Send USDC to payTo address on Base, then retry with X-Payment-Tx header",
    });
  }

  if (usedTxHashes.has(txHash.toLowerCase())) {
    return res.status(402).json({ error: "Transaction already used" });
  }

  verifyPayment(txHash).then((valid) => {
    if (valid) {
      usedTxHashes.add(txHash.toLowerCase());
      next();
    } else {
      res.status(402).json({
        error: "Payment not verified",
        hint: "Ensure USDC was sent to the correct address on Base",
      });
    }
  });
}

// Health endpoint (free)
app.get("/health", (req, res) => {
  res.json({ status: "ok", service: process.env.npm_package_name || "x402-service" });
});

// Pricing endpoint (free)
app.get("/pricing", (req, res) => {
  res.json({
    price: `${PRICE_USDC} USDC`,
    network: "base",
    chainId: parseInt(CHAIN_ID),
    payTo: WALLET_ADDRESS,
    [REDACTED_SECRET],
  });
});

// === YOUR ENDPOINTS GO HERE ===
// Add x402Middleware to any route that requires payment

app.get("/api/data", x402Middleware, (req, res) => {
  // Replace this with your actual service logic
  res.json({
    message: "Payment verified! Here's your data.",
    timestamp: new Date().toISOString(),
    // Add your data here
  });
});

// ==============================

app.listen(PORT, () => {
  console.log(`x402 endpoint live on http://localhost:${PORT}`);
  console.log(`Price: ${PRICE_USDC} USDC on Base`);
  console.log(`Wallet: ${WALLET_ADDRESS}`);
});
SERVEREOF

# dotenv dependency
cat > "$DIR/.gitignore" << EOF
node_modules/
.env
EOF

# Install dotenv too
cd "$DIR"
cat package.json | python3 -c "
import sys, json
p = json.load(sys.stdin)
p['dependencies']['dotenv'] = '^16.4.0'
json.dump(p, sys.stdout, indent=2)
" > package.json.tmp && mv package.json.tmp package.json

echo ""
echo "✅ x402 endpoint scaffolded at $DIR/"
echo ""
echo "Next steps:"
echo "  1. Edit $DIR/.env — set your WALLET_ADDRESS"
echo "  2. cd $DIR && npm install"
echo "  3. node server.js"
echo "  4. Test: curl http://localhost:3402/pricing"
echo "  5. Deploy: cloudflared tunnel --url http://localhost:3402"


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)