Charges a USDC price for one HTTP call. It answers unpaid calls with a 402, verifies the agent’s authorization, submits the settlement and pays its network fee, runs the handler once the settlement is confirmed, signs the receipt and posts it to the API.
Version 0.2.0. Install it with the two packages it depends on:
npm install ./civitas-contract-0.2.0.tgz ./civitas-program-0.2.0.tgz ./civitas-service-0.2.0.tgzExports
paywall
function paywall(options: PaywallOptions, handler: ServiceHandler): PaywallHandler;Wraps a fetch-style handler: (request) => Response. Make it once per route, since the quotes it issues live in it, and await its ready() before serving.
paywallMiddleware
function paywallMiddleware(options: PaywallOptions): PaywallMiddleware;The same as Hono middleware. Mount it once on the route, before the handler, and await its ready() before serving.
PayeeConfigurationError
class PayeeConfigurationError extends Error {
readonly code: 'PayeeChartered' | 'PayeePrincipalMismatch';
constructor(code: 'PayeeChartered' | 'PayeePrincipalMismatch', message: string);
}What ready() rejects with when the payee’s charter doesn’t match principal. Its code is PayeeChartered (the payee is chartered and principal was left out) or PayeePrincipalMismatch (it is chartered under another wallet). The message names the principal on chain.
PaywallOptions
interface PaywallOptions {
price: bigint;
payee: Keypair;
submitter: Keypair;
principal?: string | PublicKey;
rpcUrl: string;
apiUrl?: string;
cluster: string;
programId?: string | PublicKey;
usdcMint?: string | PublicKey;
lookupTable?: string | PublicKey;
}What both take.
pricebigintrequired- The price of one call in base units, paid to the payee. Above zero.
payeeKeypairrequired- The service agent’s key pair. Payments land in its vault when it is chartered, otherwise in its USDC account, and it signs every receipt.
submitterKeypairrequired- The key pair that signs and pays for each settlement transaction. It needs SOL, and pays for the payee’s USDC account when an unchartered payee has none.
principalstring | PublicKey- The wallet that chartered the payee. Required when the payee is chartered: at start the service reads the charter and refuses to run if it names another wallet, so nobody can charter your payee key and take its payments.
rpcUrlstringrequired- The Solana RPC the settlements are sent to.
apiUrlstring- The Civitas API’s base URL. When set, each receipt is posted to
POST /v1/receipts, retried once a second later. The receipt is in the response either way. clusterstringrequired- The network name the 402 quotes, which the agent checks against Civitas’s config.
programIdstring | PublicKey- Checked against the program ID the package was built for.
usdcMintstring | PublicKey- Checked against the mint in the program’s config.
lookupTablestring | PublicKey- An active address lookup table to build the settlement transaction over.
ServiceHandler
type ServiceHandler = (request: Request) => Response | Promise<Response>;The handler that serves a paid call. It runs only after the settlement is confirmed.
PaywallHandler
type PaywallHandler = ((request: Request) => Promise<Response>) & {
readonly ready: () => Promise<void>;
};What paywall returns: the handler, with ready().
PaywallMiddleware type
type PaywallMiddleware = MiddlewareHandler & {
readonly ready: () => Promise<void>;
};What paywallMiddleware returns: the middleware, with ready().
Each call
- At start, it reads the payee’s charter once. A chartered payee must match
principalorready()rejects withPayeeConfigurationError. An unchartered payee is paid into its USDC account from then on. - A call without
X-PAYMENTgets a 402 with a fresh 32-byte call ID. The quote holds for 60 seconds. It names the URL the agent called: behind a TLS-terminating proxy the service rebuilds it from the firstX-Forwarded-ProtoandX-Forwarded-Hostvalues. - A paid retry must match its quote: URL, method, content type, body, network, price, payee, mint and expiry (
PaymentMismatch), and sign the quoted fee (FeeMismatch). - The service verifies the agent’s Ed25519 signature itself (
BadSignature) and claims the call ID, so a call settles once (ChallengeUsed). - It submits a compute budget instruction, the Ed25519 instruction and
settle, and sends the same signed bytes again until the transaction is confirmed, fails on chain, or its blockhash has provably expired. - Once confirmed, it runs the handler, hashes the exact response body, signs the receipt with the payee key, posts it, and answers with
X-PAYMENT-RESPONSEandCache-Control: private, no-store.
Quotes live in the process that issued them, at most 4,096 at a time. A restart drops them, and with several processes the paid retry has to reach the one that quoted.
Refusals
A refused call is answered with JSON { "error": "<name>" }. A 402 refusal carries a fresh quote beside it, so the agent can pay again.
error | HTTP | When |
|---|---|---|
PaymentRequired | 402 | The first answer to an unpaid call, with the quote. |
InvalidPayment | 402 | The X-PAYMENT header isn’t a valid payment payload. |
UnknownChallenge | 402 | The call ID isn’t one this process issued, or its quote was dropped. |
ChallengeUsed | 402 | This quote was already paid. |
AuthorizationExpired | 402 | The quote’s expiry passed. |
PaymentMismatch | 402 | The paid retry differs from the call that was quoted. |
BadSignature | 402 | The signature doesn’t verify for these authorization bytes and this agent key. |
FeeMismatch | 402 | The authorization signed a fee other than the one the quote stated, or the program refused the signed fee. |
QuoteChanged | 402 | The program’s fee terms or mint changed after the quote. Pay the fresh quote. |
InsufficientFunds | 402 | The payer’s vault doesn’t hold amount plus fee. |
SettlementExpired | 402 | The transaction’s blockhash expired without it landing. |
SettlementRejected | 402 | The chain refused the transaction for a reason that isn’t a program error. |
SettlementUnconfirmed | 503 | The RPC answered with a different signature than the one the service signed. The body carries the service’s transaction signature: look it up before paying again. |
PayeeChartered | 402 | The payee had no charter when the service started and someone chartered its key since. Nothing moved and nothing was served; the operator restarts the service with principal. |
QuoteUnavailable | 503 | The service couldn’t read the program’s config to quote. |
SettlementUnavailable | 503 | The service couldn’t build or send the settlement. |
QuoteCapacity | 503 | The process holds 4,096 open quotes. Retry once some expire. |
A refusal from the program comes back in the 402 under its program error name, with a fresh quote: OverPerCallLimit, OverPeriodCap, PayeeNotAllowed, AgentFrozen, AgentRevoked, PolicyExpired, NonceReplayed.