Developers
Sell an API, or let an agent buy one.
API providers add one middleware. Agent builders use the client SDK or the CLI. Everything here matches the code in the repository. All three packages are on npm under @turnspike-qie.
Overview
An unpaid request gets an HTTP 402 challenge. The agent pays through the allowance contract on QIE Mainnet (chain 1990) in QUSDC, then retries with an X-Payment header. The seller verifies the receipt on chain, binds the payment to one resource, stores the response and sends it. The owner's limits are enforced by the contract, not by the agent. This is a Turnspike-specific format and is not x402-compatible.
- API providers
Protect a route with @turnspike-qie/middleware, set a price, receive QUSDC.
- Agent builders
Pay for APIs automatically with @turnspike-qie/client, inside a policy you set.
- Owners
Fund an allowance, set caps and merchants, pause or revoke, in the web console.
Requirements: Node.js 20 or later. Agents need an agent key with a little QIE for gas (one payment used 92,159 gas, 0.000104 QIE) and an owner who has set that agent's limits. Sellers need a merchant address and a persistent disk.
Quick start
Try the live gateway from a terminal. This returns the real 402 challenge and sends no transaction:
curl -i https://turnspike-qie.fly.dev/v1/block-summaryInstallation
npm install @turnspike-qie/middleware express # API providers
npm install @turnspike-qie/client ethers # agent builders
npm install -g @turnspike-qie/cli # the turnspike commandRequires Node.js 22. The middleware depends on express, ethers v6 and better-sqlite3. Set HMAC_SECRET in your environment and never commit it.
Integration
import express from "express";
import { turnspike } from "@turnspike-qie/middleware";
const app = express();
const paid = turnspike({
rpcUrls: ["https://rpc1mainnet.qie.digital", "https://rpc2mainnet.qie.digital"],
chainId: 1990,
contract: "0xa2f2e042861a593cc582c6d2d43a24457dcf5d9c", // deployed TurnpikeAllowance
token: "0x3F43DA82eC9A4f5285F10FaF1F26EcA7319E5DA5", // QUSDC, 6 decimals
merchant: process.env.MERCHANT_ADDRESS!, // where payments go
hmacSecrets: [process.env.HMAC_SECRET!], // at least 32 bytes
dbPath: "/data/turnspike.sqlite", // persistent volume
prices: {
"/forecast/:city": {
priceBase: 2500, // 0.0025 QUSDC
validate: (req) => /^[a-z-]+$/.test(req.path.split("/")[2] ?? "") ? null : "unknown_city", // 400 before any price
},
},
});
app.use("/v1", paid);
app.get("/v1/forecast/:city", (req, res) => res.json({ city: req.params.city, tomorrow: "sunny" }));
// recover payments made while you were down, then clean up challenges that can no longer be paid
setInterval(() => paid.reconcile().then(() => paid.purge()), 15 * 60_000);
app.listen(8080);Routes with no price rule pass through unchanged. A payment is bound to the method, path and sorted query string; add binding: { body: true } or binding: { identity: (req) => apiKeyId } when those define the resource. The handler's 2xx response is stored before it is sent and replayed for the same proof. Handlers run at least once, so keep them idempotent. Deployment, backups and secret rotation: docs/OPERATIONS.md.
Agent builders
@turnspike-qie/client never pays an arbitrary 402. The request origin and the merchant must be on your payee list, the chain, contract and token must match, and the price must be under your ceiling. It then checks the owner's on-chain caps, allowlist and balance and the agent's gas before broadcasting, so a refusal costs nothing. A payment on chain cannot be reversed if the API later fails; the journal lets resume() collect it without paying twice.
import { TurnspikeClient, FileJournal, QIE_MAINNET, parseUnits } from "@turnspike-qie/client";
const client = new TurnspikeClient({
signer, // the AGENT key (keystore, KMS, remote signer). Never the owner key.
owner: "0xOwner…", // whose on-chain allowance pays
network: QIE_MAINNET,
policy: {
payees: [{ origin: "https://api.example.com", merchant: "0xMerchant…" }], // nobody else is ever paid
maxPriceBase: parseUnits("0.005"), // hard ceiling per request
},
approve: (q) => q.gasCostWei < 10n ** 15n, // your rule, before every payment
journal: new FileJournal(".turnspike/journal.json"), // restart-safe
});
const r = await client.fetch("https://api.example.com/v1/forecast/lagos", {}, { idempotencyKey: "lagos-today" });
if (r.ok && r.kind === "paid") console.log(await r.response.json(), r.payment.explorerUrl);
else if (!r.ok && r.paid) await client.resume("lagos-today"); // paid, not delivered yet: resume does not pay it againErrors are typed (untrusted_destination, price_above_max, over_daily_cap, insufficient_gas, redeem_timeout and more) and say whether money moved (paid). Use dryRun: true to inspect a quote. Full reference: packages/client.
CLI
The turnspike command uses the same client, so it has the same safety rules. It asks before spending, shows the network, merchant, price and gas, prints explorer links, and supports --json. The keystore password comes from TURNSPIKE_KEYSTORE_PASSWORD or a hidden prompt, never a flag. Owner operations stay in the web console.
turnspike init --owner 0xOwner --keystore ~/.foundry/keystores/agent \
--payee https://turnspike-qie.fly.dev=0xceeFC1Cf07984D823Db90FaC317069F8BDCDB761 --max-price 0.005
turnspike doctor
turnspike account inspect 0xOwner
turnspike api probe https://turnspike-qie.fly.dev/v1/block-summary # explains the 402, never pays
turnspike api pay https://turnspike-qie.fly.dev/v1/block-summary # shows price and gas, asks, pays
turnspike api verify 0x7e41ccaa46724c9ca943b6f9580b6a71a9090d80affdca0df36d3bbc809621b7
turnspike api pay … --json --yes | jq .payment.explorerUrl # scripting; exit 3 = refused, 4 = paid or possibly paid, not deliveredExamples
- examples/express-apiA seller: two priced routes with validation and reconciliation.
- examples/node-agentA buyer: pays a Turnspike API with the client SDK. This program bought from the hosted gateway on mainnet (evidence M8).
- examples/end-to-endSeller and agent together on a local chain, using the built packages. Runs in CI.
Payment flow
HTTP/1.1 402 Payment Required
{
"error": "payment_required",
"protocol": "turnspike/1",
"requestId": "0x…", // keccak256 of nonce, merchant, resource, price, chain, contract, expiry
"sig": "…", // HMAC-SHA256 over the same fields: the secret half of the proof
"priceBase": "1000",
"token": "0x3F43DA82eC9A4f5285F10FaF1F26EcA7319E5DA5",
"contract": "0xa2f2e042861a593cc582c6d2d43a24457dcf5d9c",
"merchant": "0xceeFC1Cf07984D823Db90FaC317069F8BDCDB761",
"chainId": 1990,
"resourceId": "block-summary",
"expiresAt": 1795079974,
"paymentDeadline": 1795080034 // must be mined by this chain time
}// what @turnspike-qie/client does for you, after checking the payee, network, price, limits and gas
const vault = new Contract("0xa2f2e042861a593cc582c6d2d43a24457dcf5d9c", [
"function pay(address owner, address merchant, bytes32 requestId, uint256 amount)",
], agentSigner);
const tx = await vault.pay(ownerAddress, challenge.merchant, challenge.requestId, BigInt(challenge.priceBase));
await tx.wait(2);// retry the same request with the full proof; sig is required
const proof = btoa(JSON.stringify({ requestId, txHash: tx.hash, sig }));
const res = await fetch("https://your-api/v1/block-summary", { headers: { "X-Payment": proof } });
// 200 delivered | 202 pending (retry after retryAfter) | 400 invalid_request | 402 refused proof
// 403 wrong_resource | 409 already_redeemed | 429 rate_limited | 503 rpc_unavailable or storage_unavailableSecurity model
- The proof is a capability. Whoever presents
{ requestId, txHash, sig }gets the paid response. requestId and txHash become public on-chain;sigis shown only in the 402 response, so it is the secret half. It is required on every redemption, including replays. - Payment, not identity. Turnspike proves a resource was paid for. It does not prove who the caller is. If a route returns private per-customer data, authenticate callers yourself before
turnspike(), or bind payers withallowedOwnersandallowedAgents. - One resource per proof. The challenge binds merchant, resource, price, chain and contract. A proof for
/address/Ais refused on/address/Bwith 403, and invalid input is refused with 400 before any price is quoted. - Delivery is durable and at-least-once for handlers. The response is written to SQLite before it is sent. If the process dies mid-handler, the handler runs again after the lease lapses, so handlers should be idempotent. The gateway never charges twice, and never stores more than one response per payment.
- A payment deadline, then no redemption deadline. The payment must be mined within 60 seconds of expiry (chain time). Once paid in time, the proof can be redeemed later, and the seller's reconciliation finds payments made while it was down.
- Replay key. On-chain the key is (merchant, requestId). Request IDs are random per challenge; an attacker who sees a pending ID could consume it and force the payer to request a new challenge, but cannot obtain the resource without the sig.
Middleware API
turnspike(config) returns an Express handler with .store, .reconcile(), .purge() and .close(). A price rule can also be an object { resourceId?, priceBase, binding?, validate?, preflight? }; a preflight that returns a string makes the gateway answer 503 before issuing any challenge, so nothing is charged.
| Option | Type | Notes |
|---|---|---|
| rpcUrls | string[] | QIE RPC endpoints, tried in order (failover). |
| chainId | number | Expected chain. A receipt from another chain is rejected. |
| contract | string | TurnpikeAllowance address. Only Paid logs from this address count. |
| token | string | QUSDC address, returned in challenges. |
| merchant | string | Address that must receive the payment. |
| hmacSecrets | string[] | [current, ...previous]. Each at least 32 bytes. Extra entries allow rotation. |
| dbPath | string | SQLite file. Use a persistent volume. |
| prices | Record<string, PriceRule | string | number> | Path (relative to the mount) to price in base units. Supports :param segments. |
| confirmations | number | Default 2. Fewer confirmations answer 202 pending. |
| challengeTtlSeconds | number | Default 300. |
| rateLimitPerMinute | number | Default 60 per IP. |
| retryAfterSeconds | number | Default 4, returned with 202. |
| paymentGraceSeconds | number | Default 60. The payment must be mined by expiresAt plus this (chain time). Redeeming an in-time payment has no deadline. |
| retentionSeconds | number | Default 30 days. Unpaid challenges are deleted only after the deadline, a chain reconciliation past it, and this period. |
| deliveryLeaseSeconds | number | Default 30, minimum 2. Renewed while the handler runs and fenced by a token; after a crash the handler re-runs once it lapses. |
| maxResponseBytes | number | Default 1 MiB. Responses are buffered and stored byte-exact (binary safe); larger ones are refused and the payment stays redeemable. No streaming. |
| allowedOwners | string[] | Optional payer binding: only Paid logs funded by these owner accounts are accepted. |
| allowedAgents | string[] | Optional payer binding: only Paid logs sent by these agent keys are accepted. |
| store | Store | Optional existing store instance. |
| onEvent | (e) => void | Structured events with correlation ids. Never receives proofs, sigs or bodies. |
Responses
| Status | Meaning |
|---|---|
| 200 | Delivered (also the stored response on replay). |
| 400 | invalid_request: your validate() refused the input before any challenge was issued. |
| 202 | Pending: no receipt, too few confirmations, a reorg in progress, or another request is delivering. Retry after retryAfter. |
| 402 | Payment required: a new challenge, or a refused proof. reason is one of malformed_proof, unknown_request, bad_signature, integrity, no_matching_paid_log, wrong_merchant, amount_below_price, owner_not_permitted, agent_not_permitted, tx_failed, wrong_chain, paid_too_late. |
| 403 | wrong_resource: the proof belongs to a different resource. |
| 409 | already_redeemed: transaction already backs a different request. |
| 429 | rate_limited. |
| 503 | rpc_unavailable, storage_unavailable, or a failed preflight (no challenge issued, nothing charged). |
Gateway endpoints
| Endpoint | Behaviour |
|---|---|
| GET /healthz | Liveness. |
| GET /v1/config | Chain, contract, token, merchant, price, confirmations, demoEnabled. |
| GET /v1/stats | Delivered counts, split into addresses the operator controls and others. |
| GET /v1/payments/:requestId | State only. Never returns the resource. |
| GET /v1/block-summary | Paid endpoint: live QIE block data, 0.001 QUSDC. |
| GET /v1/address/:address | Paid endpoint: live QIE and QUSDC balances, nonce and code flag for any address, 0.001 QUSDC. Each address is its own resource. |
| GET /v1/qusdc-activity/:address?blocks=N | Paid endpoint: QUSDC flows for an address over the last N blocks (100 to 50,000; default 20,000) from Transfer logs: totals in and out, net, counts, top counterparties. 0.002 QUSDC; the window is part of the paid resource. |
| GET /demo/status | Public demo budget and limits. |
| GET /demo/challenge | Proof-of-work puzzle needed to run the demo agent. |
| POST /demo/run/:scenario | Scripted agent (allowed, replay, over-cap, unauthorized-merchant). Needs a solved puzzle (x-demo-pow header) and is quota-limited. |
Contract
| Function | Caller | Effect |
|---|---|---|
| deposit(amount) | Owner | Pulls QUSDC via transferFrom. Reverts above the deposit cap. |
| withdraw(amount) | Owner | Never blocked by pause or revoke. |
| setPolicy(agent, perCallCap, dailyCap) | Owner | Sets the single authorised agent and limits. |
| setMerchant(merchant, allowed) | Owner | Allowlist. |
| revokeAgent() | Owner | Clears the agent. |
| setPaused(paused) | Owner | Blocks pay for this account only. |
| pay(owner, merchant, requestId, amount) | Agent | Checks limits, consumes (merchant, requestId), transfers, emits Paid. |
| account(owner), spentToday(owner), isUsed(merchant, id), allowedMerchant(owner, merchant) | Anyone | Views. |
Events: Deposited, Withdrawn, PolicySet, MerchantSet, AgentRevoked, PausedSet, Paid. There is no admin, upgrade or rescue function.
Error handling
Contract custom errors, as returned by a reverted pay or owner call:
| Error | Meaning |
|---|---|
| NotOwnerAgent | This agent is not authorised for that owner (revoked, or not the configured agent). |
| Paused | The owner has paused this account. Payments are blocked, withdrawals still work. |
| MerchantNotAllowed | That merchant is not on the owner's allowlist. |
| CapExceeded | Over the per-call limit. |
| DailyCapExceeded | Over the daily limit. |
| RequestAlreadyUsed | This request ID was already paid. Replay refused. |
| InsufficientBalance | Balance is too low for that amount. |
| DepositCapExceeded | That deposit would exceed the per-account deposit cap. |
| ZeroAmount | Amount must be greater than zero. |
| ZeroAddress | An address is required. |
Reverted transactions on QIE were charged exactly half their gas limit in all 5 samples (a hypothesis, not a confirmed rule), and eth_estimateGas fails for a call that reverts. Set the gas limit deliberately when you need a refusal on-chain.
Troubleshooting
| Symptom | Cause and fix |
|---|---|
| 402 bad_signature or malformed_proof | The proof must include the sig from the same 402 response, plus requestId and txHash, base64-encoded JSON with no extra fields. |
| 202 pending, no_receipt | The transaction is not mined yet, or the hash is wrong. Retry after retryAfter. If it never appears, the transaction was dropped. |
| 202 pending, confirmations | Waiting for the configured depth (default 2 blocks, about 8 s). |
| 402 no_matching_paid_log | The transaction did not emit Paid from the configured contract for this requestId. |
| pay reverts with MerchantNotAllowed | The owner has not allowlisted the merchant. Use setMerchant, or the app. |
| pay reverts with NotOwnerAgent | The signer is not the owner's configured agent, or the agent was revoked. |
| pay reverts with RequestAlreadyUsed | That requestId was already paid. Request a new challenge. |
| 402 paid_too_late | The payment was mined after the payment deadline (expiresAt + paymentGraceSeconds). It is recorded as paid but undelivered; there is no automatic refund. |
| client: untrusted_destination | The 402 came from an origin, or named a merchant, that is not on your payee list. Nothing was paid. |
| client: paid true with redeem_timeout | The payment is on chain. Call resume(key), or turnspike api resume key, later. Resume does not pay that purchase again. |
| client: payment_pending | maybePaid is true: the payment may have been sent, or another worker holds the key. Call resume(key) with the same key; never start a new purchase. CLI exit code 4. |
| client: idempotency_conflict | The key already belongs to a different method, URL or body. Nothing was paid; use a new key. |
| 503 storage_unavailable | The gateway could not read or write its SQLite file. Nothing was delivered or charged again. |
Source
- contracts/TurnpikeAllowance.solAllowance contract
- packages/middleware/src/index.tsExpress middleware
- packages/middleware/src/verify.tsReceipt verification
- packages/middleware/test/middleware.test.tsMiddleware tests
- packages/client/src/client.tsAgent client SDK
- packages/cli/src/cli.tsCLI
- docs/PROTOCOL.mdProtocol specification
- docs/INTEROPERABILITY.mdx402 evaluation
- examples/express-api/src/server.tsRunnable example API
- apps/gateway/src/server.tsGateway server
- apps/gateway/src/demo-guard.tsDemo abuse controls
- apps/gateway/src/agent.tsScripted agent