Reference

@civitas/service

Every export of the service SDK, its options, what it does with each call, and every refusal it answers with.

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:

install
npm install ./civitas-contract-0.2.0.tgz ./civitas-program-0.2.0.tgz ./civitas-service-0.2.0.tgz

Exports

paywall

ts
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

ts
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

ts
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

ts
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.

PaywallOptions
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

ts
type ServiceHandler = (request: Request) => Response | Promise<Response>;

The handler that serves a paid call. It runs only after the settlement is confirmed.

PaywallHandler

ts
type PaywallHandler = ((request: Request) => Promise<Response>) & {
    readonly ready: () => Promise<void>;
};

What paywall returns: the handler, with ready().

PaywallMiddleware type

ts
type PaywallMiddleware = MiddlewareHandler & {
    readonly ready: () => Promise<void>;
};

What paywallMiddleware returns: the middleware, with ready().

Each call

  1. At start, it reads the payee’s charter once. A chartered payee must match principal or ready() rejects with PayeeConfigurationError. An unchartered payee is paid into its USDC account from then on.
  2. A call without X-PAYMENT gets 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 first X-Forwarded-Proto and X-Forwarded-Host values.
  3. 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).
  4. The service verifies the agent’s Ed25519 signature itself (BadSignature) and claims the call ID, so a call settles once (ChallengeUsed).
  5. 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.
  6. 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-RESPONSE and Cache-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.

errorHTTPWhen
PaymentRequired402The first answer to an unpaid call, with the quote.
InvalidPayment402The X-PAYMENT header isn’t a valid payment payload.
UnknownChallenge402The call ID isn’t one this process issued, or its quote was dropped.
ChallengeUsed402This quote was already paid.
AuthorizationExpired402The quote’s expiry passed.
PaymentMismatch402The paid retry differs from the call that was quoted.
BadSignature402The signature doesn’t verify for these authorization bytes and this agent key.
FeeMismatch402The authorization signed a fee other than the one the quote stated, or the program refused the signed fee.
QuoteChanged402The program’s fee terms or mint changed after the quote. Pay the fresh quote.
InsufficientFunds402The payer’s vault doesn’t hold amount plus fee.
SettlementExpired402The transaction’s blockhash expired without it landing.
SettlementRejected402The chain refused the transaction for a reason that isn’t a program error.
SettlementUnconfirmed503The 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.
PayeeChartered402The 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.
QuoteUnavailable503The service couldn’t read the program’s config to quote.
SettlementUnavailable503The service couldn’t build or send the settlement.
QuoteCapacity503The 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.