# Credit System

Credits are managed by the `ZDriveXCreditsV2` smart contract on Base, deployed as a UUPS upgradeable proxy. You purchase credits by sending USDC to the contract. Each successful inference call consumes one credit, deducted asynchronously after the response is streamed.

Credits do not expire. They are stored on-chain and readable by anyone via the contract's public `credits(address)` function.

## Credit flow

```mermaid
flowchart LR
    subgraph Purchase
        U[User] -->|"USDC on Base"| C["ZDriveXCreditsV2\nSmart Contract"]
        C -->|"credits[wallet]++"| BAL[On-chain balance]
    end

    subgraph Inference
        BAL -->|"Worker reads balance\n(viem + RPC fallback)"| W[CF Worker]
        W -->|"credits > 0 → Paid tier"| INF[TEE Inference]
        INF -->|"Success"| CONSUME["consumeCredit(wallet)\nasync"]
        CONSUME -->|"credits[wallet]--"| BAL
    end
```

## RPC resilience

The worker reads balances via a viem fallback transport across multiple Base RPC providers to avoid single-provider outages. If all providers fail during a credit check, the request returns 503 — the worker fails closed rather than serving inference to a user whose balance cannot be verified.

## consumeCredit behaviour

Credit deduction happens **after** a successful inference response, not before. This means:

* Failed or errored inference calls do not cost credits
* If `consumeCredit()` fails transiently, the worker retries automatically before giving up

## Contract interface

```solidity
function credits(address user) external view returns (uint256);
function consumeCredit(address user) external;
```

Only the operator address (the CF Worker's signing key) can call `consumeCredit`. The `credits` view function is public and can be queried by anyone to verify a user's balance.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.zdrive.io/architecture/credits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
