> ## Documentation Index
> Fetch the complete documentation index at: https://docs.giwa.tokscale.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Gateway Overview

> The processes behind the gateway, how one paid request moves through them, and which stages are proven on the public chain versus locally.

<img src="https://mintcdn.com/tokscale-giwa/PZ-qe7GbREC4q3PR/public/assets/gateway.png?fit=max&auto=format&n=PZ-qe7GbREC4q3PR&q=85&s=ea1f61744feea8a0e1cfc1345b96ecad" alt="Bridge" style={{display:'block',margin:'0 auto 2.5rem',width:'100%',maxWidth:'700px',borderRadius:'12px'}} width="1280" height="720" data-path="public/assets/gateway.png" />

Tokscale is a small set of single-authority processes around one PostgreSQL database. Each process holds exactly one database role with a fenced SQL contract, so no component can reach a table it does not own.

Three axes run through everything below, and keeping them apart is the central design choice: payment authorization, the usage receipt, and the epoch attestation are independent, so a failure on one axis never corrupts another.

```mermaid theme={null}
flowchart LR
    subgraph clients["Clients"]
        SDK["AI SDKs<br/>Codex, Claude Code"]
        Browser["Browser console"]
    end

    subgraph app["Application plane"]
        Web["web console<br/>Next.js"]
        GW["gateway<br/>Rust"]
        PG[("postgres<br/>append-only ledger<br/>least-privilege roles")]
        Redis[("redis")]
        RI["receipt issuer"]
        AW["attestation publisher"]
        RC["top-up reconciler"]
        RT["terminal retention"]
        XA["x402 adapter"]
    end

    subgraph chain["Chain plane"]
        FAC["x402 facilitator<br/>pinned image"]
        Anvil["anvil localnet<br/>(or GIWA Sepolia RPC)"]
    end

    SDK -->|"tok_ API key"| GW
    Browser --> Web
    Web --> PG
    Web --> Redis
    GW --> PG
    GW -->|"verify, settle, recover"| XA
    XA --> FAC
    XA --> Anvil
    FAC --> Anvil
    RC --> PG
    RC --> Anvil
    RI --> PG
    RT --> PG
    AW --> PG
    AW -->|"one EAS tx per epoch"| Anvil
```

## The components

* **web console**: the Next.js app, and the only local service published to the host. Sessions, project and key management, top-up flows, and console read models. It never joins the private chain network; its only chain reads go through a bounded method allowlist.
* **gateway**: the Rust service, default bind `127.0.0.1:8788`. Authenticates `tok_` keys, enforces per-project policy, admits credit or x402 payment, dispatches to the model provider, settles, and serves issued receipts. See [The Gateway and Its Workers](/gateway/service).
* **x402 adapter**: an isolated process on port 8090, and the only component that talks to the facilitator, the chain RPC, and the append-only settlement journal. A framework version mismatch forces the boundary, and the seam is a bearer-authenticated local JSON interface. See [x402 Payments on GIWA](/gateway/x402-payments).
* **facilitator**: a digest-pinned `x402-rs` image that verifies and broadcasts x402 settlements for `eip155:91342`. Self-hosted because Coinbase's hosted facilitator does not support GIWA.
* **postgres**: the system of record. Migrations are checksum-pinned, the database is bound once and immutably to a deployment identity, and the request ledger is append-only: a `BEFORE UPDATE OR DELETE` trigger raises `giwa request ledger is append-only` on any mutation. Ten least-privilege roles replace any shared superuser at runtime.
* **redis**: session and console cache. No financial state.
* **workers**: the receipt issuer, the top-up reconciler, the attestation publisher, and the terminal-retention poller. Each is a bounded one-shot process, polled rather than long-running. See [The Gateway and Its Workers](/gateway/service).
* **the chain**: locally a disposable Anvil chain that borrows chain ID 91342 with a fixed genesis timestamp; in the production-shaped topology, real GIWA Sepolia. Chain ID is not a network identity here. See [Network Separation](/gateway/network-separation).

## How one paid request moves through it

Five durable stages, each of which either completes or leaves a recoverable record.

<Steps>
  <Step title="Authenticate and admit">
    The client calls a native route with an `Authorization: Bearer tok_…` key:

    ```http theme={null}
    POST /v1/chat/completions
    Authorization: Bearer tok_your_project_key
    ```

    The gateway resolves the key to a project, pins the active policy decision (model allowlist, lifetime spend cap), and checks payment. A prepaid-credit request takes a conservative maximum admission under a per-project PostgreSQL session lease. An x402 request without a signature gets a `402` with a body-aware maximum quote, then retries with a signed `PAYMENT-SIGNATURE` header; the adapter verifies it against the facilitator before any intent exists.
  </Step>

  <Step title="Dispatch to the provider">
    A durable request intent and outbox row are written in one transaction. Provider dispatch is idempotent on the payment identifier, so a retry cannot cause a second provider call.
  </Step>

  <Step title="Settle actual usage">
    When the terminal artifact is in hand, usage is priced against the same pricing snapshot bound at admission. Credits settle exact-decimal, never above the admission. x402 `upto` settles the actual amount, never above the signed maximum, through the adapter, the facilitator, and the canonical Upto Permit2 proxy on-chain. A client disconnect does not strand settlement: a background commit task finishes it out of band.
  </Step>

  <Step title="Write the ledger row and issue the receipt">
    The outcome lands as one immutable row in the request ledger. The receipt issuer, a separate least-privilege worker, signs an EIP-712 `UsageReceiptV1`. The client retrieves it:

    ```http theme={null}
    GET /v1/receipts/:request_id
    ```

    For detailed instructions, see [UsageReceiptV1](/gateway/usage-receipt-v1).
  </Step>

  <Step title="Anchor the epoch attestation">
    The attestation publisher collects sealed receipts for an epoch, builds the epoch Merkle tree under the V1 merkle domain separators, and publishes exactly one EAS transaction carrying the epoch summary commitment. Cost per epoch is constant in request count. For detailed instructions, see [Receipt Attestation](/gateway/receipt-attestation).
  </Step>
</Steps>

## Which stages are proven where

Stages 1 through 4 run end to end on the local localnet today. Stage 1's Stage A `exact` settlement is additionally proven once on public GIWA Sepolia (tx [`0xad1a2f7b…fcb9f8`](https://sepolia-explorer.giwa.io/tx/0xad1a2f7b5aff4033e7779437ec487e8b51eb8170ba1c6c8cc971f6de37fcb9f8), 1.0 tUSD, replay-rejected on retry). Stage 5 is proven against the local EAS fixture only; anchoring the first public Usage Root on Sepolia is still ahead of us. [Live Evidence](/overview/live-evidence) is the authoritative split.

The local evidence is local on purpose. The topology borrows the GIWA Sepolia chain ID so the V1 wire format stays byte-identical to the public chain, which means chain ID cannot be the safety boundary: identity comes from `GIWA_NETWORK` plus an immutable database binding, and a local artifact never earns a Sepolia explorer link. See [Network Separation](/gateway/network-separation).

## What the end-to-end harness adds

<Info>
  The harness results below are maintainer-run. The gateway stack and its harness are not publicly available, so they are attributed evidence rather than reader instructions. The shipped client surface is the open-source CLI (see [Quickstart: Track Your Usage](/usage-tracker/quickstart)).
</Info>

One full pass wraps the five stages above in the things a real session needs and a real auditor would ask for:

* **Wallet sign-in.** A deterministic Anvil account completes Sign-In with Ethereum against the console. See [Dual Identity](/builder-passport/dual-identity).
* **A credit top-up before any request.** The account receives a durable `402` quote, mints test-only tUSD, and signs a real EIP-3009 authorization. The facilitator settles it, and the reconciler independently observes the calldata and events before recording exactly one credit. See [x402 Stage A](/gateway/x402-stage-a).
* **Credential-free browser verification.** A Playwright container with no session, API key, wallet key, database URL, or server secret receives only a holder-disclosable handoff. It verifies the receipt, loads the Passport proof, and writes sealed artifacts, which the outer harness then re-verifies read-only.

Two markers report the outcome:

```text theme={null}
GIWA_BROWSER_ARTIFACTS verified=receipt,passport,transactions
GIWA_LOCAL_E2E_OK
```

`GIWA_LOCAL_E2E_OK` is the authoritative local proof marker. It is emitted only after the integration journey, the browser artifact verification, the chain-restart check, and the tamper-negative checks all pass, so a pass that skips or fails any of those does not print it. `GIWA_BROWSER_ARTIFACTS` names which sealed artifacts were re-verified.

## Topologies

The default stack is sealed: only the console port reaches the host, and every key inside it is a publicly known Anvil development key valid nowhere else.

* **Sealed localnet**, the default: the full hermetic proof, with least-privilege database roles, checksum-pinned migrations, the deployment-identity binding, Anvil at chain ID 91342 with persisted state, the facilitator, the adapter, the gateway, the workers, and the console. The gateway stays on the internal network.
* **Production-shaped**: the console and gateway against real GIWA Sepolia, with the test provider disabled, every secret a required variable, and no Anvil or facilitator inside. This is a topology definition; no public deployment is running.
* **Fault injection**: two overlays that inject real failures. One slows the reconciler so it can be killed after a real EIP-3009 settlement but before observation, proving exactly-one crediting after restart. The other puts the adapter behind a one-shot response-loss proxy, proving single-settlement recovery.

## Evidence

The whole lifecycle, including the browser checks, runs under one harness target, pinned to a fixed buildx builder so image builds resolve identically on every pass:

```sh theme={null}
BUILDX_BUILDER=desktop-linux bun run local:e2e
# pass marker: GIWA_LOCAL_E2E_OK
```

A second target kills the reconciler after a real settlement and proves it credits exactly once on restart:

```sh theme={null}
bun run local:stage-a:crash:e2e
# pass marker: GIWA_LOCAL_STAGE_A_CRASH_E2E_OK
```

A third drops the adapter's settle response after a real on-chain settlement and proves read-only recovery:

```sh theme={null}
bun run local:x402:fault:e2e
# pass marker: GIWA_LOCAL_X402_FAULT_E2E_OK
```

## Next steps

* For the service and the five worker processes in detail, see [The Gateway and Its Workers](/gateway/service).
* For how payment authorization works on both axes, see [x402 Payments on GIWA](/gateway/x402-payments).
* For the full index of targets and pass markers, see [Verification Log](/gateway/verification-log).
* For the authoritative public-versus-local accounting, see [Live Evidence](/overview/live-evidence).
