# AGENTS.md — FarOut Integration Guide

Guidance for AI agents and developers calling FarOut pay-per-call LLM
inference. Everything here is live and requires no account.

## What FarOut is

FarOut is an x402 pay-per-call LLM gateway with **true-up (usage-based)
billing**. You POST a chat completion, the server answers HTTP 402 with a
payment requirement, your client pays USDC on Base, retries, and gets the
model response. No API key, no signup, no subscription. Settlement is
on-chain and happens after the answer.

- Base URL: `https://farouter.tech`
- Paid endpoint: `POST /v1/chat/completions` ([OI]-compatible)
- Anthropic alias: `POST /v1/messages`
- Catalog + live prices: `GET /v1/models`
- Manifest: `GET /.well-known/x402`
- Payments settle in USDC on **Base mainnet** (`eip155:8453`) or **Solana
  mainnet** (`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`, via the PayAI
  facilitator — network fees covered by PayAI). Pick whichever network your
  wallet lives on; the 402 `accepts` array lists both.

## True-up billing (how you are actually charged)

FarOut offers two payment schemes in every 402 — pick whichever your client
supports:

- **`upto` (recommended, true-up)**: the quote is a **spending cap you
  authorize, not the final price**. One gasless Permit2 signature; after the
  model answers, FarOut settles the ACTUAL usage (input + cached at 10% +
  output) — always <= the cap. Requires a one-time Permit2 allowance setup —
  **and FarOut sponsors the gas for it**: if your wallet holds exactly 0 ETH
  and you have settled at least one call (or have a `proofTx` USDC payment to
  FarOut), POST your wallet to `/api/sponsor-allowance` and FarOut drops the
  micro-ETH (0.000002) needed for the two one-time approvals. Details below.
- **`exact` (zero-setup fallback)**: sign an exact EIP-3009 transfer for the
  quoted amount. No allowance setup needed — works immediately with any
  wallet (e.g. Poncho). You pay the full quoted cap instead of true-up.

With `upto`:

1. The 402 carries an `upto` requirement — an upper bound computed from your
   estimated input tokens + `max_tokens` at the model's per-1M price.
2. You sign ONE Permit2 authorization for that cap (gasless, one signature).
3. The model answers. FarOut measures the ACTUAL usage from the response
   (input tokens, cached tokens at 10%, output tokens) and settles for the
   real cost — always <= the cap you authorized.
4. Whatever you didn't use is simply never taken. No refunds needed, no
   leftover spend. Check any tx on basescan.org: the settled amount is what
   left your wallet, nothing more.

Example: a request quoted (capped) at $0.005 that only uses a few hundred
tokens settles for the actual usage-based amount — often just the $0.001
minimum. Heavy requests that consume the full budget settle at the cap.
Either way you never pay more than the quote you saw in the 402.

- Minimum charge per successful call: $0.001.
- Per-call cap: $3.00 by default (the live value is in every 402 quote).
- Cached input reads are billed at 10% of the input price; repeated prompts
  with the same prefix get cheaper on later turns — automatically reflected
  in the settled amount.
- Failed upstream calls are cancelled automatically and never charged.

## Free gas sponsorship for the upto setup

The only cost of switching from `exact` to `upto` is the one-time Permit2
allowance setup (two approve txs from YOUR wallet, ~0.0000006 ETH gas on
Base — but you need a tiny bit of ETH to pay for them). FarOut sponsors
that for proven customers:

Eligibility (both required, verified live on-chain):

1. You are a paying customer — either:
   - one settled FarOut call (any scheme), **or**
   - `proofTx`: the tx hash of ANY USDC transfer from your wallet to the
     FarOut wallet (`0x8e3c...2371e`) — e.g. your `transferWithAuthorization`
     settlement, or a plain USDC transfer.
2. Your wallet holds **exactly 0 ETH**. If the wallet has any ETH at all
   (even dust like 0.000001), it can fund its own approvals and the request
   is rejected.

If eligible, POST your wallet:

```sh
curl -X POST https://farouter.tech/api/sponsor-allowance \
  -H "Content-Type: application/json" \
  -d '{"wallet":"0xYourWallet","proofTx":"0xOptionalTxHashOfYourUsdcPaymentToFarOut"}'
```

3. FarOut sends 0.000002 ETH to your wallet (one drop per wallet, ever —
   3x the real gas cost of the approvals).
4. From your own wallet, run the two approvals (any tool you like — the
   setup is yours, FarOut never touches your keys):
   - `USDC.approve(Permit2, max)`
   - `permit2.approve(USDC, x402UptoPermit2Proxy 0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002, max)`
5. Done — every subsequent `upto` call is gasless with true-up billing.

Example approve script (viem): see the setup section of the quick start.

## The payment flow

1. POST your request without any Authorization header.
2. Read the 402 response. The body carries a `quote` (the cap: USD, token
   estimate, per-1M prices). The `payment-required` response header carries
   the base64 x402 v2 requirements (`accepts`, scheme `upto`).
3. Build the payment with any x402 client and retry the same request with
   the payment header. Official SDKs send `PAYMENT-SIGNATURE`; FarOut also
   accepts `PAYMENT` and `X-PAYMENT`.
4. On success you get 200 plus a `payment-response` header with the on-chain
   settlement receipt (tx hash). The settled amount is based on actual usage
   (true-up), not the cap.

## Quick start (JavaScript)

```js
import { wrapFetchWithPayment, x402Client } from "@x402/fetch";
import { UptoEvmScheme } from "@x402/evm/upto/client";
import { toClientEvmSigner } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.BUYER_PK);
const signer = toClientEvmSigner(account);
const client = new x402Client().register("eip155:8453", new UptoEvmScheme(signer));
const fetchWithPay = wrapFetchWithPayment(fetch, client);

const r = await fetchWithPay("https://farouter.tech/v1/chat/completions", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "glm-5.3",
    messages: [{ role: "user", content: "hi" }],
    max_tokens: 50,
  }),
});
const answer = await r.json();
```

Requires `npm install @x402/fetch @x402/evm viem`. The buyer wallet needs a
little USDC on Base. Signing is gasless (Permit2); the wallet only needs gas
ETH for the one-time Permit2 approval setup (`USDC.approve(permit2)` then
`permit2.approve(upto proxy)`), after which every call is gasless.

## Request fields

| Field | Required | Notes |
|---|---|---|
| `model` | yes | Id from `GET /v1/models`, e.g. `glm-5.3`. No provider prefix. |
| `messages` | yes | Standard `[{role, content}]` array. |
| `max_tokens` | yes | Output budget. Drives the quote cap. `gpt-5.x` models require `max_completion_tokens` instead. |
| `stream` | no | `true` for SSE. Settlement happens after the stream ends. |

## Response codes

| Code | Meaning | What to do |
|---|---|---|
| 402 | Quote ready | Pay (upto cap) and retry with the payment header. |
| 200 | Paid and answered | Read the answer. Keep the `payment-response` receipt. |
| 400 | Payment mismatch | Fetch a fresh 402 (quotes are per request) and retry. |
| 404 | Unknown model | Check `GET /v1/models` for the current catalog. |
| 502 | Upstream failed | Not charged. Retry, possibly with another model. |

## Model selection notes

- Model ids carry no provider prefix (`glm-5.3`, not `cb/glm-5.3`).
- `deepseek-v4-flash`, `glm-5.3-flash`, and `gpt-5.6-luna` are the cheapest
  entry points. `gpt-5.5` and `gpt-5.6-sol` are the flagship tier. Prices
  and health are live at `/v1/models` and `/api/status`.
- The catalog is a curated set of 10 frontier models.

## Rules of thumb

- Quote first when cost matters: POST once without paying, read `quote.usd`
  (the cap), decide, then pay and retry. The unpaid probe is free.
- Your real cost is almost always BELOW the quote: the quote is a worst-case
  cap, and true-up settles at actual usage.
- One payment header per request. If your client throws "payment already
  attempted", rebuild the request from scratch with a fresh payload.
- Health dots on the site and `/api/status` reflect real probe calls every
  minute. `rate_limited` means an upstream bid squeeze, not an outage;
  retry or switch models.
- Per-call costs land in your wallet history on Base (basescan.org).

## Paying from Solana (exact scheme, zero setup)

If your wallet is on Solana instead of Base, pick the `exact` accept with
network `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` from the 402 challenge:

```js
// npm i @x402/fetch @x402/svm @solana/web3.js
import { createKeyPairSignerFromBytes } from "@solana/web3.js";
import { registerExactSvmScheme } from "@x402/svm/exact/client";
import { x402Client } from "@x402/core/client";
import { wrapFetchWithPayment } from "@x402/fetch";

// keypairBytes: 64-byte Uint8Array (seed + pubkey), standard Solana layout
const signer = await createKeyPairSignerFromBytes(keypairBytes);
const client = new x402Client();
registerExactSvmScheme(client, { signer });
const fetchWithPay = wrapFetchWithPayment(fetch, client);

const res = await fetchWithPay("https://farouter.tech/v1/chat/completions", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ model: "kimi-k3", messages: [{ role: "user", content: "hi" }] }),
});
```

- USDC (SPL) on Solana mainnet: `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`
- The PayAI facilitator submits and pays the network fee — your wallet only
  needs USDC, no SOL required (same zero-gas experience as Base exact).
- Solana is `exact` only (no true-up): you pay the quoted flat price, which is
  the worst-case cap. For true-up savings use Base `upto`.

## Verification checklist for your integration

- [ ] Unpaid POST returns 402 with a `quote` in the body (scheme `upto`).
- [ ] Paid POST returns 200 with model content.
- [ ] `payment-response` header contains a tx hash that resolves on
      basescan.org, and the transferred amount is <= the quoted cap
      (true-up billing).
- [ ] `GET /v1/models` lists the models you use.
