Guides

Paying from an agent

Run @civitas/agent in a real program: one fetch per key, two layers of limits, the receipt, and what to do with each refusal.

@civitas/agent turns an agent key into a fetch that pays Civitas services. This guide assumes a chartered, funded agent; Pay per call gets one.

One fetch per key

createAgentFetch hands out the agent's nonces. Its first paid call reads the agent's highest settled nonce and starts one above it; every later call takes the next one. Make one fetch per agent key when your process starts and share it, and concurrent calls never collide.

Two processes holding the same key each start from the same high mark, and the second settlement with a given nonce is refused with NonceReplayed. Give each process its own agent, chartered under the same principal, or coordinate the nonces yourself.

agent.ts
import { readFileSync } from 'node:fs'
import { createAgentFetch } from '@civitas/agent'

const secret = Uint8Array.from(JSON.parse(readFileSync(process.env.AGENT_KEYPAIR_PATH!, 'utf8')))

export const agentFetch = createAgentFetch({
  agent: secret,
  api: process.env.CIVITAS_API_URL,
  maxPerCall: 250_000n,
})

With api set, the fetch takes the fee terms and the starting nonce from the Civitas API. Without it, it reads them from the chain through rpcUrl.

Two limits

The agent's policy is enforced by the program on every settlement, and the principal sets it. maxPerCall is the agent's own check, made before it signs: a quote whose price plus fee is above it fails with OverPerCallLimit and nothing is signed. Set it at or below the policy's per-call limit, so an expensive quote fails in the agent instead of costing the service a refused transaction.

The fee comes on top of the price. A call priced at 5,000 base units costs 5,500 with its fee.

What comes back

A paid call returns the service's response with payment on it: the settlement's transaction signature and the service's signed receipt. The fetch has already checked the receipt's signature against the payee key, and that it names this call, this payer, this payee and this amount.

The receipt also carries the SHA-256 of the body the service served. To hold the service to its response, hash the bytes you read and compare:

check-body.ts
import { createHash } from 'node:crypto'
import type { AgentResponse } from '@civitas/agent'

export async function readChecked(response: AgentResponse) {
  const body = new Uint8Array(await response.arrayBuffer())
  const digest = createHash('sha256').update(body).digest('hex')
  if (response.payment && digest !== response.payment.receipt.responseHash) {
    throw new Error('The body differs from the one the service signed for.')
  }
  return body
}

A call that wasn't asked to pay comes back as it was, with no payment.

Refusals

A refused payment throws AgentPaymentError. Branch on its name:

nameWhat to do
OverPerCallLimitThe call costs more than the agent or its policy allows. Skip it, or have the principal raise the limit.
OverPeriodCapThis period's budget is spent. Wait for the next period, or have the principal raise the cap.
AgentFrozenThe principal froze the agent. Stop calling until it is unfrozen.
AgentRevokedThe agent is closed for good. Stop.
PolicyExpiredThe policy's expiry passed. The principal sets a new policy.
PayeeNotAllowedThe service isn't on the agent's counterparty list.
AuthorizationExpiredThe quote expired before it settled. Make the call again for a fresh quote.
FeeMismatchThe quoted fee isn't Civitas's, or the fee terms changed before the settlement landed. Make the call again for a fresh quote.
NonceReplayedAnother process used this nonce. See One fetch per key.
InvalidPaymentRequiredThe quote doesn't match the resource, the program or Civitas's fee terms, or expires further ahead than the agent signs for. Don't pay it.
InvalidPaymentResponseThe service answered without a receipt that verifies.

Every name is on @civitas/agent.

A 503 with SettlementUnconfirmed carries the settlement's transaction signature, and the fetch returns that response as it came. The payment may still land: look the signature up before calling again.

What comes next

Today the agent pays services that charge with @civitas/service. The next build lets it pay any x402 service on Solana that quotes the exact scheme, from the same vault and under the same policy.