Tokens, trading and metered execution
Research snapshot of November 23, 2026. Code and issue observations refer to the cited revisions and collection times.
The Currency, market offers and execution budgets adds an exact supply-audit counterexample and ties offline settlement and execution budgets to separate invariants. The Three design records for repository review gives the compatible correction choices.
An ID token represents a grant or capability offered by a particular server or world. Its issuer determines the in-world entitlement. The public term is units. The existing identifiers containing currency remain wire and library compatibility contracts. Drew selected double-entry accounting with Units, Pending and Revoked as account classes. The account classes of a token programme share one ledger. This chapter proposes how to extend those decisions to a game inventory, an offer and a budget a world may spend on its user’s behalf. Token ruling and extension · Governing v1 design and decisions
Architecture already present
Source inspection uses main at 4cfceaa8afc08cf2cea88b9d733a2ace14c8ad5a. Entries describe code or recorded decisions. Source inspection establishes neither deployed behavior nor a passing test run.
| Concern | What the source establishes | Consequence |
|---|---|---|
| Asset identity | Immutable definition, signing issuer key and BLAKE3 hash of canonical CBOR. Scale is at most 18. Finite cap is a u128, including zero. The v1 classes of signed events are token.define, token.issue, token.transfer and token.burn. Wire types | Existing objects keep their identities and signatures. Display the issuer and binding when rendering same-symbol offers. |
| Offline graph balances | The pure fold evaluates authenticated events in causal order with deterministic tie breaking. It parks missing ancestry or bodies, verifies body hashes, excludes disputed issuance and voids overspends at their ordered position. Signed snapshots can be recomputed. Fold · Snapshots | Two isolated peers can both observe locally affordable spends. The common event set converges. Show the frontier and pending/disputed status to the recipient. Do not sell an irreversible external service on the strength of a partial graph view. |
| Anchored settlement | The gateway verifies signed canonical requests, resolves devices and checks registry authorization. The recovery scanner persists/reuses transfer IDs, queries the ledger and surfaces impossible partial linked chains. Reconciliation compares issuer net debits against holder, fee and burn accounts and resolves graph links. Gateway · Recovery · Supply audit | Retain the signed graph as authority for definitions and authorization, and the bound ledger as balance authority. Require a settlement receipt for an anchored grant. The application and the rest of ID can operate without that currency service. |
| Registry integration | The root directly depends on id-currency-registry. Its gateway PoC and reconciliation module import it. The registry has a Postgres migration, deterministic account factory, and grant/hold abstractions. Manifest · Gateway integration · Grant service | Retain the crate. The root-dependent description is already present in ARCHITECTURE.md. The existing grant service has policy-driven vest, partial refund through void/reissue, and late clawback/debt. Preserve these independently of a computation sub-budget’s lifecycle. |
| Hosted transport | The worker README describes the TS currency directory as a proof of concept. It contains a single-process gateway/ledger stub, client-signed transfer/hold intents, server-scoped signed snapshots, a persist-before-dispatch relay with wake reconciliation, and bilateral signed server entries. Its harness includes lost replies and mutated retries. The main worker and UserDO sources reviewed here do not import the currency directory. README · Proof cases · Worker | Do not describe this source tree or another worker feature landing as evidence of a live currency endpoint, a production TigerBeetle settlement service, or cross-server atomicity. Reuse the tested boundary on both routes. |
| Fuel and payer | The id-worlds sandbox enables Wasmtime fuel and rejects guest imports. Guest calls enter GuestBurnBudget, which limits concurrent calls, orders waiters by attained service, and records settled fuel per world and account. Charge selection uses an explicit admin account first, a configured creator next, then the caller. Missing required creator fails. Missing caller identity under caller charging uses the world charge key for local accounting. ID’s lockfile selects Wasmtime 49.0.6. Sandbox · Admission · Payer selection · Lockfile | Keep the process-local fairness path for authorized calls. A scheduling counter or world fallback bucket provides no withdrawal authority. Bind spendable units to a separately issued, validated grant scoped to the selected payer. |
The signed body cannot currently designate the supply-account exception and the fold deliberately counts every issuance. The base design documents the exception and an unresolved counting detail. Recheck the later #5522/#2251 issue trail before changing a serialized field or requesting a decision. Keep historical canonical bytes valid even if a future contract adds a new marker. Fold contract · V1 decision
Proposed capability and asset model
Use the v1 semantic identity as ERTP’s brand; the public representation is copyable. Issuance requires the existing authorized issuer/generation. A transfer requires the sender’s signed authorization, the intended operation, and verification by the chosen binding. Sharing an image, currency definition, amount description, signed receipt or Atlas search result must confer no way to debit its holder. Give the UI separate handles for viewing an account, receiving payment, spending within a limit, and issuing supply. Resolve a lost reply by a persisted request ID before signing a replacement. ERTP issuer/mint model · ERTP purses and payments
For identical inventory items, use ordinary finite units with integer quantity. For a unique item, the conservative interoperable building block is a programme with cap one and scale zero, verified issuer, and a signed metadata link to content-addressed art. Cap one alone does not define whether an item burned today can be reissued tomorrow. A unique collectible needs both one live owner and a lifetime issuance/reissuance policy, including the supply-account exception. Keep the item class gated until those rules are specified. Replicated art and names remain readable under their own media permissions. An offline game may accept graph-provisional ownership under its published rules. Mark any item whose use consumes a remotely supplied scarce resource as requiring the appropriate anchored receipt.
Proposed market and escrow contract
An advertisement contains the issuer-qualified asset identifiers, public terms, binding, expiry and offer digest. Query and match can run on any peer, locally, or in an Atlas derivative; an index entry is a discovery hint. An acceptance names the exact terms/version, both sides’ authorized accounts, maximum give, minimum want, acceptance of fees, and exit conditions. A peer may attach a signed offer during a partition. The interface shows whether it is advertised, accepted awaiting escrow, reserved, settled, canceled/refunded, expired, or disputed.
- Begin with firm, whole-fill offers. An accepted seat specifies one set of give/want quantities and explicit fees. Partial fills require an opt-in lot size, integral price calculation and minimum cumulative output per fill. Sequential matching and book ordering are local policies. The safety predicate must hold for each independently accepted seat regardless of match ordering.
- Reserve the
giveassets under their bound authority. A matcher produces a candidate reallocation but cannot move assets. In one settlement domain, validate all inputs, floor/scale/fee terms, expiry and expected revisions before submitting the linked postings. Each seat receives at least its entire acceptedwantbundle or recovers its full escrowedgive. Fees for failed offers require separate authorization if supported. An equivalent retry returns the terminal outcome; a conflicting reuse fails. Offer safety · Atomic reallocations · TigerBeetle linked events - For crash recovery span the graph, intent store and ledger with persisted intent, deterministic leg IDs, reconciliation and an idempotent publication outbox. A single storage transaction cannot cover all those stores. Across servers maintain the ruled bilateral signed entries and explicit reconciliation. Never describe two independent acknowledgements as an atomic swap. A common escrow holding both assets can offer a stronger guarantee only after both deposits and its authority, exit rights and recovery assumptions are established. When escrow is unavailable, the UI retains its last signed status and displays pending until reconciliation. Recorded boundary and PoC results · Durable Object storage scope
- Where the trade is a currency conversion, reuse the signed directional rate authorization and exact-version quote, explicit fee, checked integer arithmetic and linked-leg conversion executor. At admission check the latest unrevoked authorization, quota and authenticity. The stage-adapter design makes authorization at durable admission binding: recovery completes an admitted conversion even if that authorization later expires or is revoked. A fresh intent must pass the current checks. For Pending Units, retain Drew’s specific countersigned chain of options and time/exit policy. A generic offer must never let a pending unit fund ordinary use or bypass the original grant’s provenance. Keep ambiguous option-escrow timing outside the generic settlement path pending current #2296 evidence. Conversion design · Grant ruling
Backend transitions and identity
The staged design has distinct guarantees. Redis plus its durable store admits and recovers in sequence. A destination credit is spendable after the durable posted mark. A transfer spanning independent Turso databases can pass through a recoverable saga with held funds and compensations. A TigerBeetle linked chain settles atomically within its supported domain. Surface the weakest active guarantee to both counterparties and test migration with pending and posted records under the same canonical receipts. The performance figures in the verification programme are targets until timed on an identified deployment. Staged contract · Verification programme
An identity detail matters before a backend migration. Today the hash covers the entire canonical definition body, including its serialized binding and numeric ledger on an anchored definition; a changed body changes the semantic ID. Preserve that historical definition when a backend changes. A proposed, signed operational routing record can map its immutable binding to a fenced replacement instance, with both backends’ last verified watermarks and the old instance closed for writes. If the logical binding itself changes, use an explicit predecessor/successor relation and authorized migration, with both identities visible. Add a vector that moves a deployment and still verifies old signed events before promising portable IDs across backend changes. Definition encoding and hashing · Backend transition seam
Proposed fuel budget
A fuel quote names the app digest, executor identity, payer, allowed effect classes, maximum guest units, maximum host units, conversion ratio to any grant units, schedule version and expiry. Optional local execution uses operator-funded capacity or a local grant. A remote executor may require a finite grant before admission. A local meter unit is never implicitly transferable or redeemable at every server.
- Reserve. Verify the payer’s signed budget, audience/executor, method set, version and revocation generation. Reserve against that budget before admitting any effect that incurs a charge. Splitting a parent into child funds debits the parent’s available amount. Child limits, expiry, operation set and audience can only narrow. A child grant must fail an attempted reserve if its parent is revoked under the selected validation policy. A non-expiring offline delegation cannot promise immediate remote revocation.
- Execute. Retain the pure guest boundary and existing fairness scheduler. Price host effects where the host consumes an approved command, with prevalidated bounds such as input bytes, maximum output bytes, per-batch items and request count. Apply a separate memory cap, storage quota, cancellation deadline and job concurrency limit. Pin guest bytes, runtime/configuration, ABI, arithmetic/rounding and host cost schedule for reproducibility. Record external inputs once and replay their receipts. A native app backend that cannot enforce equivalent instruction metering advertises the usable capability subset or runs the metered guest on a permitted host.
- Settle. The receipt commits invocation ID, grant, caller, app, schedule version, reserved maxima, debits by resource, released remainder, execution outcome, and effect receipt hashes. Enforce checked arithmetic and total debit no greater than authorized reserve. On success bill measured guest units and priced host effects per schedule. Current upstream Wasmtime documentation says accounting on trap may be inexact, and a blocked host call is outside Wasm execution control. Distinguish a quoted per-slice trap charge for operator-sponsored quota from exact per-instruction billing. Require release-specific conformance before exposing any transferable debit for a failed guest. Refuse an ambiguous external effect retry unless its adapter supports persisted idempotency/status resolution. Wasmtime fuel and host calls · Determinism constraints
- Recover. Reopen a durable intent after a restart and reconcile by invocation and effect IDs. Charges need an immutable idempotency record beyond a live Wasmtime store. Expiry, cancellation or revocation blocks new spend at its serialization point. A charge already committed stays part of the receipt; release unspent reservations once. Restoration of an export rebuilds a view. It cannot create a second writer or regenerate held spending authority. In a partition only an exclusive authority with a specified fencing/anti-equivocation scheme can promise independently spendable preallocation. The graph default remains verifiable provisional claims. Escrow-rights precedent and assumptions
- Bound abuse. Reject invalid, oversized, expired and unauthorized commands before decoding/dispatching expensive work. Rate-limit untrusted ingress by byte cost and burst at the node and account/grant level; reserve bounded storage and queue space. Preserve the existing queue rule for eligible fuel-bounded guest calls and weighted sponsor budgets. Opening extra worlds must not multiply one payer’s entitlement. A restricted, exhausted, or offline service still permits local graph drafts and reading previously authorized data. ID guest admission · Burst/rate definitions
Conformance oracles and implementation order
Use signed fixture inputs, a deterministic logical clock, fixed schedule and independent reference balances. Run the same operation sequence through the public caller-facing path, graph-native and anchored backends where the guarantee applies, and hosted relay with an injected lost reply. These are proposed verification cases. No test suite was run for this research pass.
| Case | Input or fault | Required observable result |
|---|---|---|
| Entitlement buckets | Credit 100 available. Reserve 40 and 60. Consume 10 against the first and close it. Close the second twice. | After reserve: 0 available, 100 reserved. First close: 30 available, 60 reserved, 10 consumed. Final: 90 available, 0 reserved, 10 consumed once. Explain whether the consumed 10 is a burn or a credit to a service account. Pending is a reservation against posted balances and never counted twice. |
| Canonical identity | Same display name/symbol, two issuer keys. Try to fulfill issuer A’s offer with issuer B’s asset. | Reject before escrow changes any balances. Rendering still lets the user distinguish both. |
| Fork and order | Two graph spends from the same initially sufficient balance. Reorder deliveries; omit then restore a body or ancestor. | Authenticated complete sets fold identically; pending descendants move zero until complete. Anchored intents affect no ledger balance on their own. |
| Grant and authorization | Split beyond remaining budget; widen child permissions; route to wrong executor; race revocation and reserve; creator-charged world has no creator. | Each refused operation produces zero debits. An acknowledged earlier commit retains its receipt. Missing creator charges nobody. A local fallback accounting key signs no debit. |
| Trading | Alice escrows 5 available units for item K; Bob escrows K for 5. Mutate a term after signing; try cancel vs settle; lose the successful reply. | Exactly one terminal outcome. Full original allocations or the promised swap; no partial spend, duplicate item or fee surprise. Same ID/new payload conflicts. Verify final balances and unique ownership separately from receipt count. |
| Availability | Suppress a signed receipt after ledger commit; crash before publication. Restore a backup to another relay, then reconnect. | Resubmission with original IDs reconciles to one ledger movement. Client views catch up; older import cannot resurrect closed rights. A half-observed bilateral trade remains unresolved. |
| Cost and performance | Guest exhausts fuel; deterministic success; host exceeds byte/expiry bound; native profile cannot meter guest. | All charges fit the quote, bounds apply before side effects, and exact on-trap billing is never inferred. A stalled adapter yields a bounded terminal or explicitly pending outcome. Two worlds charging one account share its ceiling. |
- Register fixtures alongside existing tests. Qualify the
currencytests,id-currency-registryacceptance suite, hosted currency proofs andid-worldsaccounting tests against the same binding matrix. Start with existing identity/fold and request replay vectors; make the next small code slice a new failing-oracle case on an owned issue. The first new feature candidate is a read-only, versioned per-call resource receipt distilled from the existing execution boundary. Its acceptance condition is one receipt for the same guest result through public invocation without changing accounting or the ABI. - Connect budgets after authority is established. Consolidate with the existing app-facing surface in #2803, the runtime work in #1067, and existing grant tracks #2294, #2295 and #2723. The open census shows #2803 carries both parked and claimed labels, #2723 parked/assigned and #1067 in review. None was claimed during this pass. Check newest individual claim comments and domain-specific approvals before working.
- Resolve settlement dependencies in order. #2290 and #3801 govern rate authorization verification. #3802 tracks quote binding and #5536 the conversion engine. The source contains PoC execution and directional authorization types; a production settlement claim requires an observed production entry point and a working backend. #5676 already has an architecture and correctness programme through the staged backend design and its verification programme. Avoid parallel design of a new default backend. Cluster provisioning #2292 has independent topology/review/cost constraints and is unnecessary for the fixture or documentation slice.
- Extend to item exchange. Name the authoritative binding per offered asset. Design an additive item descriptor referencing the existing definition. Prove whole-fill, single-domain swaps before adding order-book indexes, partial fills and pending-option trades. File missing slices only after deduplication against current main and live owners. Outstanding policy details in archived records require fresh review of current #2296 and #5522 discussions before escalating to Drew.
A same-pass search of open repository PRs found #12539 for per-account quota policy and a fuel-rate ledger, its stacked #12557 for charging the update allowance before invocation, and #12348 for pending hold/adverse-event handling. Those PR bodies describe work in review. Treat existing GitHub owners as the first route for receipt/fixture changes addressing their slices. Keep rate-limit debits, measured successful guest fuel and separately authorized token settlement distinct in the public API. No claim or merge is inferred from labels; fresh issue comments and later merge state must be checked at the time of implementation.