> ## 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 API

> Route table, authentication, 402 payment challenges, receipts, and fail-closed behavior of the giwa-gateway binary and its x402 adapter.

The gateway is a Rust service on axum, bound to whatever address `GIWA_GATEWAY_BIND_ADDR` names (port 8788 in the shipped topologies). The x402 Stage B payment path is proven on the local localnet topology; the public GIWA Sepolia topology exists in the repository with `GIWA_TEST_PROVIDER` disabled and has no public URL yet ([Live Evidence](/overview/live-evidence)).

## Route table

| Route                         | Method | Auth                                     | Semantics                                                                                                                                                                         |
| ----------------------------- | ------ | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/`                           | GET    | None                                     | Empty 200. A reachability probe: Claude Code pings its configured origin before the first Messages request. Not an identity or discovery endpoint                                 |
| `/healthz`                    | GET    | None                                     | Liveness. Returns `{"status":"ok","product":…}`                                                                                                                                   |
| `/v1/models`                  | GET    | `tok_` API key                           | Lists the local-fixture model catalog in OpenAI list shape. Small by design: it exists so native clients (Codex) can discover their configured model, not as a production catalog |
| `/v1/models/:model`           | GET    | `tok_` API key                           | Retrieves one model object; only the local native model ID resolves                                                                                                               |
| `/v1/chat/completions`        | POST   | `tok_` API key + access (credit or x402) | OpenAI Chat Completions compatible inference                                                                                                                                      |
| `/v1/responses`               | POST   | `tok_` API key + access (credit or x402) | OpenAI Responses API (Codex native protocol)                                                                                                                                      |
| `/v1/messages`                | POST   | `tok_` API key + access (credit or x402) | Anthropic Messages API (Claude Code native protocol)                                                                                                                              |
| `/v1/messages/count_tokens`   | POST   | `tok_` API key                           | Anthropic token-count endpoint                                                                                                                                                    |
| `/v1/receipts/:request_id`    | GET    | `tok_` API key                           | Returns the issued UsageReceiptV1 envelope for one request. Scoped to the presenting key: another key's request ID is not served, and a malformed ID is rejected                  |
| `/v1/test-provider/responses` | POST   | `tok_` API key                           | Deterministic test provider, present only when `GIWA_TEST_PROVIDER=enabled` (local localnet). Disabled in the GIWA Sepolia topology                                               |

## Authentication and access

Callers authenticate with bearer API keys carrying the `tok_` prefix. Keys are never compared in plaintext: the gateway digests the presented key and authenticates the digest against the store.

Inference routes then compose access in exactly one of two modes, selected per request by the `x-giwa-payment-mode` header:

* **Credit** (Stage A): prepaid balance topped up by ERC-3009 `exact` transfers. This is what an absent header, or `x-giwa-payment-mode: credit`, selects, and it stays the mode even when an x402 configuration is sealed. The `exact` settlement primitive is proven once on public GIWA Sepolia (tx [`0xad1a2f7b…`](https://sepolia-explorer.giwa.io/tx/0xad1a2f7b5aff4033e7779437ec487e8b51eb8170ba1c6c8cc971f6de37fcb9f8)); see [x402 Stage A: Credit Top-Up](/gateway/x402-stage-a).
* **X402** (Stage B): per-request `upto` Permit2 settlement, reached only by `x-giwa-payment-mode: x402`. If no x402 configuration is sealed, that header returns 404 rather than falling back to credit. Proven on the local localnet topology, including fault recovery; see [x402 Stage B: Per-Request Settlement](/gateway/x402-stage-b).

The opt-in is deliberately one-way. A `payment-signature` header presented without the x402 mode header is rejected as an invalid request, so a payment signature can never silently change the authority of a normal SDK request. Any other value of `x-giwa-payment-mode`, an empty value, or a repeated header is rejected the same way.

## The 402 response

When x402 access applies and the request carries no valid `payment-signature` header, the gateway answers `402 Payment Required`. The challenge travels base64-encoded in the `payment-required` response header:

```json theme={null}
{
  "x402Version": 2,
  "resource": { "url": "…", "description": "…", "mimeType": "application/json" },
  "accepts": [
    {
      "scheme": "upto",
      "network": "eip155:91342",
      "amount": "<body-aware maximum>",
      "payTo": "0x…",
      "maxTimeoutSeconds": 60,
      "asset": "0x…",
      "extra": {
        "assetTransferMethod": "permit2",
        "name": "Tokscale Test USD",
        "version": "1",
        "facilitatorAddress": "0x…",
        "giwaBindingVersion": 1,
        "giwaBindingDigest": "…",
        "giwaProjectId": "…",
        "giwaApiKeyId": "…",
        "giwaProtocol": "openai-chat",
        "giwaCanonicalRoute": "/v1/chat/completions",
        "giwaRequestId": "…",
        "giwaRequestFingerprint": "…",
        "giwaExpiresAtUnixSeconds": "…",
        "giwaAuthorizationNonce": "…"
      }
    }
  ],
  "extensions": {}
}
```

`maxTimeoutSeconds` and `giwaBindingVersion` are JSON numbers, not quoted strings; the configured timeout must sit between 30 and 300 seconds. The quote is body-aware: the maximum amount is a conservative bound computed from the actual request body (it grows with each additional message), so one-message requests prove the exact boundary and multi-message requests settle for less than the maximum. The `extra.giwa*` fields bind the quote immutably to the project, API key, protocol, route, request fingerprint, price maximum, and expiry; the Permit2 nonce is derived from that binding digest, so a signature cannot be rewrapped for a different request.

A 402 is side-effect free: no ledger row, no intent, no settlement attempt. The challenge expiry travels back inside the client's signed `payment-signature`, so a retry after the wall clock moves cannot silently shift the Permit2 nonce.

## Receipts endpoint

`GET /v1/receipts/:request_id` returns the EIP-712 signed UsageReceiptV1 envelope the gateway issued for a completed request. It is authenticated and ownership-scoped: the presenting `tok_` key must own the request. This is the raw material for independent verification (see [Verifying a Receipt](/builder-passport/verify-a-receipt) and [UsageReceiptV1](/gateway/usage-receipt-v1)).

## Error and fail-closed behavior

The payment boundary fails closed. The x402 client boundary has exactly five error categories: invalid adapter configuration, invalid payment, adapter unavailable, adapter rejected, and invariant violation (the adapter returned evidence that does not check out). An unavailable or rejecting adapter produces no settlement and no served inference. Settlement evidence is re-verified after broadcast: the settled payer and amount must match the admitted request, and a mismatched or unmined settlement is not accepted as paid. The recovery path is read-only by construction: `/v1/recover` can only confirm a transaction hash already durably associated with a request, and can never ask the adapter to broadcast.

## The x402 adapter (port 8090)

Stage B payment authority is isolated in a separate process, bound to port 8090 on the internal network. The gateway reaches it over a narrow authenticated API with a shared bearer token; the adapter never sees database credentials and the gateway never holds payment broadcast authority.

| Route         | Method | Auth         | Semantics                                                                                         |
| ------------- | ------ | ------------ | ------------------------------------------------------------------------------------------------- |
| `/healthz`    | GET    | None         | Liveness probe used by the Compose healthcheck                                                    |
| `/v1/verify`  | POST   | Bearer token | Validates a complete payment authorization against route facts without broadcasting               |
| `/v1/settle`  | POST   | Bearer token | Broadcasts one settlement for one admitted authorization. One authorization, one settlement, ever |
| `/v1/recover` | POST   | Bearer token | Read-only confirmation of a transaction hash already associated with a request. Cannot broadcast  |

<Info>
  GIWA does not officially support x402. The facilitator (`ghcr.io/x402-rs/x402-facilitator@sha256:89ab5c03…`), the Permit2 proxies, and the ERC-6492 validator were deployed and pinned by Tokscale. The adapter and its routes are our port, not a GIWA builtin. Addresses: [The Public Chain](/gateway/public-chain).
</Info>

## Next steps

* For the service internals behind these routes, see [The Gateway and Its Workers](/gateway/service).
* To point a real client at them, see [Client Integration](/gateway/client-integration).
* For the receipt envelope the receipts endpoint returns, see [UsageReceiptV1](/gateway/usage-receipt-v1).
* For the processes these routes run inside, see [Gateway Overview](/gateway/overview).
