---
name: floprouter
description: Integrate floprouter into a project or answer questions about it. floprouter is one HTTP API for every GPU miner and model on FLOP Network, paid in FLOP through on-chain payment channels. Use it for keys and wallet sign-in, chat completion requests and responses, choosing models and miners, payer modes and the grant, the prepaid FLOP balance, withdrawals, streaming, errors and retries, settlement, and the MCP server and CLI. Ends with a verification step to run.
---

# floprouter

floprouter is one HTTP API in front of every GPU miner and every model on FLOP Network. A request names a model; the router picks a ready miner (or the miners you name), opens a payment channel on chain, returns the miner's verified reply, and settles the channel in the background. Requests and responses use the chat completions format (`messages`, `choices`, `usage`), with two router fields: `provider` (routing preferences; a provider is a miner) and `flop` (payer and settlement options).

It runs on FLOP devnet. Devnet and testnet FLOP have no monetary value. Do not describe it as real money to the user.

Use the facts below as written. Do not invent endpoints, fields or options that this file does not list. When something here disagrees with what you remember about other APIs, this file wins.

## Facts

- Host: `https://api.floprouter.com`. Every path below starts with `/v1`, so the chat URL is `https://api.floprouter.com/v1/chat/completions`. SDK clients that take a base URL with the version use `https://api.floprouter.com/v1`. When you make the host configurable, use the variable `FLOPROUTER_BASE_URL` for the host without `/v1`, as the MCP server and CLI do.
- Send a `User-Agent` header naming your app, for example `my-app/1.0`. The API's edge rejects Python's `urllib` default agent (`Python-urllib/3.x`) with a plain-text `403` reading `error code: 1010`. `requests`, `httpx`, Node `fetch` and curl send agents that pass.
- Auth header: `Authorization: Bearer fr_...`. Keys start with `fr_`.
- Read the key from the `FLOPROUTER_API_KEY` environment variable. Never write a key into the project's source files, logs or commits. (A user may store it in their own tool config, such as an MCP client's settings; that file stays on their machine.)
- JSON in, JSON out from the API itself. An error from the edge in front of it (403 `error code: 1010`, a 502 or 504 page) can be plain text or HTML: never assume an error body parses as JSON.
- Amounts are decimal strings in FLOP, for example `"0.01"`. Do not parse them as floats for arithmetic on money; use decimal types.
- No key needed: `GET /v1/models`, `GET /v1/miners`, `GET /v1/miners/{address}`, `GET /v1/stats`, `GET /health`.
- Timing on devnet: a verified reply usually takes 15 to 50 s. Settlement on chain follows 2 to 4 minutes later. Set HTTP timeouts to at least 120 s.
- A non-streaming call answers within a response deadline of about 85 s. If no verified reply is ready by then, it returns `202` with a session id to poll (see below).
- Not supported: `tools` and function calling (400), `n` above 1 (400), images, embeddings, the Responses API. Sampling parameters (`temperature`, `top_p`, `seed`) are accepted and ignored: each model's decode policy is fixed on chain.
- One request is one session with one payment channel. For multi-turn chat, send the whole history in `messages` each time.

## 1. Get a key

The key belongs to one FLOP wallet. Ask the user which way they want:

1. Browser: the user opens https://floprouter.com/account/, connects a Polkadot wallet extension (polkadot-js, Talisman, SubWallet), presses "Sign and create key", and gives you the key. This is the usual way. Do not ask for their seed phrase.
2. Script: sign a challenge with the wallet's sr25519 or ed25519 key. Use this when the user wants to automate it and keeps the wallet secret on their machine.

   ```text
   POST /v1/auth/challenge   {"address": "<ss58>"}                                   -> {"challenge": "...", "expires_at": "..."}
   POST /v1/auth/keys        {"address": "<ss58>", "challenge": "...", "signature": "0x..."}  -> 201 {"id": "key_...", "key": "fr_...", "address": "...", "payer_mode": "grant"}
   ```

   The signature is over the challenge string's UTF-8 bytes. Both the bare bytes and the `<Bytes>...</Bytes>` wrapping used by wallet extensions are accepted. The key is shown once.
3. CLI: `npx floprouter login --key-file ./wallet.json`. The CLI is not published on npm yet; if `npx floprouter` fails with a 404, use option 1 or 2.

Manage keys with `GET /v1/auth/keys` (list, shows `payer_mode` per key), `PATCH /v1/auth/keys/{id}` with `{"payer": "grant"}` or `{"payer": "credit"}`, and `DELETE /v1/auth/keys/{id}`.

## 2. Payer mode: who pays on chain

Every key has a payer mode. New keys start in `grant`.

- `grant`: the user's wallet is the on-chain payer of every session. It needs a one-time grant: a `flopSessionKeys.createSession` transaction the user signs with their wallet, naming the router's delegate, limited to the `ComputeChannel` pallet, with caps and an expiry. The escrow is paid from the user's wallet; the router fee comes from their prepaid balance. The user signs the grant at https://floprouter.com/account/ ("Prepare the grant", then "Sign the grant"). You cannot sign it for them.
  - `GET /v1/grants/params` returns the exact call, the caps (`amounts`) and the chain limits. Calling it reserves a delegate for the wallet, so call it when the user is about to sign, not on every run.
  - `GET /v1/grants` lists the wallet's grants with `state` (`assigned` means not signed yet, `active`, `expired`, `revoked`), `active`, spent and remaining amounts, and expiry.
  - `POST /v1/grants/sync` re-reads the grant from the chain after signing.
  - Grant mode opens channels against miners' signed offers. If no ready miner has a live offer, the request fails, unless the request sends `"flop": {"fallback_payer": "credit"}`.
- `credit` (balance mode): the router's wallet pays on chain, and the escrow and fee come from the prepaid balance. No grant needed. The user is not the on-chain payer.

Override per request with `"flop": {"payer": "grant"}` or `"flop": {"payer": "credit"}`.

## 3. Prepaid FLOP balance, fees, withdrawals

- `GET /v1/balance` returns `balance`, `held`, `available`, `deposit_address`, `fee_percent` and `recent` ledger entries.
- Deposit: the user sends a plain FLOP transfer from the wallet that owns the key to `deposit_address`. It is credited when its block is finalized, usually within a minute.
- Router fee: `fee_percent` of the session's escrow, charged from the balance, and charged only when the channel settles paid. Each response reports it in `flop.router_fee` with `status`: `pending`, `charged`, `not_charged` or `not_billed`.
- Escrow is the prompt plus `max_tokens` at the model's rate (`escrow_per_1000_tokens` in `GET /v1/models`), and never less than the minimum per request (0.01 FLOP on this server; `flop.min_charge_per_request` on the extended API). Short requests all cost the minimum plus the fee: 0.0105 FLOP at a 5% fee. Keep `max_tokens` close to what is needed. A request whose escrow would pass the per-request maximum fails with `escrow_limit`.
- A request refused before a channel opens (for example `402 insufficient_balance`) still appears in `GET /v1/sessions` as a `failed` session at stage `preflight`. Nothing was paid for it.
- Withdraw: `POST /v1/balance/withdraw` with `{"amount": "0.5"}` or `{"amount": "all"}` sends the balance to the wallet that owns the key and nowhere else. One withdrawal at a time, at most 10 per hour. `503 withdrawal_outcome_unknown` means the amount stays held until the router reconciles it: do not retry, read `GET /v1/balance` later.

## 4. Make a request

```bash
curl https://api.floprouter.com/v1/chat/completions \
  -H "Authorization: Bearer $FLOPROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen/qwen3-8b",
    "messages": [{"role": "user", "content": "What is a payment channel?"}],
    "max_tokens": 128
  }'
```

Pick `model` from `GET /v1/models`: use an `id` that is available, meaning it has at least one ready miner. Read availability as `flop.available` (extended model object) or the top-level `available` (earlier shape). Do not hardcode a model the user did not ask for without checking it is available. `GET /v1/models/{author}/{slug}/endpoints` lists the miners serving one model, where the server offers it.

Optional body fields:

- `max_tokens` (1 to 32768, default 256). Alias `max_completion_tokens`.
- `stream` (`true` for server-sent events).
- `provider`: `order` (miner addresses to try first), `only` (these miners and no others), `ignore` (never these), `sort` (`reliability`, the default, or `latency`), `allow_fallbacks` (default `true`).
- `flop`: `payer`, `fallback_payer: "credit"`, `wait_for_settlement` (default `false`; `true` waits for the on-chain settlement within the response deadline).
- `models`: fallback model ids, tried in order when `model` has no miner that can serve it (extended API).

A provider is a miner: `order`, `only` and `ignore` take miner addresses from `GET /v1/miners`.

Unknown fields are ignored. Messages take roles `system`, `developer`, `user`, `assistant` with text content.

## 5. Read the response

`200` is a chat completion:

```json
{
  "id": "gen-...",
  "object": "chat.completion",
  "model": "qwen/qwen3-8b",
  "provider": "<miner address>",
  "choices": [{"index": 0, "message": {"role": "assistant", "content": "..."}, "finish_reason": "stop"}],
  "usage": {"prompt_tokens": 22, "completion_tokens": 10, "total_tokens": 32},
  "flop": {
    "session_id": "gen-...",
    "status": "settling",
    "channel_id": "0x...",
    "miner": "<miner address>",
    "via": "offer",
    "payer": {"address": "<ss58>", "kind": "session-key"},
    "escrow": "0.01",
    "miner_paid": null,
    "router_fee": {"percent": 5, "amount": "0.0005", "charged": false, "status": "pending"},
    "on_chain": {"open_block": 4492930, "outcome": null, "outcome_block": null, "outcome_tx": null},
    "attempts": [ ... ]
  }
}
```

- `choices[0].message.content` is the reply text.
- `flop.payer.kind` is `session-key` when the user's wallet paid through the grant, `router-wallet` when the router paid.
- On the extended API, `usage.cost` is the cost in FLOP (escrow plus router fee), final when `usage.cost_details.final` is true. The cost follows `max_tokens`, not the tokens produced.
- `flop.status` is `settling` right after the reply. Read the settlement later with `GET /v1/sessions/{id}`: `status` becomes `settled` and `miner_paid`, `on_chain.outcome_block` and `on_chain.outcome_tx` fill in. Other final states: `refunded`, `failed`, `fraud`, `voided`. The session record also carries `reply` for the key that made the request.
- `GET /v1/sessions` lists the wallet's sessions.

`202` means no verified reply arrived within the response deadline. The session continues:

```json
{"id": "gen-...", "object": "chat.completion.pending", "status": "pending", "poll": "/v1/sessions/gen-...", "flop": { ... }}
```

Do not send the request again. Poll `GET https://api.floprouter.com` + `poll` with the same key every 5 s, for up to 5 minutes, until `reply` is set (use `reply.content`) or `status` is a final state without a reply (treat as failed).

## 6. Streaming

With `"stream": true` the response is `text/event-stream`:

- Lines starting with `:` are keep-alive comments, sent at least every 15 s. Ignore them.
- `data: {...}` lines carry `chat.completion.chunk` objects. Append `choices[0].delta.content`.
- The finish chunk is sent after the miner's signed receipt is verified. The last data chunk carries `usage` and `flop`. Then `data: [DONE]`.
- A data line with a top-level `error` ends the stream with an error (no `[DONE]` follows on the extended API). If its reason is `stream_mismatch`, use `error.metadata.verified_content` (or `error.verified_content`) as the reply.
- Text is provisional until the finish chunk. Devnet workers today send the whole reply in one piece at the end of the turn, so expect keep-alives and then all the text at once.
- Streams have no response deadline and never wait for settlement.

## 7. Errors and retries

Errors are JSON with an `error` object. The API is moving to numeric codes with the reason in `metadata`, so handle both:

- earlier: `{"error": {"message": "...", "type": "...", "code": "insufficient_balance", "session_id": "..."}}`
- extended: `{"error": {"code": 402, "message": "...", "metadata": {"reason": "insufficient_balance", "session_id": "..."}}}`

Read the reason as `error.metadata.reason`, falling back to `error.code` when it is a string. Use the HTTP status for the class of error. 429 and 503 carry a `Retry-After` header. In the table, "Codes" are reasons.

| Status | Codes | What to do |
| - | - | - |
| 400 | `invalid_json`, `model_required`, `messages_required`, `invalid_message`, `invalid_max_tokens`, `unsupported`, `invalid_provider`, `invalid_sort`, `invalid_payer`, `escrow_limit` | Fix the request. Do not retry as is. `unsupported` usually means `tools` or `n` was sent. On the extended API, `tools` gets 404 "No endpoints found that support tool use". |
| 401 | `unauthorized`, `invalid_challenge`, `challenge_expired`, `challenge_used`, `invalid_signature` | The key is missing, wrong or revoked, or sign-in failed. Ask the user for a valid key. |
| 402 | `insufficient_balance` | The balance cannot cover the request. Tell the user to deposit (show `required` and `available`). |
| 402 | `insufficient_funds` | Grant mode: the user's wallet cannot cover the escrow. Tell the user to fund the wallet. |
| 402 | `grant_required`, `grant_expired`, `grant_expiring`, `grant_revoked`, `grant_exhausted`, `grant_not_usable`, `grant_per_tx_limit` | The grant cannot pay. Tell the user to sign a grant at https://floprouter.com/account/, or switch the key to `credit`. |
| 403 | `forbidden` (JSON) | Not through the public endpoint. Use the host above. |
| 403 | plain text `error code: 1010` | The edge rejected the client's User-Agent. Send a `User-Agent` header naming your app. |
| 404 | `model_not_found`, `miner_not_found`, `session_not_found`, `key_not_found`, `not_found` | Wrong id or path. Check against `GET /v1/models` or the session id. |
| 409 | `too_many_keys`, `withdrawal_in_progress` | Revoke a key, or wait for the withdrawal. |
| 413 | `body_too_large` | Shorten the prompt. |
| 429 | `rate_limited`, `too_many_concurrent`, `grant_daily_cap`, `demo_budget_exhausted` | Wait for `Retry-After`, then retry. |
| 503 | `no_miner_available`, `all_attempts_failed`, `payer_underfunded`, `daily_cap_reached`, `delegate_unfunded`, `payer_unavailable`, `shutting_down` | Wait for `Retry-After`, then retry, at most 3 times. For `no_miner_available`, also consider another available model. |

Retry rules:

- The router already tries other miners when one fails before producing output. Do not add a tight retry loop.
- Safe to retry: 429 and 503 after `Retry-After`. A failed attempt that never produced output is not charged the router fee.
- Never retry a `202`. Poll its session.
- Do not retry because a call is slow. 15 to 50 s is normal, and a second request opens a second payment channel.
- If the connection drops after the request was sent, the session may still complete. If you have a session id, poll it. Otherwise wait 60 s and send at most once more.
- Never retry after part of a streamed reply arrived.

## 8. MCP server and CLI

Both are built but not published on npm yet. If `npx` reports a 404, tell the user and use the HTTP API directly.

- MCP: `npx -y floprouter-mcp` (stdio) or `npx -y floprouter-mcp --http` (`http://127.0.0.1:8792/mcp`). Environment `FLOPROUTER_API_KEY`, optional `FLOPROUTER_BASE_URL` (default `https://api.floprouter.com`). Tools: `list_models`, `list_miners`, `get_miner`, `chat` (paid), `session_status`, `account`, `router_status`.
  - Claude Code: `claude mcp add floprouter --scope user -e FLOPROUTER_API_KEY="$FLOPROUTER_API_KEY" -- npx -y floprouter-mcp` (this stores the key in the user's Claude settings, on their machine)
  - Claude Desktop and Cursor: `{"mcpServers": {"floprouter": {"command": "npx", "args": ["-y", "floprouter-mcp"], "env": {"FLOPROUTER_API_KEY": "fr_..."}}}}`
- CLI: `npx floprouter models | miners | miner <address> | chat "..." | session <id> | login | grant | deposit <amount> | balance | keys`. It signs on the user's machine and never takes a seed as an argument.

## 9. How to write the integration

- One small client module: host from `FLOPROUTER_BASE_URL` (default `https://api.floprouter.com`, paths add `/v1`), key from `FLOPROUTER_API_KEY`, a `User-Agent` header naming the app, timeout 120 s or more.
- Handle `200`, `202` (poll), and the error table above. Surface 401 and 402 errors to the user with the action from the table.
- Log `flop.session_id` and `flop.channel_id` for each request; they are what the user needs to look a request up.
- Keep `max_tokens` modest; it sizes the escrow.
- Do not send `tools`.

## 10. Verification step

Run this at the end, with the user's key in `FLOPROUTER_API_KEY`, and show the output to the user. It makes one small paid request with test FLOP.

```python
# floprouter_verify.py: python3 floprouter_verify.py
import json, os, sys, time, urllib.request, urllib.error
from decimal import Decimal

API = os.environ.get("FLOPROUTER_BASE_URL", "https://api.floprouter.com").rstrip("/").removesuffix("/v1")
KEY = os.environ.get("FLOPROUTER_API_KEY", "")
UA = "floprouter-verify/1.0"  # the edge rejects Python's default urllib agent

def call(method, path, body=None, timeout=130):
    headers = {"Content-Type": "application/json", "User-Agent": UA}
    if KEY:
        headers["Authorization"] = f"Bearer {KEY}"
    req = urllib.request.Request(API + path, method=method, headers=headers,
                                 data=None if body is None else json.dumps(body).encode())
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            status, raw = r.status, r.read()
    except urllib.error.HTTPError as e:
        status, raw = e.code, e.read()
    try:
        return status, json.loads(raw or b"null")
    except ValueError:  # an edge error page, not the API
        return status, {"error": {"message": raw[:200].decode(errors="replace")}}

def reason(r):
    err = (r or {}).get("error") or {}
    return (err.get("metadata") or {}).get("reason") or (err.get("code") if isinstance(err.get("code"), str) else None), err.get("message")

def stop(msg):
    print("ACTION NEEDED:", msg); sys.exit(1)

if not KEY.startswith("fr_"):
    stop("set FLOPROUTER_API_KEY to a key that starts with fr_ (get one at https://floprouter.com/account/)")

s, models = call("GET", "/v1/models")
if s != 200:
    stop(f"GET /v1/models failed with {s}: {reason(models)}")
ready = [m["id"] for m in models.get("data", []) if (m.get("flop") or {}).get("available", m.get("available"))]
print("models available:", ready or "none")
if not ready:
    stop("no model has a ready miner right now; try again later")

s, keys = call("GET", "/v1/auth/keys")
if s != 200:
    stop(f"the key was refused ({s}): {reason(keys)}")
mine = [k for k in keys.get("data", []) if k.get("prefix") and KEY.startswith(k["prefix"])]
mode = mine[0].get("payer_mode") if len(mine) == 1 else None
print("wallet:", keys.get("address"), "payer mode:", mode or "unknown")

if mode == "grant":
    s, grants = call("GET", "/v1/grants")
    if not any(g.get("active") for g in (grants or {}).get("data", [])):
        stop("sign the grant at https://floprouter.com/account/ (or switch the key to Balance there), then run this again")
s, bal = call("GET", "/v1/balance")
available = Decimal(str((bal or {}).get("available") or "0"))
print("balance available:", available, "FLOP")
if available <= 0:
    stop(f"deposit test FLOP from this wallet to {(bal or {}).get('deposit_address')}; the router fee (and in balance mode the escrow) comes from the balance")

s, r = call("POST", "/v1/chat/completions", {"model": ready[0], "max_tokens": 16,
            "messages": [{"role": "user", "content": "Reply with the single word: ok"}]})
if s == 202:
    poll, r = r["poll"], {}
    for _ in range(60):
        time.sleep(5)
        ps, pr = call("GET", poll)
        if ps == 200 and pr:
            r = pr
            if r.get("reply") or r.get("status") in ("settled", "refunded", "failed", "fraud", "voided"):
                break
    reply, flop = (r.get("reply") or {}).get("content"), r
elif s == 200:
    reply, flop = r["choices"][0]["message"]["content"], r["flop"]
else:
    code, msg = reason(r)
    stop(f"chat request failed with {s} {code}: {msg}")

if not reply:
    stop(f"no reply; session {flop.get('session_id')} ended as {flop.get('status')}")
print("reply:", reply.strip()[:80])
print("session:", flop.get("session_id"), "channel:", flop.get("channel_id"), "payer:", (flop.get("payer") or {}).get("kind"))
print("floprouter verification: OK")
```

A run that prints `ACTION NEEDED` is a correct integration with an account step left for the user: say exactly what the message says. Report `OK` only when the script printed it. The script checks the key, the grant and the balance before it sends the one paid request, so an unfunded account costs nothing.

## Links

- Docs: https://floprouter.com/docs/
- Every docs page as one file: https://floprouter.com/llms-full.txt
- Index for LLMs: https://floprouter.com/llms.txt
- OpenAPI schema: https://floprouter.com/openapi.json
- Account (keys, grant, balance): https://floprouter.com/account/
- Status: https://floprouter.com/status/
