AGIx402 logo AGIx402 — Serverless x402 Payments
  █████  ████  ██   ██  AGIx402  ████  █████
  ░ ░░░  ░ ░░  ░░   ░░   SERVERLESS x402 PAYMENTS   ░░░  ░ ░░░
  ─────────────────────────────────────────────────────────────

AGIx402 is a serverless payment platform using the x402 protocol. Offer pay-per-use APIs with instant crypto settlements. No registration, no subscriptions. Clients pay on-chain, your backend verifies and issues a one-time x402 token,
Contract : BUPtrH7CvzASNiVpJpR7EbYhzN9zWCxsMyJvhQLspump
.

▌› // home
ABOUT

What is AGIx402?

Serverless payments for any API

AGIx402 is a lightweight gateway implementing the x402 protocol. It lets you charge per request or per metered unit (tokens, seconds, rows) with instant crypto settlements. Users don’t sign up—wallet pays, backend verifies, response unlocks via a short-lived x402 token.

Zero accounts, zero subscriptions. Frictionless start.
Solana & EVM ready (extendable to more chains).
Drop-in front of AI, data, bots, or internal services.
Works with metering (credits/units) and 402 re-challenge.
~0.2s
Gateway Overhead
2+
Chains at Launch
JWT
One-Time x402 Token
FLOW

How it Works

Standard x402 challenge flow — user pays on-chain, backend verifies, response unlocks with a one-time x402 token.

1 Pay Wallet → Receiver 2 Verify /v1/verify → x402 token 3 Unlock Use Paid Endpoint
01

Pay

Client opens wallet and sends payment (SOL/USDC or ETH/USDC) to your receiver address returned by /v1/prices.

GET  /v1/prices?product=ai.small
→ { unit_price: 0.001, receiver: "...", chain:"solana" }
02

Verify

Frontend posts the transaction hash to /v1/verify. Backend checks chain state and issues a short-lived x402 token.

POST /v1/verify { chain, txid, product }
← { paid:true, token:"<jwt>", credits:2000 }
03

Unlock

Client calls the paid endpoint with Authorization: Bearer <token>. Metering deducts units; 402 re-challenge if exhausted.

POST /v1/ai/complete
Authorization: Bearer <token>
← { output:"...", remaining:1900 }
QUICKSTART

From zero to paid API in ~3 minutes

Spin up the AGIx402 gateway, verify on-chain payments, and unlock any endpoint with a short-lived x402 token.

01

Install

Clone or drop the gateway into your server.

# Node 18+
git clone https://github.com/your-org/agix402.git
cd agix402
cp .env.example .env
npm i
        
02

Configure .env

Set allowed origins, RPCs, and receiver addresses.

# Server
PORT=8080
CORS_ORIGINS=https://your-frontend.com

# JWT
JWT_SECRET=change_me
TOKEN_TTL_SECONDS=300
CURRENCY=SOL

# Solana
SOLANA_RPC=https://api.mainnet-beta.solana.com
SOL_RECEIVER=YOUR_SOL_RECEIVER_ADDRESS

# (Optional) EVM
EVM_RPC=https://mainnet.infura.io/v3/YOUR_KEY
EVM_RECEIVER=0xYourEvmReceiver

# Pricing / Credits
PRICE_AI_SMALL=0.001
CREDITS_AI_SMALL=2000
        
03

Run & test

Start the server and dry-run the x402 flow with curl.

npm start
# 1) Get price/receiver
curl -sS 'http://localhost:8080/v1/prices?product=ai.small'

# 2) After paying on-chain, verify your txid (replace ...):
curl -sS -X POST 'http://localhost:8080/v1/verify' \
  -H 'content-type: application/json' \
  -d '{"chain":"solana","txid":"","product":"ai.small"}'
# ← { paid:true, token:"", credits:2000 }
        
04

Use the paid endpoint

Send the x402 token in Authorization to unlock your API.

# Example: AI completion demo (charges 100 units)
curl -sS -X POST 'http://localhost:8080/v1/ai/complete' \
  -H 'content-type: application/json' \
  -H 'authorization: Bearer ' \
  -d '{"prompt":"Hello AGIx402"}'
# ← { output:"Echo: Hello AGIx402", remaining:1900 }
        

Drop-in “Pay → Verify → Unlock” widget (frontend)

Paste this snippet into your page; it fetches price, asks the user to pay, then verifies and calls a paid endpoint.

<script>
const API = 'https://your-agix402-backend.com/v1';
let X402_TOKEN = null;

async function price(product='ai.small'){
  const r = await fetch(`${API}/prices?product=${product}`); return r.json();
}
async function askUserToPay(p){
  // Replace with real wallet adapter; demo uses a prompt:
  return prompt(`Paste transaction signature after paying ${p.unit_price} ${p.currency} to ${p.receiver}`);
}
async function payVerify(){
  const p = await price('ai.small');
  const txid = await askUserToPay(p);
  if(!txid) return alert('Payment not provided');
  const vr = await fetch(`${API}/verify`, {method:'POST',headers:{'content-type':'application/json'},
              body: JSON.stringify({ chain:'solana', txid, product:'ai.small' })});
  const data = await vr.json();
  if(!data.paid) return alert('Verification failed');
  X402_TOKEN = data.token;
  document.querySelector('#x402-status').textContent = 'PAID — features unlocked';
}
async function callPaid(){
  const r = await fetch(`${API}/ai/complete`, {method:'POST',
              headers:{'content-type':'application/json','authorization':`Bearer ${X402_TOKEN}`},
              body: JSON.stringify({ prompt:'Hello AGIx402'})});
  const d = await r.json(); alert(JSON.stringify(d,null,2));
}
</script>

<button onclick="payVerify()">Pay & Verify</button>
<button onclick="callPaid()">Use Paid API</button>
<div id="x402-status">LOCKED</div>
Copied
PRICING

Simple pay-per-use tiers

Charge per request or per metered unit. No accounts, no subscriptions—just on-chain payments and short-lived x402 tokens.

Starter

ai.small

0.05 SOL
per request
  • Up to 2,000 credits per token
  • Fair use metering (402 re-challenge)
  • Fast verify & unlock
  • Great for prototyping
Get Started
Core

ai.medium

0.10 SOL
per request
  • Up to 6,000 credits per token
  • Priority verify (lower latency)
  • Usage insights
  • Best for staging / small apps
Get Started
Pro

ai.large

0.25 SOL
per request
  • Up to 20,000 credits per token
  • Priority verify + enhanced metering
  • Extended routing / adapters
  • Scale-ready for production
Get Started

API reference (pricing endpoints)

# Get current price & receiver for a product
GET  /v1/prices?product=ai.small
→ { product:"ai.small", unit_price:0.05, currency:"SOL", receiver:"...", chains:[...] }

# Verify on-chain payment (replace values)
POST /v1/verify
{ "chain":"solana", "txid":"<tx-signature>", "product":"ai.small" }
← { "paid":true, "token":"<jwt>", "credits":2000, "expires_in":300 }
Copied
SECURITY

Secure by design: TTL, anti-replay, and credit metering

AGIx402 issues short-lived x402 tokens after on-chain verification. Tokens are single-use, scoped to a product, and guarded by TTL, origin allowlists, rate-limits, and replay protection.

Short-Lived Tokens (TTL)

JWT expires quickly (e.g., 300s). Limits abuse window and enforces fresh on-chain payment.

  • exp claim enforced
  • Clock-skew tolerant
  • No long-term sessions

Anti-Replay (txid)

Each on-chain txid is persisted and can be verified only once.

  • Unique index on txid
  • Idempotent verification
  • Reject reused tx

Credits Metering

Every paid call decrements credits; if depleted → 402 re-challenge.

  • Per-product quotas
  • Atomic decrement
  • Usage introspection

Edge Defenses

Origin allowlist + small rate-limit to dampen bursts and scrapers.

  • CORS allowlist
  • 429 rate-limit
  • Audit logs
Verify /v1/verify → JWT Use Token Authorization: Bearer Meter Credits Atomic decrement Re-challenge 402 if credits ≤ 0
Short-Lived JWT (TTL)

Issue JWTs with a tight exp (e.g., 300s) and embed minimal claims: tokenId, product, exp. Validate clock-skew and reject expired/invalid signatures.

{
  "tokenId": "txid:timestamp",
  "product": "ai.small",
  "exp": 1730450000
}
Anti-Replay (unique txid)

Persist every verified txid with a unique index. If the same txid appears again, return 402 with X-402-Why: replay_detected.

-- SQL (example)
CREATE TABLE payments (
  txid TEXT PRIMARY KEY,
  chain TEXT NOT NULL,
  product TEXT NOT NULL,
  amount NUMERIC NOT NULL,
  verified_at TIMESTAMP NOT NULL DEFAULT NOW()
);
Credits Metering + 402 re-challenge

Attach a credit bucket to the tokenId. On each paid call, atomically decrement. If insufficient → respond with 402 and re-challenge headers.

HTTP/1.1 402 Payment Required
X-402-Why: insufficient_credits
X-402-Price: 0.05 SOL
X-402-Product: ai.small
Origin Allowlist & Rate-Limit

Only allow requests from trusted origins and throttle bursts. Keep a small audit trail for sensitive calls.

CORS_ORIGINS=https://your-frontend.com,https://admin.your-frontend.com
# Example rate limit: 50 req / 10s / IP (tune per product)

Hardening checklist

  • JWT TTL ≤ 5 minutes (rotate secret on compromise)
  • Persist txid and enforce unique usage
  • Atomic credit decrement (DB row lock or Redis LUA)
  • Return clear 402 headers for client UX
  • Strict CORS allowlist + small rate-limit
  • Log verify/paid calls with request hash (no PII)

Reference: verify → token → paid call

# 1) Verify (after on-chain payment)
POST /v1/verify
{ "chain":"solana", "txid":"<signature>", "product":"ai.small" }
← { "paid":true, "token":"<jwt>", "credits":2000, "expires_in":300 }

# 2) Use token on a paid endpoint
POST /v1/ai/complete
Authorization: Bearer <jwt>
← { "output":"...", "remaining":1900 }
Copied
SDKs

Integrations & SDKs

Use lightweight adapters to wire AGIx402 into your stack. Verify payments on-chain, mint short-lived x402 tokens, and meter credits.

Solana Adapter (Node)

Verifies a SOL/USDC payment and returns the payer & amount.

// npm i @solana/web3.js @solana/spl-token
import { Connection, PublicKey } from "@solana/web3.js";

export async function verifySolanaTx({ rpc, txid, receiver, minLamports }) {
  const conn = new Connection(rpc, "confirmed");
  const tx = await conn.getTransaction(txid, { maxSupportedTransactionVersion: 0 });
  if (!tx) return { ok:false, reason:"tx_not_found" };

  // Sum all post-balance deltas to the receiver
  const acctKeys = tx.transaction.message.getAccountKeys().staticAccountKeys;
  const idx = acctKeys.findIndex(k => k.toBase58() === receiver);
  if (idx === -1) return { ok:false, reason:"receiver_not_in_tx" };

  const pre = Number(tx.meta.preBalances[idx] || 0);
  const post = Number(tx.meta.postBalances[idx] || 0);
  const received = post - pre;

  if (received < minLamports) return { ok:false, reason:"insufficient_amount", received };
  return { ok:true, receivedLamports: received, payer: acctKeys[0].toBase58() };
}
Copied