## Account and billing

[Sign in](https://carbium.sh/login) with an emailed 6-digit code, Google, X or a Solana wallet, with the [Carbium Terms](https://carbium.sh/terms) ticked. First sign-in: a starter key and one-time free credits; FREE has RPC and WebSocket, no carbon stream.

### agents: only a solana keypair

| step | call |
|---|---|
| 1 challenge | `GET /v1/signup/challenge` answers `{challenge, difficulty}`; valid once, for 300 s. |
| 2 solve | find a u64 `nonce` where BLAKE3(challenge UTF-8 bytes + `nonce` as 8 little-endian bytes) starts with `difficulty` zero bits (now 18, about 262,000 hashes). |
| 3 message | `POST /v1/auth/wallet` step `challenge`, base58 `wallet` answers `{nonce_token, message}`; signing it accepts the Terms version it names. |
| 4 verify | sign it (ed25519, base58 or base64), send step `verify` with `wallet`, `nonce_token`, `signature`, `pow: {challenge, nonce}`; answers `{session_token, account}`. |
| 5 key | `GET /v1/keys` with `Authorization: Bearer <session_token>`, then `POST /v1/keys/{key_id}/secret` for `raw_key`; wallet accounts get no email. |
| 6 quote | `POST /v1/modules/quote` `{"plan": "free"}` with the session adds the free Quote plan: every live key gains `quote`; `quote`, `swap`, `prices` and `health` cost no credits. |
| 7 pay | optional, before the first call, carbium.sh only: `POST /v1/billing/crypto-intent` with `payer`, sign its `tx`, send it at once via any Solana RPC (the door refuses it without credits). Poll `GET /v1/billing/crypto-intent/{intent_id}` until `paid` (or `held`, `expired`). RPC plans add credits, Quote plans none. |
| 8 call | `x-api-key: <raw_key>` on `services.carbium.sh`; a first call may get 429 `CREDITS_PENDING`: retry after `Retry-After`. No credits: 402 on billed calls. |
| 9 automate | `POST /v1/account/api-keys` with the session and `{"name": "automation", "access": "read"}` (or `"full"`) answers an [account API key](https://carbium.sh/docs/account-api-keys.md), shown once; it runs the account without this wallet and cannot pay or cancel. |
| limits | 3 sign-ups a day per IPv4 address or IPv6 /56; Tor, ASN-DROP and denied subnets: 403. Back off on `retry-after-ms`: a free account refused most hours of a day is suspended. |

> Full reference and the paid path: [SKILL.md](https://carbium.sh/docs/agents.md) section "Agents: onboard yourself with only a Solana keypair", also at [/skill.md](https://carbium.sh/skill.md).

```
// Onboard to Carbium with only a Solana keypair, no browser and no inbox: a free account, its key, the free Quote plan, a first call
// and a first quote; then, if you ask for one, a paid plan paid in USDC or USDT from the same wallet (carbium.sh only).
//   npm i @solana/kit @noble/hashes
//   KEYPAIR=~/agent.json node onboard.ts            free account, key and Quote plan (Node 22.18+ runs TypeScript as is)
//   KEYPAIR=~/agent.json PLAN=starter node onboard.ts    and the Quote API Starter plan (or TIER=dev for an RPC tier)
//   KEYPAIR=~/agent.json ACCOUNT_KEY=read node onboard.ts  and an account API key for your automation (read or full), saved to ./carbium-account-key
import {
  createKeyPairSignerFromBytes, generateKeyPairSigner, getBase58Decoder, getBase64EncodedWireTransaction, getBase64Encoder,
  getTransactionDecoder, signBytes, signTransaction,
} from "@solana/kit";
import { blake3 } from "@noble/hashes/blake3.js";
import { readFileSync, writeFileSync } from "node:fs";

const DASH = process.env.CARBIUM_DASH ?? "https://carbium.sh";           // the account API
const DOOR = process.env.CARBIUM_DOOR ?? "https://services.carbium.sh";  // the RPC door
// Any Solana RPC sends the plan payment: an account with no credits (a wallet whose earlier account was deleted starts at 0) cannot use the door.
const SOLANA_RPC = process.env.SOLANA_RPC ?? "https://api.mainnet-beta.solana.com";

async function call(path: string, init: { body?: unknown; session?: string; post?: boolean } = {}) {
  const res = await fetch(DASH + path, {
    method: init.post || init.body !== undefined ? "POST" : "GET",
    headers: {
      ...(init.body !== undefined ? { "content-type": "application/json" } : {}),
      ...(init.session ? { authorization: `Bearer ${init.session}` } : {}),
    },
    body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
  });
  const text = await res.text();
  if (!res.ok) throw new Error(`${path}: HTTP ${res.status} ${text}`);
  return JSON.parse(text);
}

async function rpc(key: string, method: string, params: unknown[]) {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(DOOR, {
      method: "POST",
      headers: { "content-type": "application/json", "x-api-key": key },
      body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
    });
    const r = await res.json();
    // A new key's first call can reach a node before its credits do: 429 CREDITS_PENDING (-32005, retryable). Wait and retry.
    if (r.error?.data?.reason === "CREDITS_PENDING" && attempt < 4) {
      await new Promise((ok) => setTimeout(ok, Number(res.headers.get("retry-after-ms") ?? 1000)));
      continue;
    }
    if (r.error) throw new Error(`${method}: ${JSON.stringify(r.error)}`);
    return r.result;
  }
}

// The sign-up challenge (an anti-abuse puzzle): the first u64 nonce whose blake3(challenge's UTF-8 bytes, then the nonce as 8 little-endian bytes)
// starts with at least `difficulty` zero bits.
function solve(challenge: string, difficulty: number): number {
  const c = new TextEncoder().encode(challenge);
  const buf = new Uint8Array(c.length + 8);
  buf.set(c);
  const view = new DataView(buf.buffer);
  for (let nonce = 0; ; nonce++) {
    view.setBigUint64(c.length, BigInt(nonce), true);
    let bits = 0;
    for (const b of blake3(buf)) {
      if (b === 0) { bits += 8; continue; }
      bits += Math.clz32(b) - 24;
      break;
    }
    if (bits >= difficulty) return nonce;
  }
}

// The agent's keypair: a solana-keygen JSON file (64 bytes), or a new one for a trial.
const signer = process.env.KEYPAIR
  ? await createKeyPairSignerFromBytes(new Uint8Array(JSON.parse(readFileSync(process.env.KEYPAIR, "utf8"))))
  : await generateKeyPairSigner();
const wallet = signer.address;

// 1. A one-use sign-up challenge (it lasts 300 s), solved locally.
const { challenge, difficulty } = await call("/v1/signup/challenge");
const nonce = solve(challenge, difficulty);

// 2. The sign-in message. It names the Carbium Terms and their version: signing it is your acceptance of them.
const { nonce_token, message } = await call("/v1/auth/wallet", { body: { step: "challenge", wallet } });
const signature = getBase58Decoder().decode(await signBytes(signer.keyPair.privateKey, new TextEncoder().encode(message)));

// 3. Verify. A new wallet opens a free account (500,000 credits) with one starter key; a known wallet signs in.
const { session_token } = await call("/v1/auth/wallet", {
  body: { step: "verify", wallet, nonce_token, signature, pow: { challenge, nonce } },
});

// 4. A paid plan, if you want one (carbium.sh only), before the first call: a wallet whose earlier account was deleted starts with
// no credits; an RPC tier (TIER) adds credits and a Quote plan (PLAN) adds none. The wallet pays the plan's price in USDC (or USDT with "mint") and a little SOL for the fee.
if (process.env.PLAN || process.env.TIER) {
  const want = process.env.PLAN ? { plan: process.env.PLAN } : { tier: process.env.TIER };
  const intent = await call("/v1/billing/crypto-intent", { session: session_token, body: { ...want, payer: wallet } });
  if (intent.sim_error) throw new Error(`the payment would fail: ${intent.sim_error}`);
  // `tx` is an unsigned v0 transaction on a fresh blockhash that pays this intent from your wallet: sign it and send it at once.
  const signed = await signTransaction([signer.keyPair], getTransactionDecoder().decode(getBase64Encoder().encode(intent.tx)));
  const sent = await fetch(SOLANA_RPC, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "sendTransaction", params: [getBase64EncodedWireTransaction(signed), { encoding: "base64" }] }),
  }).then((res) => res.json());
  if (sent.error) throw new Error(`sendTransaction: ${JSON.stringify(sent.error)}`);
  for (;;) {
    const s = await call(`/v1/billing/crypto-intent/${intent.intent_id}`, { session: session_token });
    if (s.status === "paid") break;
    if (s.status !== "open") throw new Error(`intent ${intent.intent_id} is ${s.status}`); // held: received, not applied, no plan bought: contact support; expired: start again
    await new Promise((r) => setTimeout(r, 2000));
  }
  console.log(JSON.stringify({ paid: intent.intent_id, account: await call("/v1/account", { session: session_token }) }));
}

// 5. The key's secret. A wallet account has no email, so read it here: list the keys, then reveal one.
const [key] = await call("/v1/keys", { session: session_token });
const { raw_key } = await call(`/v1/keys/${key.key_id}/secret`, { session: session_token, post: true });

// 6. The free Quote plan, unless you bought a paid one above: every live key gains `quote`, and the quote plane costs no credits.
if (!process.env.PLAN) await call("/v1/modules/quote", { session: session_token, body: { plan: "free" } });

// 7. A first call on the door. getSlot costs 1 credit: an account with none (a wallet whose earlier account was deleted, which
// bought nothing or only a Quote plan) is answered 402 -32002 `credits exhausted` until it buys an RPC tier (TIER=dev).
const slot = await rpc(raw_key, "getSlot", []).catch((e) => {
  if (String(e).includes('"code":-32002')) return "no credits: buy an RPC tier (TIER=dev) to call RPC";
  throw e;
});

// 8. A first quote: 0.001 SOL to USDC, amounts in base units as strings. `swap` with its `quoteId` builds the transaction to sign.
const quote = await rpc(raw_key, "quote", [{
  src_mint: "So11111111111111111111111111111111111111112", dst_mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
  amount_in: "1000000", slippage_bps: 50,
}]);
const now = await call("/v1/account", { session: session_token }); // the tier after any purchase above
console.log(JSON.stringify({ wallet, account_id: now.account_id, tier: now.tier, key_id: key.key_id, slot, usdc_out: quote.destAmountOut }));

// 9. An account API key for your automation, if you ask for one (ACCOUNT_KEY=read or full). It runs the account by API without
// this wallet, and it cannot pay or cancel. Its value is shown once: it goes to a file only you can read, never to the console.
if (process.env.ACCOUNT_KEY) {
  const made = await call("/v1/account/api-keys", { session: session_token, body: { name: "automation", access: process.env.ACCOUNT_KEY, expires_in_days: 90 } });
  writeFileSync("carbium-account-key", made.raw_key + "\n", { mode: 0o600 });
  const self = await call("/v1/api-key", { session: made.raw_key }); // the key as the bearer: its own record
  console.log(JSON.stringify({ account_api_key: self.prefix, access: self.access, expires_at: self.expires_at, saved: "carbium-account-key" }));
}
```

### keys and billing

| what | how |
|---|---|
| keys | live keys: FREE 1, DEV 5, BUSINESS 10, PRO 50 (revoked excluded). Create, rotate and revoke on [KEYS](https://carbium.sh/). |
| rotate | same key, new secret; the old one is refused at once. Within about 2 s an open WebSocket closes 1008 key_revoked, a stream ends UNAUTHENTICATED api key revoked. |
| revoke / delete | revoke refuses the key everywhere, cut off as on rotate. The dashboard hides it; GET /v1/keys shows revoked_at until DELETE /v1/keys/{id}. |
| key emails | each new key with its endpoints (stream on :9443), a rotate's new secret, and a notice without secrets on revoke, delete, or an account API key made or revoked. |
| permissions | per key: RPC, WS, GRPC (the stream), QUOTE and DAS, at issue or with SCOPE. DAS starts ticked; untick it to keep a key off the DAS methods. QUOTE needs the Quote module, GRPC Dev or higher. A call outside them gets 401. |
| ip allowlist | up to 16 IPv4 or IPv6 addresses or CIDRs per key; others get 403 IP_NOT_ALLOWED, PERMISSION_DENIED on the stream ([errors](https://carbium.sh/docs/errors.md)). |
| method caps | per-key req/s ceiling on one rate class; past it, 429 ([rate limits](https://carbium.sh/docs/limits.md)). |
| plans | DEV, BUSINESS and PRO, monthly; prices and credits at [/v1/plans](https://carbium.sh/v1/plans). FREE: the one-time grant. Quote module plan: [MODULES](https://carbium.sh/modules) ([quote api](https://carbium.sh/docs/quote.md)). |
| paying | Stripe card, monthly renewal or a single month; or USDC or USDT from your Solana wallet: one month on [ACCOUNT](https://carbium.sh/account), 1 to 12 months via `POST /v1/billing/crypto-intent`. Prepaid terms do not renew. |
| credits | each paid month adds its plan's credits, which carry over. At term end the account drops to FREE; keys keep working. |
| invoices | invoice PDFs and CSV on [BILLING](https://carbium.sh/billing); Manage billing opens Stripe for the card; crypto payments link to Solscan. |
| emails | receipts, monthly statement, low-balance notice, and a reminder before a non-renewing DEV, BUSINESS or PRO term ends (none for Quote module terms). |
| cancel | on [BILLING](https://carbium.sh/billing): the plan runs to term end, no further charge; undoable until then. |
| delete account | on [BILLING](https://carbium.sh/billing): two warnings, then type DELETE. Paid time left is lost, every key revoked; a returning identity gets no free credits ([acceptable use](https://carbium.sh/docs/terms.md)). |

> API calls for each control: [SKILL.md](https://carbium.sh/docs/agents.md) section "Account, keys and billing".
