Docs

Build a seller or an agent

The quick starts, the wire format, every refusal reason and the limits.

Seller quick start

Charge for an endpoint. Prices are base units (bigint) or a decimal string of whole tokens ('0.001', using decimals, default 6). A price must be a multiple of unit.

import { createSeller } from '@preima/sdk/seller';

const seller = createSeller({
  payTo: SELLER_ADDRESS, asset: TOKEN, contract: TABS, unit: '0.001',
  rpcUrl: process.env.RPC_URL, gasKey: process.env.SELLER_GAS_KEY,
});
seller.start(); // the settle loop (Node). In a Worker, call `await seller.tick()` from a cron trigger.

export default { fetch: seller.protect('0.001', async (req) => Response.json({ ok: true })) };

Express-style:

app.get('/data', seller.express('0.001'), (req, res) => res.json({ ok: true }));

Node http without a framework: http.createServer(toNodeListener(handler)).

Options worth knowing:

OptionDefaultMeaning
storein memorynew FileSellerStore(dir) for anything that must survive a restart; see Storage for what a shared store must guarantee
minLifeSeconds7200SPEC 4 rule 3
settle.threshold'5.00'settle when unsettled value reaches this
settle.maxAgeSeconds86400or when the oldest unsettled payment is this old
settle.nearCloseSeconds21600or when the tab is this close to closableAt
settle.readIntervalSeconds3600re-read every open tab at least this often, in one batched call
maxAhead64a ticket may jump at most n * maxAhead payments past the last one, checked before any hashing
maxGap65536second bound: most hashes one ticket may cost to verify
maxFeeBps50highest fee a tab may be pinned at; a tab above it is refused
coin.maxStamprate when first seen, plus 10 percenthighest stamp a tab may be pinned at; above it the tab is refused (stamp-too-high). Set it explicitly in production
coin.marginBps2000extra share of the coin owed that the settling key must hold and have approved before the seller takes a ticket
coin.readEverySeconds600how often the coin, rate, and the settling key's balance and allowance are re-read (never under 60)
loggerconsole.errorwhere loud operator messages go
settle.gasBudget20,000,000one claim transaction settles at most (gasBudget - 300,000) / 140 payments; more is settled in chunks
pricebigint, decimal string, { amount, description, mimeType }, or a function of the request
alsoAcceptsnoneextra accepts entries, for example an exact entry; handleOther(request, payment) serves them
onEventnoneaccepted, settled, claimed-by-other, claim-failed, handler-error

What the middleware does (SPEC section 4): first sight of a tab it reads tab(tabId) and checks payer, seller, token, unit and count > claimed; it accepts a ticket only if lastK + n <= k <= count and hashing w back to lastK gives lastW; it refuses a tab pinned above maxFeeBps; on every ticket it refuses a tab whose closableAt is under minLifeSeconds away or that has a close requested; accepting a ticket is one compare-and-set in the store, and the wrapped handler runs only if the swap landed. A handler that throws returns a 500 and the payment is still taken. The reply is stored with the tab, so a retry of the last ticket (same tab, same k, same method and URL) gets it back byte for byte without running the handler, also after a restart. For a streaming route, pass { storeReplies: false } as the third argument of protect.

Settling. seller.tick() is one pass of the loop and is safe to call from a timer, a cron, or by hand; start() calls it every 60 s (it refuses an interval under 60 s unless allowFastPolling: true, meant for local chains only). A pass re-reads due tabs in one Multicall3 call (parallel single reads if the chain has no Multicall3), then for every tab that meets rule 6 it re-reads again, simulates claim, sends it in chunks that fit the gas budget, waits for each receipt and reconciles. Inside the last 6 hours before closableAt it also settles after every accepted ticket; await seller.flush() waits for those. A claim someone else already made is detected at the re-read or by the simulation reverting, and the record is reconciled with the chain instead of failing. A claim in flight is recorded before it is sent, so a restart never sends a second one for the same position.

After the coin launches: what a seller must do

$PREIMA has not launched. Until it does, nothing changes for a seller: a tab pins a 0.5 percent fee in USDG and a claim pays the seller the rest. After it launches, a seller cannot settle a tab without $PREIMA, so read this before it does. Agents never need the coin.

Once the owner sets the coin, every new tab for that token is stamped: each claim pulls paid * stamp coin from WHOEVER CALLS claim, burns most of it and sends a share to the Cube. For this package that caller is the seller's settling key, the gas key it settles with. So the coin must sit in the settling key, approved to the tabs contract; the seller address itself needs none. Nobody else can ever spend that coin: a stranger who calls claim pays with their own. A settling key with too little coin or approval cannot settle, and the owed payments are lost if the tab refunds first. A seller that has the coin locked in PreimaLock pays no stamp on tabs ending within the lock's horizon.

The package never serves what it cannot get paid for. On a stamped tab it adds up the coin needed to settle everything unsettled across all open tabs plus the new ticket, adds a margin (default 20 percent), and refuses the ticket with seller-needs-coin (HTTP 503, before the ticket is taken, so the payer loses nothing and the agent sends the same ticket again later) unless both the settling key's coin balance and its allowance to the tabs contract cover it. The log says which key to top up and by how much. Tabs with stamp 0 (locked seller, or opened before the coin) are unaffected.

The settling key is a hot key. It holds a private key on a server and is meant to hold gas dust; now it also holds coin. Keep in it only the coin you expect to burn soon, and top it up as you go.

Launch-day steps for a seller, in order:

  1. Know the coin address: await seller.coinStatus() returns coin once the owner has set it (null before), the rate, the settlingKey, its balance and allowance, what you owe for unsettled payments and any shortfall. Nothing changes for you until then.
  2. Get the coin: buy it, or lock it with the SELLER address for free settlement (steps 3 and 4 are then not needed for the tabs the lock covers).
  3. Move coin into the settling key (the gas key), enough for coinStatus().requiredWithMargin: the rate times the token value you expect to have unsettled, plus the 20 percent margin. Not more than you expect to burn soon.
  4. Approve the tabs contract from the settling key: await seller.approveCoin(amount) (coin base units). It always sends the transaction, because the gas key approves for itself. Use the same amount you put in the key.
  5. Set coin.maxStamp to the highest stamp you accept. By default it is the rate when you first see the coin set, plus 10 percent, computed once and kept in the store (a restart does not move it), so a later rate raise (the owner must give 7 days' notice) is refused on new tabs (stamp-too-high). The cap gates first sight of NEW tabs only. A tab you accepted tickets on is always settled at the stamp it pinned, whatever the cap or the rate is later: acceptance is the commitment.
  6. Strangers can open tabs to your address. The package only ever settles tabs it accepted tickets on, so an unwanted tab is left alone and refunds to its payer at expiry. If you lowered the cap and hold an open tab above it that has nothing unsettled, await seller.releaseUnwanted() ends it (a tab with accepted tickets that are not settled yet is never offered): release can be called only from the seller address, so if your gas key is a different account it returns the exact call instead of sending. Releasing returns the rest to the payer.
  7. Watch the log. REFUSING PAYMENTS and SETTLEMENT BLOCKED are printed at most once a minute. A claim that reverts StampUnpaid is retried only after a growing backoff, never in a loop; top up the settling key and the next pass settles.

Agent quick start

import { createAgent, EoaPayer, FileAgentStore } from '@preima/sdk/agent';

const agent = createAgent({
  payer: new EoaPayer({ privateKey: PAYER_KEY, rpcUrl: process.env.RPC_URL, chainId: 4663 }),
  tabKey: TAB_KEY,                 // 32 bytes hex; makes every tab secret (SPEC 2.1)
  contracts: [TABS],               // the only tabs contracts this agent will fund
  budgets: { perCall: '0.10', perTab: '5.00', perDay: '20.00', allowlist: ['api.example.com'] },
  store: new FileAgentStore('./agent-state.json'),
});

const res = await agent.fetch('https://api.example.com/data'); // pays a preima-tab 402, retries

agent.fetch is a drop-in fetch. On a 402 that offers preima-tab it finds or opens the tab for that seller, persists the new position k, sends the ticket, and returns the response. Repeat calls to the same URL skip the 402 round trip. Anything that is not a preima-tab 402 passes through untouched.

Rules the client enforces (SPEC 5):

  • A seller the agent has no history with gets a SMALL first tab: the price of firstTabCalls calls (default 20) or firstTab (default '0.50'), whichever is smaller, and never less than one call. The next tab is full size only after that seller has served trustAfterCalls calls (default 10) without a refusal, or has settled. So a hostile unknown seller costs at most that small deposit's time value plus one call.
  • A seller that proves a lie (it reports a position above anything the agent sent) is refused from then on (seller-lied), persisted in the agent store, until the operator calls await agent.forgive(seller, origin?). The refusal is keyed by the pair (origin of the URL, seller address): a page that merely names an honest seller's address and lies cannot get that seller refused for other origins. await agent.refusedSellers() lists them. A lying seller therefore costs one small tab and one call, not one tab per call.
  • Money is "locked" from the open until it is actually back: maxLocked (per asset), the per-seller limit budgets.maxLockedPerSeller (default twice the full tab size) and budgets.maxTabsPerDay (default 20, PER SELLER, with budgets.maxTabsPerDayTotal, default 200, as a backstop across sellers) all count retired and closing tabs until they are refunded.
  • Any agent built with createAgent must call maintain() on a timer (hourly is fine; the MCP server does it every 10 minutes). Without it nothing is refunded, idle tabs are never closed, and the locked-money limits eventually lock the agent out of a seller it trusts. createAgent logs a warning once if 24 hours pass with tabs open and no maintain() call (option logger).
  • maintain() refunds. Anyone may call refund, so for every tab of its own that has become closable (expired, or a day after its close request) the agent calls it, through the refund option of createAgent (for example gasKeyRefunder({ client, walletClient, account })) or the Payer's own refund(tabId, { contract }) (EoaPayer has one). It reports { action: 'refunded', tabId, hash, returned } with what came back, leaves a TooEarly refund for the next pass, and reports refund-unavailable if it has no way to send one.
  • One open tab per (seller, asset, unit). Size is min(budgets.perTab, defaultTab) (default '5.00', at most the contract's 2^17 payments), life 7 days. "Per tab" means the size of a tab.
  • Strictly ordered per tab: concurrent calls to one seller are paid one at a time, each holding the tab until the seller answers. A call to another seller does not wait.
  • The agent never moves forward on a seller's word. It remembers the highest position it has ever released on each tab. A refusal that reports a lastK at or below that only shows the agent is behind something it already sent, and it may move up to that and no further. A lastK above it is a lie (a seller trying to make the agent skip ahead and then claim the whole tab with one ticket): the agent stops paying on that tab, requests its close, and refuses that seller from then on (forgive(seller) undoes it). It never releases a value beyond what the calls made so far cost.
  • k is saved before the ticket is sent and is never reused. A ticket the seller refuses still counts as spent, because the seller has seen the value. The idempotency key is (tabId, k): after a network error the same ticket is resent, never a new one. A 402 after paying is a refusal, not a prompt to pay again: the client hands the refusal back (one exception: a refusal for a closing, expiring or closed tab retires it and the call is tried once on a fresh tab).
  • Budgets are refused locally, before any transaction or payment: perCall, perTab (the size of a tab), perDay (UTC day), allowlist (seller addresses or hostnames), optional maxLocked (total in open tabs, per asset). The three limits are required.
  • A 402 naming a tabs contract that is not in contracts is refused (untrusted-contract), so a seller cannot point an approval at its own contract.
  • Amounts: bigint base units, or decimal strings of whole tokens. Numbers are refused.
  • await agent.maintain() (call it on a timer, hourly is fine): requests close of idle tabs (idle for a day), requests close of retired tabs, and opens the next tab when one is nearly spent or within a day of expiry.
  • Read-only views, none of which hold a key or a chain value: listTabs({ refresh }), budgets(), walletBalance().

Sub-agent budgets: slice(m)

const slice = await agent.slice(20, { seller: SELLER });   // a plain JSON object
// hand `slice` to the child process over a private channel
const child = createSliceClient(slice, { statePath: './child.json' });
await child.fetch('https://api.example.com/data');          // pays from the slice only
child.state();                                              // { tabId, from, to, k, remainingPayments }
await agent.endSlice(slice.id, { usedK: child.state().k }); // the parent takes the tab back
// if the child died: ask the seller where it stopped (a junk probe, always refused, reports lastK; used only up to k+m),
// or read what the chain shows as settled: endSlice(slice.id, { fromChain: true })
await agent.endSlice(slice.id, { probeUrl: 'https://api.example.com/data' });

The slice carries w[k+m] and the range (k, k+m]. From that value a child can compute exactly m payments and no value past k+m, so it cannot overspend, and it pays only the seller of that tab. The top field inside the slice is a chain value: treat the whole object like a key, never log it, and never pass it through a model's context. The parent's position moves to k+m at once, the m units count against today's budget, and the parent makes no payments on that tab (slice-live) until endSlice. The parent never moves forward on the seller's word here either: endSlice resumes at most at k+m, because everything up to there was already released to the child. Where the child stopped is taken from usedK (the child's state().k), or fromChain: true (what the chain shows as claimed, which can lag until the seller settles), or probeUrl (the seller's report, clamped to the slice). Unused slice payments are forfeited if the parent ends the slice with none of these. A slice client that is told a position above anything it sent stops paying that seller (seller-lied).

The Payer interface

Anything with these members can open tabs. The agent computes tabId and tip itself and passes both in; a payer must open the tab with exactly these arguments.

{
  address: '0x..',                       // the account that will be the tab's payer
  async openTab({ contract, seller, token, unit, count, tip, expiry, salt, tabId }) { /* -> { hash, tabId? } */ },
  async requestClose(tabId, { contract }) { /* -> { hash } */ },
}

openTab resolves once the tab is mined. EoaPayer approves the contract for unit * count if needed and calls open. The EOA payer signs transactions with an elliptic-curve key, so it is for tests and simple use. WalletPayer (@preima/sdk/wallet, also exported from the package root) implements the same interface with a hash-key wallet: address is the wallet contract, openTab signs one action that approves and opens, submitted by a gas key that holds only gas dust and cannot move the wallet's money. The 24 words come from a file or an env var, are used once to make the key, and are never stored or returned. A wallet action carries a deadline from the wall clock, so give it a machine whose clock is right.

MCP server

The MCP server is inside the package, which is not on npm. After installing the package file from the home page:

claude mcp add preima --env PREIMA_CONFIG=/path/to/preima.json -- node node_modules/@preima/sdk/src/mcp/bin.js

Tools: preima_fetch (pay-and-fetch an http or https URL), preima_tabs (tabs and what is left; refresh reads the chain), preima_budgets (limits and today's spend), preima_maintain (run upkeep now), preima_wallet_balance. The server runs maintain() itself, once at start and then every 10 minutes (maintainEverySeconds), and logs what it refunded to stderr; forgive is deliberately not a tool, so a model cannot clear a refused seller. No tool returns a key, the tab key, a chain value, or the RPC URL: results are built from public fields only, payment headers are not passed on, the caller cannot inject payment headers, and every result is scrubbed of the secret strings the process holds. Errors are reduced to a code and a short message with URLs removed.

Configuration is a JSON file (--config <path> or PREIMA_CONFIG) plus environment variables; the environment wins.

Env varMeaning
RPC_URLchain RPC, read from the environment only (never put it in the file or on a command line)
PREIMA_CONTRACTScomma list of trusted PreimaTabs addresses (file field contracts)
PREIMA_CHAIN_IDdefault 4663
PREIMA_TAB_KEY_FILE or PREIMA_TAB_KEY32-byte hex tab key (a key file must be mode 600 or the server refuses it)
PREIMA_PAYER_KEY_FILE or PREIMA_PAYER_KEYkey of the EOA payer (the default payer)
PREIMA_PAYER=walletpay from a hash-key wallet instead; then PREIMA_WALLET_FACTORY, PREIMA_WORDS_FILE or PREIMA_WORDS (the 24 words; a file must be mode 600), PREIMA_GAS_KEY_FILE or PREIMA_GAS_KEY (pays gas only), PREIMA_WALLET_LEAF_FILE (spent one-time leaves, required), optional PREIMA_WALLET_INDEX, PREIMA_WALLET_TOP_CACHE
PREIMA_STOREagent state file
PREIMA_BUDGET_PER_CALL, PREIMA_BUDGET_PER_TAB, PREIMA_BUDGET_PER_DAY, PREIMA_BUDGET_MAX_LOCKEDlimits, decimal strings
PREIMA_ALLOWLISTcomma list of seller addresses or hostnames
PREIMA_ASSETS, PREIMA_DECIMALS, PREIMA_DEFAULT_TAB, PREIMA_MULTICALL3optional

Wire format

Sources read for this section (the coinbase/x402 repository, specs/): x402-specification-v2.md (PaymentRequired 5.1, PaymentPayload 5.2, SettlementResponse 5.3), transports-v2/http.md, x402-specification-v1.md, transports-v1/http.md. The exact scheme files were not needed.

v2v1
Payment required402 plus PAYMENT-REQUIRED header, base64 JSON402 plus JSON body with accepts
PaymentPAYMENT-SIGNATURE header, base64 JSONX-PAYMENT header, base64 JSON
ResultPAYMENT-RESPONSE header, base64 JSONX-PAYMENT-RESPONSE header, base64 JSON

A Preima seller sends both forms in one 402: the v2 header, and a body that is the v2 object with each accepts entry also carrying v1's maxAmountRequired and resource. It reads either payment header and answers in the matching form. Preima adds one header of its own to requests, Idempotency-Key.

The captured examples below come from the end-to-end test (a local chain with id 31337, so the network reads eip155:31337; on Robinhood Chain it is eip155:4663).

  1. The first request gets a 402. PAYMENT-REQUIRED, decoded:
{
  "x402Version": 2,
  "error": "PAYMENT-SIGNATURE header is required",
  "resource": { "url": "http://127.0.0.1:61833/data" },
  "accepts": [
    {
      "scheme": "preima-tab",
      "network": "eip155:31337",
      "asset": "0x<token address>",
      "payTo": "0x<seller address>",
      "amount": "1000",
      "maxTimeoutSeconds": 60,
      "extra": {
        "contract": "0x<tabs contract address>",
        "unit": "1000",
        "minLifeSeconds": 7200
      }
    }
  ]
}

amount is the price of the call in token base units and must be a multiple of extra.unit; n = amount / unit payments are due. maxTimeoutSeconds is required by x402 v2 and is not used by this scheme.

  1. The agent opens or finds its tab, then retries with PAYMENT-SIGNATURE, decoded:
{
  "x402Version": 2,
  "resource": { "url": "http://127.0.0.1:61833/data" },
  "accepted": { "...": "the accepts entry above, unchanged" },
  "payload": {
    "tabId": "0xce45bece60f42e176bc39b251d89e268e7e4cc87259a173019f3be302204c960",
    "k": 1,
    "w": "0x5450a3e1838a4ad1479cffc2e281e7f2c739f27d5443c2d08a444d713b7499c3"
  }
}

Plus Idempotency-Key: <uuid>. payload is the SPEC 3 payload. In v2 the scheme and network live inside accepted, not beside payload as SPEC 3 sketches. v1 sends { "x402Version": 1, "scheme": "preima-tab", "network": "...", "payload": { "tabId", "k", "w" } } in X-PAYMENT.

  1. The seller serves the call and answers with PAYMENT-RESPONSE, decoded:
{
  "success": true,
  "transaction": "",
  "network": "eip155:31337",
  "payer": "0x<payer address>",
  "amount": "1000",
  "tabId": "0xce45bece60f42e176bc39b251d89e268e7e4cc87259a173019f3be302204c960",
  "k": 1,
  "settled": 0,
  "remaining": 4999
}

success, transaction, network, payer and amount are x402's fields (transaction is empty because no transaction is made per call). tabId, k, settled (payments claimed on chain, as last read) and remaining (payments left) are Preima's. amount is what this ticket moved the position by.

  1. A refusal is a 402 (400 for a malformed payment) with a fresh PAYMENT-REQUIRED header and a JSON body that adds reason, and lastK (the seller's position on the tab) on every refusal that knows the tab. A v1 payer gets x402Version: 1 in the body. Captured v1 refusal body:
{
  "x402Version": 1,
  "error": "replay: this payment, or a later one, was already accepted",
  "resource": { "url": "http://127.0.0.1:61833/data" },
  "accepts": [ { "scheme": "preima-tab", "amount": "1000", "maxAmountRequired": "1000", "...": "as above" } ],
  "reason": "replay",
  "lastK": 2
}

Retrying the same ticket on the same request returns the stored reply (same body and PAYMENT-RESPONSE) without serving the call again. The key is (tabId, k); the agent also sends Idempotency-Key: <tabId>:<k> for logs, and the seller does not depend on it. The reply to the last ticket of each tab is kept in the seller store, so this also holds after a restart; the same ticket on any other request is a replay.

Refusal reasons

Seller refusals (the reason field of the 402 body):

ReasonStatusMeaning
payment-required402no payment header
malformed-payment400header, payload, tabId, k or w could not be read
wrong-scheme402not preima-tab and no handleOther served it
wrong-network402not this seller's eip155:<chainId>
wrong-asset, wrong-recipient, wrong-contract, wrong-unit402the accepted entry does not match what this seller offers
unknown-tab402no such tab on chain (or not mined yet)
tab-wrong-seller, tab-wrong-token, tab-wrong-unit402the tab was opened for something else
tab-fee-too-high402the tab was pinned at a fee above maxFeeBps
stamp-too-high402the tab was pinned at a coin stamp above the seller's coin.maxStamp
seller-needs-coin503the seller's settling key cannot cover the coin it owes at settlement; nothing was taken, resend the same ticket later
tab-closed402nothing left to claim on the tab
tab-closing402the payer asked to close it
tab-expiring402closableAt is less than minLifeSeconds away
replay402k <= lastK; body carries lastK
too-few-payments402k < lastK + n; body carries lastK and the current amount
beyond-tab402k > count
gap-too-large402k - lastK is over n * maxAhead (refused before any hashing) or over maxGap
bad-preimage402w does not hash back to lastW
chain-unavailable503the first-sight read failed; retry
rate-limited429too many first-sight tab reads in a minute
storage-error503the durable write failed; nothing was served and k was not accepted

How the agent reacts: seller-needs-coin, chain-unavailable, rate-limited and storage-error mean the seller took nothing: the agent steps back to the previous position (and gives the day's budget back), so the next call sends the same ticket again. replay and too-few-payments return the refusal to the caller; if the reported lastK is at or below the highest position the agent has sent, the agent moves up to it (never further), and if it is above, the tab is ended and closed, and the seller is refused, as a lie (a refusal is never a prompt to pay again); tab-closing, tab-expiring and tab-closed retire the tab, and the call is tried once on a fresh tab; anything else is returned to the caller as the 402 it is.

Local refusals by the agent (thrown as PreimaError with a code; nothing is sent): over-per-call, over-per-tab, over-per-day, over-max-locked, seller-not-allowed, untrusted-contract, wrong-chain, tab-too-small, seller-min-life, slice-live, no-tab, ambiguous-tab, no-slice, tab-expiring, probe-failed, open-failed, over-max-locked-per-seller, over-max-tabs-per-day, seller-lied. A slice client adds slice-exhausted and over-per-call.

Storage

Seller store: getTab, casTab(tabId, expectedRev, next), listTabs, getReply, putReply, getMeta, casMeta (small shared records: the coin ledger and the persisted default cap), and a scope: 'process', 'host' or 'shared'. MemorySellerStore (scope: 'process') and FileSellerStore(dir) (scope: 'host').

casTab is the only write the seller makes to a tab and the only thing that accepts a ticket (SPEC 4 rule 4). Contract: with expectedRev === null, create the record only if none exists; otherwise replace it only if the stored rev equals expectedRev; return true only if the swap landed, and when it does the record is durable. It must be atomic and linearizable per tab across every seller instance sharing the store.

  • MemorySellerStore is atomic inside ONE process only and forgets everything on exit. Pass processes: 2 (or more) to createSeller and it refuses to start on this store.
  • FileSellerStore keeps one file per revision (<tab>.<rev>.rec), created by writing a complete temp file and hard-linking it to its final name: the operating system lets exactly one process create a given name, so exactly one of several processes wins each revision. Every read takes the highest revision from the directory itself (one directory listing, no cache and no hint), and every write, revision 0 included, is checked after its link: if a higher revision exists the write is undone. The price is that a read costs one listing of the directory, so it grows with the number of files in it (about 32 per tab). listTabs is one pass over the directory (1,000 tabs list in 0.2 s after a restart, not 29 s), and the seller deletes records of tabs that closed more than 30 days ago (settle.archiveAfterSeconds). It is atomic across every process on one host and one local volume (PM2 or cluster mode, several containers on one volume), proved by the test B-M3 with three real processes. It is not safe on NFS or other filesystems without reliable hard links, and not across machines.
  • A Durable Object store (one object per tab): do the compare and the put inside one blockConcurrencyWhile or transaction and let the output gate hold the response until the write is durable. A D1 or SQL store: a single UPDATE ... SET data = ?, rev = ? + 1 WHERE tab_id = ? AND rev = ? and test rows-affected, with creation as INSERT ... ON CONFLICT DO NOTHING. Redis: WATCH/MULTI or one Lua script. A store that reads, compares and writes in separate steps lets one ticket buy many calls.
  • Several seller instances that share one settling key must share one store: the coin they owe is reserved in it (a compare-and-set on a ledger record) before each ticket is accepted. A reservation is kept by position and is pending for 120 seconds: a ledger rebuild keeps a pending reservation and takes the larger of the ledger entry and the tab record, and a lower reservation never overwrites a higher pending one, so the ledger never counts less than a live acceptance has promised. A reservation that never lands (a refused ticket, an instance that died) is dropped by the first rebuild after 120 seconds, so it can over-count for at most two minutes. Instances on separate stores must use separate settling keys, or together they can promise more coin than the key holds.

Agent store: load(), save(state); MemoryAgentStore and FileAgentStore(path). The agent file holds positions and tab facts only: no key and no chain value, since tab secrets are re-derived from the tab key, with a checkpoint every 1024 values so any w[k] is under 1024 hashes away.

Limits

  • One tab per (seller, asset, unit) for an agent. Both sides need this package, or another implementation of the same scheme: a plain x402 client cannot pay a preima-tab seller, and a plain seller cannot take these tickets.
  • Calls to one seller are paid one at a time, so one agent's throughput to one seller is bounded by that seller's round-trip time.
  • The seller needs a gas key. It can only call claim, which pays the seller. After the coin launches that key also needs coin (see above), or the seller address needs a lock.
  • The stamp's dollar value follows the coin's price until the owner moves the rate by hand; the seller's coin.maxStamp is the only protection against a raise.
  • The settling key's coin balance and allowance are read on a slow timer, so coin spent elsewhere between reads can make a settlement revert (StampUnpaid); it is retried with backoff.
  • The settling key is a hot key that holds coin. Keep little in it.
  • The seller's extra.stamp in a 402 is informational. Agents ignore it. It holds gas dust and cannot move anyone's money, but a seller with no gas settles nothing, and a payer's close request must be settled within one day.
  • A seller must read its tabs at least hourly and settle within the one-day close window; a seller that is down for longer than a tab's close window can lose the unsettled payments to the refund.
  • Money at risk on the paying side is what is left in open tabs with that seller, bounded by the tab size and the agent's budgets. A seller that takes a ticket and serves nothing keeps that ticket's payments.
  • A seller learns of a payer's close request, a third-party claim or an expiry only when it reads the chain: at first sight of a tab, hourly, and before it claims. A handler that fails after taking the ticket still consumes the payment.
  • Settlement is by claim(tabId, k, w), in chunks under the gas budget. A stamped claim adds two coin transfers. Measured on the fork with real USDG: 1,000 payments settle in one claim of about 254,000 gas; the hash-key wallet's create is about 138,000 and its approve-and-open action about 613,000. This is execution gas; the chain's L1 data fee is not included.
  • A Worker without a long-lived process has no timer: run tick() from a cron trigger and use a store that survives restarts. The in-memory store loses every position on restart.
  • The EOA payer uses an elliptic-curve key. Nothing in this package is described as safe from a signature break beyond the tab tickets themselves.
  • Not audited.

Six endpoints at https://api.preima.xyz sell Robinhood Chain data per call, in USDG. They are sold through the seller middleware above, so they are also a seller to test an agent against. The catalogue is at api.preima.xyz and the OpenAPI description at api.preima.xyz/openapi.json.

EndpointPriceWhat it returns
GET /v1/ping0.001 USDGServer time, a block number read at most 10 seconds ago and where this ticket left your tab.
GET /v1/gas0.001 USDGGas price, base fee and block read at most 10 seconds ago, and the execution gas cost in ETH of a transfer, a tab open and a 1,000 payment claim.
GET /v1/exposure/{address}0.002 USDGKey exposure report for an account: transaction count, code size, EIP-7702 delegation, ETH and USDG balance, and a plain verdict.
GET /v1/token/{address}0.002 USDGERC-20 facts in one read: name, symbol, decimals, total supply, code size and owner, each null if the token does not answer.
GET /v1/balances/{address}?tokens=a,b,c0.002 USDGETH balance plus up to 20 token balances with decimals and symbol, in one read (USDG if no tokens are named).
POST /v1/simulate0.005 USDGRuns a call at the latest block without sending it: return data or revert data with the decoded reason, and a gas estimate.

Pay one with the agent. The tabs contract is the one in deployment.json.

import { createAgent, EoaPayer, FileAgentStore } from '@preima/sdk/agent';

const agent = createAgent({
  payer: new EoaPayer({ privateKey: PAYER_KEY, rpcUrl: process.env.RPC_URL, chainId: 4663 }),
  tabKey: TAB_KEY,
  contracts: ['0xda5c1c78c34a26ee5f2a0ce683fc0f41f41aa5df'],
  budgets: { perCall: '0.01', perTab: '0.50', perDay: '2.00', allowlist: ['api.preima.xyz'] },
  store: new FileAgentStore('./agent-state.json'),
});

const res = await agent.fetch('https://api.preima.xyz/v1/ping');
console.log(await res.json());
  • Inputs are checked before any payment is looked at: a bad address or body returns 400 and costs nothing.
  • Only the last ticket taken on a tab can be sent again: to the same method and URL it returns the stored reply, whatever that was, and is not charged twice. An earlier ticket is refused as a replay.
  • No ticket is taken in the last six hours before a tab can be refunded (tab-expiring); the agent opens the next tab before then.
  • A ticket is taken before the chain is read. If that read fails, after one retry where the request budget allows, the reply is 502 with paid: true and the payment is not returned; sending that ticket again returns the same stored 502. Block and gas data up to 60 seconds old is served in that case, marked stale.
  • Gas figures are execution gas. The chain's L1 data fee is not included.

More

Two longer references have their own pages.

  • The agent wallet: the hash key, the signed digest, calldata, gas and the wallet's limits.
  • The token layer: the stamp, the lock, the Cube and the Board, with every owner power and notice.