Inference

Agents buy answers from Claude, GPT, Gemini, Grok, DeepSeek, Kimi and GLM by the call, paid in USDG on Robinhood Chain over x402, with a signed receipt for every answer.

An agent with a wallet buys a model's answer at one address and pays for it in USDG on Robinhood Chain. There is no account and no API key. Each call costs the tokens it used at the model's list price plus a fixed 0.01 USDG, and every answer comes with a receipt BrainChain signs.

Base URL https://inference.usebrainchain.com/v1
Payment USDG on Robinhood Chain (eip155:4663), x402 upto scheme through Permit2
Models and prices GET /v1/models

The model you name gives the answer, with no hiring or grading by BrainChain. To have BrainChain hire a model for the work and grade the reply, use the OpenAI-compatible API.

Models and prices

GET /v1/models lists every model with the model that answers (upstream) and its price: inputPerMillion and outputPerMillion, USDG per million tokens as decimal strings, and perCall, the amount added to each call. The inference page shows the same list and prices a call for you.

A model that runs in an enclave also has attestation: the address where the enclave publishes its attestation report, a statement signed by the hardware about the code it runs. A buyer can check it before paying. Models served by Phala carry one, and the inference page links it next to the model. Their answers also carry a receipt signed inside Phala's gateway enclave: see Enclave receipts. Those that take end-to-end encrypted calls also carry sealed: true: see Sealed calls.

A call is charged the tokens the answer used, rounded up to a millionth of a USDG, plus perCall.

Pay for a call

The paying wallet holds USDG on Robinhood Chain and has approved Permit2 (0x000000000022D473030F116dDEE9F6B43aC78BA3) to spend it, as on the agents page. The approval is the only transaction the wallet sends, so it needs a little ETH on Robinhood Chain once. After it, every payment is a signature and needs no gas. A wallet without USDG or without the approval gets a 402 whose error names what is missing.

  1. Send the chat request without payment. The reply is 402 (payment_required) with a PAYMENT-REQUIRED header that states the ceiling, the most this call can cost.
  2. Sign for the ceiling and send the same request again with a PAYMENT-SIGNATURE header.
  3. The answer returns with an X-BrainChain-Receipt header and a PAYMENT-RESPONSE header that names the settlement transaction. The charge is what the answer used and never more than the ceiling.
npm install viem @x402/core @x402/evm

Save this as client.mjs and run it with PAYER_KEY=0x... node client.mjs:

import { decodePaymentRequiredHeader, decodePaymentResponseHeader, encodePaymentSignatureHeader } from "@x402/core/http";
import { toClientEvmSigner } from "@x402/evm";
import { UptoEvmScheme } from "@x402/evm/upto/client";
import { createPublicClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";

const URL = "https://inference.usebrainchain.com/v1/chat/completions";
const account = privateKeyToAccount(process.env.PAYER_KEY);
const chain = createPublicClient({ transport: http("https://rpc.mainnet.chain.robinhood.com") });
const body = JSON.stringify({ model: "deepseek", messages: [{ role: "user", content: "Name one prime number above 100." }] });

// The first reply is the price: the most this call can cost, and where the payment goes.
const quote = await fetch(URL, { method: "POST", body });
const required = decodePaymentRequiredHeader(quote.headers.get("payment-required"));
const terms = required.accepts[0];
console.log(`ceiling ${Number(terms.amount) / 1e6} USDG`);

// Sign for the ceiling and send the same request again.
const payment = await new UptoEvmScheme(toClientEvmSigner(account, chain)).createPaymentPayload(2, terms);
const paid = await fetch(URL, { method: "POST", body, headers: { "payment-signature": encodePaymentSignatureHeader({ ...payment, accepted: terms, resource: required.resource }) } });
if (!paid.ok) throw new Error(`${paid.status} ${await paid.text()}`);

// Kept as bytes: the receipts cover the answer's exact bytes.
const bytes = new Uint8Array(await paid.arrayBuffer());
const answer = JSON.parse(new TextDecoder().decode(bytes));
const receipt = JSON.parse(Buffer.from(paid.headers.get("x-brainchain-receipt"), "base64").toString());
const settled = decodePaymentResponseHeader(paid.headers.get("payment-response"));
console.log(answer.choices[0].message.content);
console.log(`charged ${Number(receipt.price) / 1e6} USDG in ${settled.transaction}`);

The ceiling counts one input token for each byte of the request body and the longest answer the request allows. Send max_tokens to lower it.

Each request needs its own authorization, and a wallet is answered one request at a time. To run calls side by side, pay from several wallets.

What a request carries

A request is OpenAI's chat completions body with model, messages and, when wanted, max_tokens (or max_completion_tokens), temperature, top_p, stop, seed, presence_penalty, frequency_penalty and user. Message content is a string or a list of text parts. Any other field gets a 400 that names it, response_format included.

Streaming, images and tool calls get a 400 before any payment is asked for. A body is at most 200 kB, and one request can cost at most 1 USDG. An answer is at most 8,192 tokens, and a larger max_tokens is lowered to that.

The receipt

X-BrainChain-Receipt is base64 of a JSON object:

Field Meaning
v The receipt version, 1
request, response keccak256 of the request body as sent and of the answer body as returned
model, upstream The id asked for and the model that answered
tokensIn, tokensOut The tokens the model reported for the request and the answer
price, fee Everything charged, in millionths of a USDG, and the per-call amount inside it
absorbed, judged "0" and null
asset, network USDG's address and eip155:4663
payer, nonce The paying address and the Permit2 nonce of its authorization
at When the receipt was signed, UTC
signer, signature BrainChain's key for this service and its signature

BrainChain signs receipts with 0x70D882879E1954Ac9A06b693379334Fd131B786D. The signature is an EIP-191 message over keccak256 of the receipt's JSON without signature, with the keys in the order above.

Check a receipt

With receipt and bytes from the client above, or a receipt from a day's list and the answer you kept, in an ES module (.mjs):

import { keccak256, recoverMessageAddress, stringToBytes } from "viem";

const SIGNER = "0x70D882879E1954Ac9A06b693379334Fd131B786D";
// `receipt` as parsed from the header, which keeps the signed key order.
const { signature, ...fields } = receipt;
const hash = keccak256(stringToBytes(JSON.stringify(fields)));
const signer = await recoverMessageAddress({ message: { raw: hash }, signature });
if (signer !== SIGNER) throw new Error(`signed by ${signer}, not by BrainChain`);
// `response` is keccak256 of the answer's bytes as received, so the check needs those bytes, not the parsed JSON.
if (keccak256(bytes) !== receipt.response) throw new Error("this receipt is for another answer");
console.log("signed by BrainChain, for this answer");

GET /v1/receipts/<YYYY-MM-DD> returns one UTC day: day, signer, count, receipts and root, the Merkle root over them (null for a day without receipts). unreadable counts lines of the day's record that could not be read and are in neither the list nor the root; it is normally 0.

The leaves are the hashes the receipts are signed over (keccak256 of each receipt's JSON without signature), in the order listed. Two hashes are joined smaller first and hashed with keccak256, as OpenZeppelin's MerkleProof checks, and an unpaired hash moves up unchanged.

After a day closes, its root is recorded on BrainChain (chain 274663, RPC https://rpc.usebrainchain.com), so a receipt can be shown to belong to its day. BrainChain's operator 0x70C665780E43BA1496a4E691e408F24844dB58eC calls the Inscriptions contract 0x770D6756CA8a1627FFf01B846383b13d6fa0c514, which emits Inscribed(address by, string kind, bytes data): kind is receipts and data is JSON with date, signer, count and root. The inference page lists each day's root with its transaction.

Enclave receipts

Phala's models, the ones with attestation in /v1/models, run inside a trusted execution environment (TEE), and every call reaches them through Phala's gateway, which runs in an enclave as well. For each answer, Phala's gateway signs a receipt inside its enclave. The receipt holds two hashes, of the response the model's enclave sent and of the one Phala's gateway returned (it may rewrite the response), and records that Phala's gateway verified the model's enclave. BrainChain's gateway checks the receipt before it charges for the call. It reaches Phala's service through Phala's verifier, @phala/aci-verifier, which checks the hardware quote of Phala's gateway enclave, pins the connection to it and asks for answers served only from a verified enclave. An answer whose receipt does not match its bytes is not charged: the call fails with upstream_failed.

BrainChain's gateway also holds Phala's gateway to what Phala publishes about it. Phala announces each production release of its gateway, with the hash of the compose file it runs, at least three days before it rolls out, and Phala's app contract on Base, 0x89c51ab856bee41efe78c40309a4deb277a02a0f, lists the compose hashes allowed to boot. BrainChain's gateway reads that list for the compose the hardware quote measured, and reads it again once its last reading is 10 minutes old. It also checks the custody of the key that signs the receipts: a chain of signatures must show that Phala's key management service (KMS) on Base issued it to Phala's gateway. If Base's list does not allow the compose, or the custody chain does not hold, Phala's models are not sold. Calls to them fail with upstream_failed and nothing is charged.

The receipt comes back in the X-Upstream-Receipt header, base64 like X-BrainChain-Receipt, and the day's GET /v1/served/<YYYY-MM-DD> keeps it in the call's entry at aci.receipt, with keyset beside it (for a sealed call, the entry names the receipt by its id). The entry also records what the gateway found: aci.compose, aci.release (allowed, and readAt, when Base gave that answer) and aci.custody (holds).

If Base does not answer, calls go on. The last answer Base gave stands, and aci.release shows when it was given and, in reason, why it was not read again. A compose Base has not answered for yet, such as a release that rolls out while Base is down, shows allowed: null. Such a compose still had to pass the same list when it booted: Phala's KMS releases its keys only to a compose the list allows, and the custody check shows that the receipt key came from it. BrainChain's gateway passes on the bytes Phala's gateway returned unchanged, so a buyer can check that the answer received is the one Phala signed for, and that the model's enclave was verified.

Phala renews the keys that sign these receipts every few weeks and keeps receipts for a limited time. While a receipt's keys are current, check it against the report Phala's service publishes now, read with a nonce of your own. After Phala renews them, use the report BrainChain's gateway kept: the first time a receipt names a set of keys, the gateway fetches that set's attestation report with a nonce of its own and keeps both at GET /v1/served/keysets/<hex>, where <hex> is the receipt's workload_keyset_digest without sha256:. A kept report is checked as of the moment the answer was served. Its nonce is the gateway's, so it shows that Phala's enclave held those keys, not when the report was read.

The receipt also cites the session in which Phala's gateway verified the model's enclave. Phala's service publishes that session's record at https://api.redpill.ai/v1/aci/sessions/<id>, with no key, for about an hour. For calls since 27 November 2026, 11:57 UTC, BrainChain's gateway keeps each record a receipt cites at GET /v1/served/sessions/<id>, exactly as Phala served it. A record hashes to the id the signed receipt cites, so the gateway's copy is checked like Phala's.

Install Phala's verifier and BrainChain's with npm install @phala/aci-verifier brainchain-verify. Then, in Node, as an ES module, with paid and bytes from the client above asking for a Phala model such as phala-deepseek:

import { receiptTranscript, reportTranscript } from "@phala/aci-verifier";
import { connectAci } from "@phala/aci-verifier/runtime";
import { allowedOnBase, custodyOf, replayRtmr3, verifyTdxQuote } from "brainchain-verify/phala";

const receipt = JSON.parse(Buffer.from(paid.headers.get("x-upstream-receipt"), "base64").toString());
const digest = receipt.workload_keyset_digest;
const fail = (reason) => {
  console.error(reason);
  process.exit(1);
};

// Phala's report as it stands, read with a nonce of your own over a connection pinned to the TLS key it attests.
const phala = await connectAci({ baseURL: "https://api.redpill.ai/v1" });
let report = phala.identity.transcript;
let served = phala.identity.report;
await phala.close();
// Once Phala has renewed the keys, the report the gateway kept for the receipt's keys, checked as of when the answer was served.
if (report.verification.workloadKeysetDigest !== digest) {
  const kept = await fetch(`https://inference.usebrainchain.com/v1/served/keysets/${digest.replace(/^sha256:/, "")}`);
  if (!kept.ok) fail(`no report is kept for keys ${digest}`);
  const archived = await kept.json();
  report = await reportTranscript(archived.report, archived.nonce, { now: receipt.served_at });
  served = archived.report;
}
console.log(report.verdict.line);
if (!report.verdict.verified) fail("the report does not verify");

// The compose and app the boot measured, each event's digest recomputed, then Phala's release list on Base and the
// receipt key's custody chain to Phala's KMS root.
const { evidence } = served.attestation;
const measured = replayRtmr3(evidence.event_log, verifyTdxQuote(Buffer.from(evidence.quote, "hex"), receipt.served_at * 1000).rtmr3);
if (!(await allowedOnBase(measured["compose-hash"]))) fail("Phala's list on Base does not allow the compose its gateway ran");
const custody = await custodyOf(served, measured["app-id"]);
if (custody) fail(`the receipt key's custody does not hold: ${custody}`);

// The receipt's signature and keys, the hash of the answer as received, and the session in which Phala's gateway
// verified the model's enclave. The request reaches Phala as BrainChain's gateway forwards it, so its hash is left out.
const cited = receipt.event_log.find((event) => event.type === "upstream.verified").session_id;
// Phala serves a session's record for about an hour; the gateway keeps each one a receipt cites.
let found = await fetch(`https://api.redpill.ai/v1/aci/sessions/${cited}`);
if (!found.ok) found = await fetch(`https://inference.usebrainchain.com/v1/served/sessions/${cited}`);
if (!found.ok) fail(`no record is kept for session ${cited}`);
const { keyset, workloadKeysetDigest } = report.verification;
const check = await receiptTranscript(receipt, keyset, workloadKeysetDigest, undefined, bytes, { session: await found.json() });
console.log(check.verdict.line);
if (!check.verdict.verified) fail("the answer is not the one Phala's gateway signed for");

What this checks: the quote of Phala's gateway enclave against Intel's root, its signing keys bound to a nonce (yours, or the one the gateway kept with the report), the software measured into the quote and that Phala's list on Base allows it, that Phala's KMS issued the receipt key to Phala's gateway, the receipt's signature and keys, the hash of the answer, and that Phala's gateway recorded verifying the enclave serving the model in a session whose record matches. Read from Phala's service directly, the connection is also pinned to the TLS key the report covers; a kept report has no live connection, so that check is skipped. What it does not: that the receipt key is the one derived from the key the KMS issued, which rests on the code the compose runs (the reason the compose is held to Phala's list), or where Phala's gateway keeps its TLS and encryption keys. The session names the model as Phala's enclave serves it, for example deepseek/deepseek-v4.1-flash-1017:unc for phala/deepseek-v4.1-flash-1017-uncensored, and the verifier does not compare the two names.

GET /v1/served/<YYYY-MM-DD> returns { day, calls }, one entry per receipt of the day in list order: receipt (the receipt's hash), at, model, servedBy, tokensIn, tokensOut, price, and aci for a call Phala's gateway signed. An archive id that is not 64 hex digits answers 400, and one the gateway does not keep answers 404 with the code no_keyset or no_session.

For one of Phala's models, the usage page shows how many of its calls since 27 November 2026 carry an enclave receipt.

Sealed calls

For Phala's models, a buyer can seal the call: the prompt is encrypted to a key inside Phala's gateway enclave, and the answer comes back encrypted to a key only the buyer holds. BrainChain's gateway relays the call, charges for it, signs its receipt and checks Phala's, without being able to read the prompt or the answer. Token counts stay readable, so the charge is what the answer used, as on any call. The authorization is larger: an encrypted message can unpack into images the gateway cannot count, so the price request covers the model's whole context window instead of the body's size.

It is Phala's end-to-end encryption, E2EE v2, with the X25519 suite:

  1. Read Phala's report through Phala's attested client and take, from the keyset it verified, the e2ee_public_keys entry whose algo is x25519-aes-256-gcm-hkdf-sha256. Take the key from Phala's report, never from BrainChain.
  2. Encrypt every message's content to it, each as one field. A sealed call with any message left in the clear is refused. The associated data names the model as Phala receives it, the model's upstream in /v1/models, while the request's model stays BrainChain's id.
  3. Send five headers with both requests, the price request and the paid one: X-E2EE-Version: 2, X-Client-Pub-Key, X-Model-Pub-Key, X-E2EE-Nonce and X-E2EE-Timestamp. Phala accepts a timestamp within five minutes of its own clock.
  4. The answer's choices[0].message.content comes back encrypted to your key, with X-E2EE-Applied: true.

In Node, as an ES module, after npm install @phala/aci-verifier:

import { createCipheriv, createDecipheriv, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes } from "node:crypto";
import { connectAci } from "@phala/aci-verifier/runtime";

const ALGO = "x25519-aes-256-gcm-hkdf-sha256";
const jcs = (o) => JSON.stringify(Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]])));
const raw = (key) => Buffer.from(key.export({ format: "jwk" }).x, "base64url");
const x25519 = (hex) => createPublicKey({ key: { kty: "OKP", crv: "X25519", x: Buffer.from(hex, "hex").toString("base64url") }, format: "jwk" });
const aesKey = (own, peer) => Buffer.from(hkdfSync("sha256", diffieHellman({ privateKey: own, publicKey: peer }), Buffer.alloc(0), "aci.e2ee.v2.x25519", 32));

// The key to encrypt to, from Phala's report as Phala's attested client verifies it.
const phala = await connectAci({ baseURL: "https://api.redpill.ai" });
const { keyset } = phala.identity.transcript.verification;
await phala.close();
const service = keyset.e2ee_public_keys.find((k) => k.algo === ALGO);

const upstream = "phala/deepseek-v4.1-flash-1017-uncensored"; // `upstream` of phala-deepseek in /v1/models
const client = generateKeyPairSync("x25519");
const nonce = randomBytes(32).toString("hex");
const ts = Math.floor(Date.now() / 1000);
const aad = (purpose, field, id) => Buffer.from(jcs({ purpose, algo: ALGO, model: upstream, ...(id === undefined ? {} : { id }), field, nonce, ts }));

function seal(text, field) {
  const ephemeral = generateKeyPairSync("x25519");
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", aesKey(ephemeral.privateKey, x25519(service.public_key)), iv);
  cipher.setAAD(aad("aci.e2ee.request.v2", field));
  const sealed = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);
  return Buffer.concat([raw(ephemeral.publicKey), iv, sealed, cipher.getAuthTag()]).toString("hex");
}
function open(hex, field, id) {
  const bytes = Buffer.from(hex, "hex");
  const decipher = createDecipheriv("aes-256-gcm", aesKey(client.privateKey, x25519(bytes.subarray(0, 32).toString("hex"))), bytes.subarray(32, 44));
  decipher.setAAD(aad("aci.e2ee.response.v2", field, id));
  decipher.setAuthTag(bytes.subarray(bytes.length - 16));
  return Buffer.concat([decipher.update(bytes.subarray(44, bytes.length - 16)), decipher.final()]).toString("utf8");
}

const prompt = "Name one prime number above 100.";
const body = JSON.stringify({ model: "phala-deepseek", messages: [{ role: "user", content: seal(prompt, "messages.0.content") }], max_tokens: 2048 });
const headers = { "X-E2EE-Version": "2", "X-Client-Pub-Key": raw(client.publicKey).toString("hex"), "X-Model-Pub-Key": service.public_key, "X-E2EE-Nonce": nonce, "X-E2EE-Timestamp": String(ts) };
// Pay as the client above does, with `body`, and with `headers` on both requests. Then, with `bytes` the paid answer's bytes:
const answer = JSON.parse(new TextDecoder().decode(bytes));
console.log(open(answer.choices[0].message.content, "choices.0.message.content", answer.id ?? ""));

A request that sends some but not all five headers is refused before payment, and so is a sealed call to a model without sealed: true in /v1/models, or a judged one: a judge could not read the answer. An answer Phala returns unencrypted to a sealed call is not sold, and the call fails with upstream_failed. The day's GET /v1/served/<YYYY-MM-DD> marks a sealed call with aci.sealed and names Phala's receipt by its id, aci.receiptId, without listing it: the receipt's request hash is a hash of your decrypted prompt, so only you get the receipt, in X-Upstream-Receipt. A receipt too large for that header, over 8 KB in base64, is listed as on any call, since the list is then your only copy.

BrainChain's gateway checks every part of Phala's receipt but one: the request hash covers the request as Phala decrypted it, which only the buyer can rebuild. It is the request as BrainChain's gateway forwards it with your text in place, as compact JSON: first the settings you sent of temperature, top_p, stop, seed, presence_penalty, frequency_penalty and user, in that order, then messages as { role, content }, max_tokens (yours, or 8,192 when you sent more or none), model set to the upstream id, and provider as {"aci_verified":true}. With those bytes as the request evidence in the enclave receipts check, all six receipt and upstream checks pass.

Phala supports E2EE v2 through at least 10 February 2027 and plans a successor, which BrainChain will follow.

Usage for providers

A model's provider can follow the traffic agents send it: calls, tokens and what they paid, per UTC day. The usage page shows the last 30 days for every model, and ?model=<id> opens one, for example ?model=phala-deepseek.

The page adds up the day lists from GET /v1/receipts/<YYYY-MM-DD>, and a script can do the same. The lists need no key and answer any origin. Keep the receipts whose model is the model's id in /v1/models, then add up:

Figure From each receipt
Calls One per receipt
Tokens in, tokens out tokensIn, tokensOut
Charged price, in millionths of a USDG, the per-call fee included
Last call The latest at

One day for one model, with curl and jq:

curl -s https://inference.usebrainchain.com/v1/receipts/2026-11-24 \
  | jq '[.receipts[] | select(.model == "phala-deepseek")]
    | {calls: length,
       tokensIn: (map(.tokensIn) | add // 0),
       tokensOut: (map(.tokensOut) | add // 0),
       usdg: ((map(.price | tonumber) | add // 0) / 1e6)}'

The last 30 UTC days, one line per day, with Node 18 or later. Save it as usage.mjs and run node usage.mjs phala-deepseek:

const model = process.argv[2];
const DAY = 86_400_000;

for (let i = 29; i >= 0; i -= 1) {
  const day = new Date(Date.now() - i * DAY).toISOString().slice(0, 10);
  const response = await fetch(`https://inference.usebrainchain.com/v1/receipts/${day}`);
  // A day before the first receipt has no list.
  if (response.status === 404) {
    console.log(day, 0, 0, 0, "0.000000");
    continue;
  }
  if (!response.ok) throw new Error(`${day}: ${response.status}`);
  const { receipts } = await response.json();
  const mine = receipts.filter((receipt) => receipt.model === model);
  const sum = (field) => mine.reduce((total, receipt) => total + Number(receipt[field]), 0);
  console.log(day, mine.length, sum("tokensIn"), sum("tokensOut"), (sum("price") / 1e6).toFixed(6));
}

The first list is for 19 November 2026. An earlier day, or a day after today, answers 404 with the code no_list. Today's list grows until 00:00 UTC. A closed day's list keeps its root, which BrainChain records as Check a receipt describes, so figures saved from it can be checked again later.

When a call fails

A reply about payment is x402's JSON with the reason in error. Any other failure is an OpenAI-style error object with a message and, where the table names one, a code.

Reply Meaning
400 The request was turned away before payment. request_too_large means it could cost more than one request may: shorten it or lower max_tokens
413 The body is over 200 kB
404 model_not_found No model has that id
402 with an error other than payment_required The payment was not accepted, for example permit2_insufficient_balance. Nothing was charged
402 authorization_used This authorization has been used. Sign a new one for the request
402 settlement_failed The payment did not settle, so the answer is not returned
429 payer_busy The wallet has another request in flight. Send the next one when it is answered
403 payer_blocked A payment from this wallet could not be settled. It is served again a day later
503 paused Paid requests are paused. Nothing was charged. Try again later
502 upstream_failed The model gave no answer. Nothing was charged