Skip to main content
TokenSwap is a product and protocol design in development. The TEE Gateway, usage receipt protocol, and capacity-cap settlement described on this page are not shipped yet.

Overview

TokenSwap is the first service-matching application built with OpenContract. A Seller with otherwise-idle API, subscription, bundle, or committed capacity lists a ticket for a defined future time window; a Buyer that needs AI inference capacity accepts it at a fixed price. The traded object is an AI Usage Ticket, not an API key and not a financial token. A ticket is a non-transferable right to consume a bounded AI inference service under an agreed policy:
  • a provider and model tier;
  • a start and end time window;
  • a maximum spend and/or usage allowance, enforced as a hard cap rather than billed per unit;
  • reserved throughput, rate limits, and concurrency;
  • allowed use and content policy;
  • a minimum availability threshold used to determine settlement;
  • evidence, receipt, and logging requirements.
TokenSwap uses OpenContract for commitments, money, disputes, and settlement. Actual model invocation and metering happen off-chain inside a Usage Gateway, ultimately a Trusted Execution Environment (TEE) Gateway.
In TokenSwap, usage tokens are model input, cached-input, and output units. They are unrelated to any future OpenContract protocol or governance token.

End-to-End Flow

A single view of the whole lifecycle — listing, credential provisioning, the per-call loop, periodic checkpoints, and settlement — with where encryption applies at each hop: Three storage locations, three different contents:
  • Encrypted evidence log — every call’s full record (Part 1 ciphertext + Part 2 plaintext), decoupled from the TEE’s own compute instance and from OpenContract’s database. See Evidence Storage and Checkpointing.
  • OpenContract’s Postgres — contract state (WorkingContract) and checkpoint history (ContractCheckpoint) — hashes and aggregate counts, never content.
  • Buyer — its own real-time copy of every response and signed receipt, independent of both of the above.

Why TokenSwap Uses OpenContract

A conventional API proxy can route requests and collect payment, but it does not create a neutral, auditable agreement between a capacity Buyer and Seller. TokenSwap applies OpenContract’s service-contract primitives to continuous machine-delivered work: TokenSwap sells a capacity cap for a fixed price, not a metered pay-as-you-go service: the Buyer pays once for the right to use up to the ticket’s allowance within its window, there is no usage-based billing and no refund for unused capacity, and the Buyer cannot cancel after accepting. The TEE Gateway enforces the cap directly — it rejects requests once the allowance or window is exhausted — so usage receipts exist to prove the cap was respected and the capacity was actually available, not to calculate a bill.

Participants

Each participant has a defined responsibility and a corresponding trust boundary: facts or decisions that cannot be established by that participant’s claim alone. The Gateway Operator is a distinct protocol role. OpenContract may operate the first Gateway, but the contract must not assume that OpenContract and the Gateway Operator are permanently the same entity. Future tickets may select an OpenContract-operated TEE, a qualified third-party TEE, or another approved gateway implementation.

Separation of Control

TokenSwap separates money and adjudication from secrets and execution:

OpenContract controls

  • ticket creation, matching, and lifecycle state;
  • Buyer escrow, Seller Stake, and Dispute Bond;
  • the committed policy hash and approved TEE measurement;
  • receipt checkpoints and the final evidence commitment;
  • deterministic settlement and escalation to dispute resolution;
  • refunds, payouts, and slashing.

TEE Gateway controls

  • the Seller’s scoped upstream credential;
  • Buyer request authentication and replay protection;
  • request and response plaintext inside the protected execution boundary;
  • time-window, quota, rate-limit, and model-policy enforcement;
  • provider invocation;
  • quota state and receipt sequence;
  • receipt signing and evidence-log commitments.
The OpenContract application and its ordinary backend must never receive the Seller credential or Buyer prompt in plaintext in the TEE design.

AI Usage Ticket

A ticket is a worker-initiated Fixed Working Contract tagged application: "tokenswap". Fields every Working Contract already has cover most of what a ticket needs and aren’t repeated here: The fields below are TokenSwap-specific and don’t fit the generic schema — they live in Application Metadata, a structured, unvalidated-at-the-protocol-level JSON object rather than separate Working Contract columns:

Ticket policy (Application Metadata)

maxCost, usageAllowance, reservedThroughput, and rateLimits are enforcement ceilings, not billing inputs: the TEE Gateway rejects a request that would exceed any of them (quota_exhausted, policy_rejected) rather than letting it through and charging extra. Input, cached-input, output, and multimodal units may have different throughput weights, so maxCost still needs its own ceiling even when token allowances are also set. policyHash, used throughout this page, is the hash of this Application Metadata object’s canonical serialization — not a separately stored field. Because Application Metadata is written once at Create Contract time and the row is never mutated afterward, its commitment is exactly the ticket’s existing creation record in OpenContract; a party that wants policyHash recomputes it from the stored object rather than trusting an independently-supplied value.

Pricing model

TokenSwap sells a fixed-price capacity cap, not metered usage:
  • The Buyer pays the full Ticket Price at match. There is no per-unit usage charge and no refund for capacity the Buyer did not use.
  • The Buyer cannot cancel after match; the price is fixed and disclosed before acceptance, so there is nothing to renegotiate mid-window.
  • Usage receipts and checkpoints are not billing inputs — they exist to prove the Buyer stayed within the enforced caps and to evidence whether the Seller actually kept capacity available, which is what settlement is based on (see Settlement).
  • Seller Stake should cover credible replacement-cost exposure, not only a fixed percentage of ticket price.

Key Inventory

Every claim in this page ultimately rests on who holds which key and what crosses the wire between them. Each participant keeps exactly one long-term identity key and never exports it; every value that crosses a boundary between two parties without an existing channel goes through the same pattern — a fresh ephemeral key, endorsed by the sender’s long-term identity key, used to derive a one-time or session-scoped shared secret via ECDH, then discarded once its job is done.

Buyer

Seller

TEE Gateway

OpenContract

OpenContract issues Bearer API Keys to the Buyer and Seller after verifying a one-time signature from each party’s identity key, and stores the TEE’s signing public key on the ticket so Buyer and Seller can verify the TEE’s signatures. It never receives any party’s private key, the Provider credential, or Part 1 plaintext.

TEE Attestation and Credential Provisioning

The Seller does not encrypt a credential to a permanent platform key. It provisions the credential only after verifying a fresh TEE instance: The Seller-provided credential should be:
  • dedicated to one ticket or a narrowly bounded ticket pool;
  • restricted to agreed models, endpoints, projects, and regions where supported;
  • protected by an upstream hard spend and throughput limit;
  • short-lived or immediately revocable;
  • deleted or revoked when the ticket closes.
TEE protection reduces trust in the Gateway Operator, but upstream limits still bound loss if the TEE, its policy, or provider adapter contains a bug.

Request Lifecycle

Every accepted request is authorized by the Buyer and processed against the committed policy: Rejected and failed requests also produce signed denial receipts. Each status class carries a fault attribution — which party’s availability record it counts against, if any — used by Settlement: gateway_network_failure replaces a plain gateway_unavailable: a TEE can already tell the difference in code between “I can’t reach the Provider at all” (network/infrastructure layer) and “the Provider rejected my credential” (application layer, gateway_credential_failure) without needing a human judgment call — so the denial receipt should say which one happened rather than collapsing both into one ambiguous status. This distinction matters specifically because the Gateway Operator isn’t always the Seller — in the Closed MVP, OpenContract operates the Gateway itself (gatewayType: platform), so a gateway_network_failure there is OpenContract’s own fault, not the Seller’s. Without denial receipts, a Seller or Gateway could omit failed attempts and present a misleading availability record.

Usage Receipts

Public usage receipt

The settlement-safe receipt excludes prompt and response plaintext:
Request and response commitments must include ticket-specific context, sequence, canonical content, and a random salt. An unsalted hash of a short or predictable prompt may permit dictionary guessing. The salt remains in the private evidence envelope, never disclosed. contentPolicyViolation carries the upstream Provider’s own moderation/safety verdict for the call (most providers already flag or refuse policy-violating requests) — it’s a plain boolean the Provider already computed, not something derived from Buyer content, so it belongs in the public receipt rather than the private envelope. It’s the primary evidence for Buyer Misuse Complaints.

Private evidence envelope

The actual prompt and response are encrypted separately, to the Buyer’s own key only:
This envelope exists so the Buyer can browse its own usage history later — the Buyer already receives the plaintext response directly at call time, so this is a durable personal copy, not new information. Nobody else ever needs it: settlement only needs the public receipt above (see Settlement), and Buyer Misuse Complaints resolve from contentPolicyViolation, not from re-reading content. Single-recipient encryption is deliberate — a scheme where the Seller, OpenContract, or a dispute resolver could also decrypt it would mean the Buyer is being asked to hand over evidence against itself, which it has no incentive to do. Seller-side allowed-use restrictions narrower than the Provider’s own policy (a ticket’s allowedUse disallowing something the Provider’s moderation wouldn’t itself flag) are a known gap this doesn’t cover — deferred rather than solved with added key-sharing complexity.

Evidence Storage and Checkpointing

Every receipt must be durable, but every full receipt does not need to be stored in OpenContract or posted on-chain. The encrypted evidence log is not the TEE’s own working memory, and not local disk on the machine running the TEE — a real TEE’s protected memory is small and expensive, and tying durable evidence to one compute instance’s lifecycle risks losing it if that instance is terminated or its operator stops it (see Trust Model). The TEE only needs to hold constant-size working state at any moment — remaining quota, the hash of the most recent receipt (to extend the chain), and the in-flight call_intent — and flushes each signed receipt out to durable storage as soon as it’s produced (see Crash-safe metering); nothing accumulates in the TEE itself as the ticket’s call count grows. That durable storage is also kept separate from OpenContract’s own database: it’s bulk, rarely-read, per-call data with a very different cost and access profile than OpenContract’s settlement-critical state, and coupling the two would make the Gateway’s live operation depend on OpenContract’s availability for every checkpoint — see Separation of Control. Since the public receipt fields carry no Buyer content (only the private envelope does — see Private evidence envelope), who operates or administers this storage doesn’t affect confidentiality; it only affects durability and cost.

Periodic checkpoint

The TEE submits a checkpoint after a configured number of receipts, elapsed time, or uncommitted value. ticketId is the URL path parameter, not a body field; the cumulative counts are TokenSwap-specific and live in data — see Application Metadata:
Submitted via POST /v1/contracts/:id/checkpoint, callable only by the ticket’s Seller (workerId), any number of times while the contract is matched — this never advances the contract’s status; only a Final Receipt (below), submitted through the existing Submit Delivery call, moves it to under-review. GET /v1/contracts/:id/checkpoints returns the full ordered history for a given ticket — this is a generic Working Contract capability (see Contract Structure), not TokenSwap-specific, though TokenSwap is the only application using it today. OpenContract enforces, today:
  • fromSequence picks up exactly where the previous checkpoint’s toSequence left off (gapless, and starts at 1) — rejected with 409 otherwise;
  • checkpointedAt strictly increases from one checkpoint to the next.
Not yet enforced — teeSignature/teeMeasurement are stored but not cryptographically verified against the ticket’s approvedMeasurements, since no real TEE attestation infrastructure exists yet in this phase (gatewayType: platform); the Merkle root and hash chain are likewise stored as opaque anchors rather than independently recomputed. These land once TEE-Ledger (see MVP and Evolution) provides something real to verify against. maxUncheckpointedExposure limits the value the TEE may consume without a successful checkpoint. When the threshold is reached, new calls pause until the checkpoint is accepted.

Final receipt

At expiry or exhaustion, the TEE revokes or deletes the credential and signs the final state:
The final receipt is the TokenSwap equivalent of a Working Contract delivery. Unlike a generic delivery, criteriaMet is written automatically the instant the final receipt lands — see Settlement — so there’s nothing subjective left for the Buyer to review. The Buyer may still approve early or dispute before the Review Deadline; if the deadline passes with no action, the ticket resolves to that already-computed outcome rather than a blind default.

Evidence Chain

The complete cooperation record is:
The hash chain establishes receipt order. Merkle proofs establish inclusion in a committed batch. Neither primitive independently proves that a log is complete; completeness additionally depends on Buyer-held receipts, monotonically increasing sequence numbers, TEE-enforced logging, bounded uncheckpointed exposure, and upstream billing reconciliation.

Crash-safe metering

The TEE persists a call_intent and reserves quota before invoking the provider. It finalizes the receipt only after receiving provider usage metadata. If the TEE crashes after the provider may have charged the Seller but before finalization, recovery exposes an indeterminate call rather than silently dropping it. The provider request ID and billing record are then used for reconciliation. TEE sealed storage protects confidentiality but does not by itself prevent an operator from restoring an old encrypted snapshot. Recovery must reject any quota or sequence state older than the latest OpenContract checkpoint. Upstream hard spending limits remain the final loss bound.

Verification and Disputes

TokenSwap resolves deterministic evidence before recruiting Backup Agents: Backup Agents do not vote on cryptographic facts such as whether a signature is valid or whether a timestamp falls inside a window. They adjudicate only evidence that deterministic verification cannot resolve. TEE attestation proves that approved code issued the invocation and receipt under the committed policy. It does not cryptographically prove which model weights an upstream provider executed internally. Model-integrity claims therefore use combined evidence rather than TEE evidence alone.

Buyer Misuse Complaints

Availability isn’t the only thing that can go wrong with a ticket — a Buyer can also misuse the capacity it bought (prohibited content, illegal use) without ever causing an availability shortfall the Seller is responsible for. Nothing about that failure mode is reflected in the single Acceptance Criterion in Settlement, which only measures whether the Seller kept capacity available — so it needs its own path, separate from settlement. TokenSwap uses the protocol-generic Complaints mechanism for this — see File Complaint for the API. A Seller flagging Buyer misuse is TokenSwap’s motivating case, not a bespoke TokenSwap-only feature: either party can file, the same way on any Working Contract.
  • Who files, in TokenSwap’s case: the Seller, against the Buyer, when it observes misuse. The mechanism itself is bidirectional — a Buyer could equally file about Seller conduct unrelated to availability — TokenSwap just doesn’t prescribe a specific evidence shape for that direction yet.
  • Window: a fixed period after the ticket’s Review Deadline, the same protocol-generic window every Working Contract gets — not anchored to the ticket’s own endsAt, so the mechanism doesn’t need to read TokenSwap-specific policy to enforce it.
  • Evidence: contentPolicyViolation on the relevant receipt(s) — see Public usage receipt. This is the upstream Provider’s own moderation verdict, already public, so no content ever needs to be decrypted to file or adjudicate a complaint. A ticket’s allowedUse terms narrower than the Provider’s own policy (something the Provider’s moderation wouldn’t itself flag) aren’t covered by this evidence and are a known gap, deferred rather than solved by giving the Seller or a resolver access to the Buyer’s private evidence envelope — see Private evidence envelope for why that’s single-recipient by design.
  • Adjudication: OpenContract reviews each complaint directly rather than recruiting Backup Agents — the same lightweight path as the manual outbound-transfer review described in Payments & Custody, not the on-chain V2C flow. This is an early-stage tradeoff, not a permanent one; it may move to Backup Agent adjudication once volume justifies it.
  • Outcome has no effect on this ticket’s settlement. No funds move either way — the Ticket Price is still paid or refunded purely by the availability criterion, regardless of how a misuse complaint resolves. A complaint only writes a reputational record, and it’s symmetric to discourage frivolous use of it: upheld records a violation against whoever it was filed against; rejected records an unfounded complaint against the filer instead. Both sides’ Agentic Resume complaintRecord reflects this regardless of role.

Settlement

TokenSwap tickets carry exactly one Acceptance Criterion, authored by the protocol rather than by either party — a Buyer-negotiated or Seller-authored criterion would put one side in a position to grade its own performance:
The Seller maintained the ticket’s committed capacity availability during the service window.
This single criterion is evaluated automatically at Submit Delivery: OpenContract computes availability from the ticket’s checkpoint history and compares it against the ticket’s sla threshold, rather than trusting an availability figure the Seller or Gateway reports. availability itself is computed with a three-way fault split, not a Buyer-or-Seller binary — see the fault column in Request Lifecycle:
seller_attributable_failures excludes both Buyer-caused denials (those aren’t a Seller availability failure at all — the TEE is just enforcing limits the Buyer agreed to) and Gateway-Operator-caused denials (gateway_network_failure) — the latter is neither Buyer’s fault nor Seller’s, so it’s dropped from the ratio entirely rather than defaulting onto either side. This matters concretely in the Closed MVP, where OpenContract operates the Gateway itself: an outage in OpenContract’s own infrastructure must not silently count against the Seller it’s also judging.
  • met — final availability ≥ the ticket’s sla threshold, with no unresolved indeterminate calls.
  • not met — the threshold was missed for reasons attributable to the Seller.
  • unclear — the evidence is inconclusive (e.g. conflicting attestation or provider records); resolved through the Backup Agent / dispute-resolver path in Verification and Disputes.
Because there is exactly one criterion, Working Contract settlement collapses to a binary outcome — a ticket is either fully-met (full Ticket Price paid to the Seller) or none-met (full refund to the Buyer) — partially-met cannot occur. An unclear result defaults to fully-met under the same all-unclear rule as any other Working Contract, unless the Buyer disputes and Backup Agents resolve it to not met. At ticket close:
  1. The TEE submits the final receipt and evidence root.
  2. OpenContract computes availability from the checkpoint history it has already accepted and writes criteriaMet immediately — no Buyer action is needed to produce this result. Each checkpoint was checked for gapless continuity when it was submitted; verifying its TEE signature, measurement, and policy hash arrives with real attestation (see Periodic checkpoint).
  3. The Buyer may approve early, dispute, or take no action before the Review Deadline. On silence, the ticket resolves to the already-computed outcome from step 2, not a blind default.
  4. A dispute posts the configured Dispute Bond and identifies the contested receipt range or availability claim.
  5. Deterministic checks run first; an unresolved claim recruits qualified dispute resolvers.
  6. OpenContract pays the full Ticket Price to the Seller and returns Seller Stake (fully-met), or refunds the Buyer in full and slashes Seller Stake (none-met), and resolves the Dispute Bond per Working Contract settlement.

Trust Model

TokenSwap uses several complementary controls. Encryption protects confidentiality, isolation limits access, hashes bind data and state, signatures authenticate actors and receipts, and attestation authenticates the TEE execution environment. No single control proves that the complete system is correct.

Residual risks not covered above

  • The Gateway Operator can still stop the machine or block its network even with correct, attested code running.
  • Attestation-service failures, and hardware, firmware, or side-channel vulnerabilities, are outside what a valid measurement can rule out.
  • A policy-compliant request can still be harmful or illegal; attestation verifies code and policy, not legality or intent.
  • OpenContract cannot create a valid TEE receipt without the attested receipt key, and credential scope, upstream limits, checkpoints, escrow, and stakes bound the loss from every failure mode above that cryptography alone cannot prevent.
These risks are handled with redundancy, monitoring, scoped credentials, provider reconciliation, SLA remedies, stake, dispute resolution, and supplier eligibility rules rather than by claiming the system is fully trustless.

MVP and Evolution

Closed MVP

The first test may use one Buyer and one Seller, one provider adapter, test-value escrow, and an OpenContract-operated Gateway. Its purpose is to validate the ticket lifecycle and evidence semantics:
  • create and match an AI Usage Ticket;
  • commit a policy hash;
  • provision a dedicated, capped, revocable credential;
  • authenticate Buyer requests;
  • enforce window, quota, and rate limits;
  • generate usage and denial receipts;
  • build a receipt hash chain and periodic roots;
  • submit a final receipt;
  • exercise approval, a simulated dispute, and settlement.
The MVP may initially substitute a process-isolated Gateway for a production TEE, but it must preserve the same interfaces for secret storage, attestation, signing, policy evaluation, receipt storage, and checkpointing. Its trust assumptions must be disclosed as gatewayType: platform.

Current prototype status

The rest of this page describes the target design. The process-isolated Gateway that exists today implements a subset of it, and differs from it in the ways below. All of it has been exercised end to end against a testnet ticket. Implemented
  • Ticket creation, with policy validation: allowedModels must be non-empty, and the service window must sit inside the ticket’s own deadlines (see Ticket policy).
  • The Seller-TEE provisioning handshake and the Buyer-TEE session handshake, each an ephemeral key exchange endorsed by the initiating party’s identity key; sellerApiKey and the Provider credential are delivered only through the former, and the Buyer’s archival public key is bound into the latter’s signed message (see Key Inventory).
  • Enforcement of the service window, nonce replay, the model allowlist, the output-token usageAllowance, and credential presence, each producing a signed denial receipt with the fault attribution above.
  • A hash-chained receipt log with Part 1 encrypted to the Buyer’s archival key, periodic checkpoints carrying per-status counts, a Final Receipt submitted through Submit Delivery, and automatic settlement from the checkpoint history.
  • Destroying the credential, sellerApiKey, and session key once the Final Receipt is submitted; the Gateway then refuses further calls.
Not yet implemented, or different from the design
  • No attestation or hardware isolation. teeMeasurement is a fixed placeholder and the Gateway’s signing key is generated fresh per ticket rather than persisted, which is why the trust assumption is disclosed as gatewayType: platform.
  • No per-request Buyer signature. A request is authenticated by the handshake and the session key, which proves to the Gateway that the Buyer sent it but not to a third party. Receipts therefore carry no buyerRequestSignature, and the Verification and Disputes row on unauthorized requests cannot be resolved by signature verification yet. In this phase that rests on trusting the operator; with attested, reproducibly built Gateway code it stops depending on that trust.
  • Only some policy is enforced. rateLimits, maxCost, reservedThroughput, and allowedUse are not, so buyer_rate_limited and provider_rate_limited are never produced.
  • A mock Provider. There is no real upstream call, so provider_error and provider_rate_limited cannot arise from a real Provider.
  • A reduced receipt. Fields such as policyHash, providerRequestId, timestamps, cached-input tokens, cost, and quota before and after are not recorded.
  • No crash-safe metering. There is no durable call_intent, indeterminate recovery, or maxUncheckpointedExposure pause.
  • A local evidence log. Receipts are appended to a local file standing in for the external durable storage described in Evidence Storage and Checkpointing.
  • Calls are in-process. The Gateway is a library called directly, not yet a separate network service.
  • sellerApiKey is not scoped. It is the Seller’s ordinary platform key rather than one limited to this ticket’s checkpoint and delivery endpoints.

TEE-Ledger

Move receipt signing, quota state, sequence state, and checkpoint construction into an attested environment. Add sealed-state recovery and rollback protection.

TEE Gateway

Move credential provisioning and the complete Buyer-to-provider request path into the TEE. Buyer requests and provider responses remain encrypted outside the attested environment.

Verification TEE and open supply

Add pre-listing and pre-window verification of Seller access, multiple qualified Gateway Operators, provider billing reconciliation, supplier authorization classes, and redundant TEE deployments.

Non-goals

TokenSwap is not:
  • an API-key marketplace;
  • an account- or subscription-sharing product;
  • a transferable claim on future cash flows;
  • a prediction market;
  • a secondary market for an OpenContract protocol token;
  • proof that an upstream provider internally executed particular model weights;
  • a replacement for provider terms, supplier authorization, privacy review, or applicable regulation.
The open-market version should admit only supply whose authorization permits the Seller to provide the contracted downstream service. The closed MVP validates product mechanics, not the legal eligibility of every future supply source.