# Carbium - Solana Infrastructure Skill

> You are integrating with Carbium, a bare-metal Solana infrastructure provider.
> This file is the short form. It tells you where each service answers, how the key travels and gives one working sample per service.

## Products

| Product | URL | Purpose |
|---------|-----|---------|
| Carbium RPC | https://services.carbium.sh | Solana JSON-RPC reads and writes |
| WebSocket | wss://services.carbium.sh | Native Solana pubsub (account, program, logs, signature, slot, root, block subscriptions) |
| Carbon Stream (gRPC) | https://services.carbium.sh:9443 | Yellowstone gRPC stream of slots, accounts and transactions matching your filters |
| Carbium Swap API | https://services.carbium.sh | Quotes and unsigned swap transactions across Solana liquidity; your app signs and submits. Swaps built with it pay a 0.05% on-chain router fee |
| Carbium Swap | https://dex.carbium.io | Swap app built on the Swap API. Carbium Swap is non-custodial: you connect your own wallet and sign every transaction yourself, except the scheduled buys of a DCA you opened |
| Docs | https://carbium.io/docs/ | Guides |
| Dashboard and keys | https://carbium.sh/ | Sign in, keys, plans |

## Full reference: load it for anything beyond this file

The full and current reference for Carbium RPC, WebSocket, Carbon Stream and quotes is **https://carbium.sh/skill.md**. Load that file for anything beyond the short form here: every method, limit, error and complete client. The same reference for people: https://carbium.sh/docs.

Keys made before carbium.sh keep working on the endpoints of the earlier service until those plans run out. The pages for those keys are marked in https://carbium.io/docs/.

---

## API Key Management

- One key for every service. Sign in on https://carbium.sh/ to get it.
- Send the full key (`c_serv_...`). The short prefix the dashboard lists is a label and is refused.
- What a new key needs before each service answers:
  - RPC and WebSocket: the starter key covers both.
  - Carbon Stream: a paid plan, and the gRPC scope turned on for the key.
  - Quotes: the Quote module added on the dashboard (it has a free plan).
- Plans: https://carbium.sh/ or https://carbium.sh/v1/plans. Limits: https://carbium.sh/docs#limits
- Environment variable: `CARBIUM_KEY`
- **Security:** Never embed keys client-side, avoid version control commits, rotate regularly. Prefer a header over the URL so the key stays out of logs.

Auth reference: https://carbium.sh/docs#auth

---

## Primary Use Cases

| Use Case | Product |
|----------|---------|
| Account data / balance reads | RPC |
| Transaction submission | RPC |
| Wallet application building | RPC + WebSocket + Swap API |
| Token swap quotes | Swap API |
| Programmatic swap transactions | Swap API |
| Wallet SOL balance updates | WebSocket (logsSubscribe with mentions) + RPC getBalance |
| Token account updates | WebSocket (accountSubscribe) |
| Transaction confirmation (no polling) | WebSocket (signatureSubscribe) |
| Program account monitoring | WebSocket (programSubscribe) |
| Log-based event indexing | WebSocket (logsSubscribe) |
| Slot / block clock monitoring | WebSocket (slotSubscribe) |
| Full blocks | RPC (getBlock) |
| Transaction indexing (by account filter) | Carbon Stream |
| Wallet monitoring (all activity) | Carbon Stream (transactions with accountInclude) |
| Portfolio tracking | RPC |

---

## 1. RPC - Solana JSON-RPC

### Endpoint
```bash
POST https://services.carbium.sh
```

### Authentication
The key goes in the `x-api-key` header (preferred), or in the query string as `?api-key=`.

### Example - getBalance (curl)
```bash
curl -s https://services.carbium.sh \
  -H "content-type: application/json" \
  -H "x-api-key: $CARBIUM_KEY" \
  -d '{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["YOUR_WALLET_ADDRESS"]}'
```

### TypeScript (@solana/web3.js v1)
```typescript
import { Connection, PublicKey } from "@solana/web3.js";
const KEY = process.env.CARBIUM_KEY;
const connection = new Connection("https://services.carbium.sh", {
  commitment: "confirmed",
  httpHeaders: { "x-api-key": KEY }, // key stays out of the URL
  wsEndpoint: "wss://services.carbium.sh/?api-key=" + KEY, // web3.js derives ws from http, so set it
});
const slot = await connection.getSlot();
const info = await connection.getAccountInfo(new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"));
```

### Rules that matter
- Put `"method"` before `"params"` in every request object.
- Always send `"maxSupportedTransactionVersion": 1` on `getTransaction` and `getBlock`: mainnet carries version-1 transactions.
- Standard Solana JSON-RPC methods are served. A few are not (for example `requestAirdrop` and `getTokenLargestAccounts`): see the method list in the reference.

Reference: https://carbium.sh/docs#rpc

### Commitment Levels
- `processed` - fastest, rollback risk
- `confirmed` - recommended default
- `finalized` - guaranteed, slowest

---

## 2. WebSocket - Solana Pubsub

### Endpoint
```bash
wss://services.carbium.sh
```

Same domain and key as RPC: the `x-api-key` header on the handshake, or `?api-key=` on the URL. Native Solana subscription protocol - any Solana SDK works out of the box.

### WebSocket vs Carbon Stream - When to Use Which

| | WebSocket | Carbon Stream |
|---|---|---|
| **Protocol** | JSON-RPC over WebSocket | gRPC (Yellowstone) |
| **What you get** | Account changes, slot updates, logs, signatures, blocks | Slots, accounts and transactions matching your filters |
| **Best for** | Wallets, dApps, monitoring specific accounts | Indexers of the accounts and programs you filter on |

**Rule of thumb:** watching specific accounts or signatures -> WebSocket. Processing every transaction that touches accounts or programs you name -> Carbon Stream.

### Subscription Methods

| Method | What it streams |
|---|---|
| `accountSubscribe` | Account data changes (not plain SOL wallets: use `logsSubscribe` with `mentions` plus `getBalance`) |
| `programSubscribe` | Accounts owned by a covered program |
| `logsSubscribe` | Transaction logs (`"all"` or `{"mentions":[one address]}`) |
| `signatureSubscribe` | Transaction confirmation (one notification, then it ends) |
| `slotSubscribe` | New slot numbers |
| `rootSubscribe` | Rooted slots |
| `slotsUpdatesSubscribe` | Slot lifecycle updates |
| `blockSubscribe` | Blocks (send `"maxSupportedTransactionVersion": 1`) |

Each has a matching `...Unsubscribe`. Only these methods and `getVersion` work over the socket; send every other method to RPC.

### TypeScript - slotSubscribe (Node 22+ global WebSocket)

```typescript
const ws = new WebSocket("wss://services.carbium.sh/?api-key=" + process.env.CARBIUM_KEY);
ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" }));
ws.onmessage = (e) => {
  const m = JSON.parse(e.data);
  if (m.id === 1) return m.error ? console.error(m.error) : console.log("sub id", m.result);
  if (m.method === "slotNotification") console.log(m.params.result.slot);
};
ws.onclose = (e) => console.log("closed", e.code, e.reason); // see the close-code table
```

### Reconnection (Required for Production)
- Reconnect with exponential backoff and jitter.
- Subscription ids are not stable across connections: after any reconnect, re-send every subscribe and map the new ids.
- Nothing is replayed: after a disconnect, re-read the state you care about over RPC.
- Answer server pings (browsers, Node 22+ `WebSocket` and the `ws` package do this on their own) and read fast.

Reference, with a complete reconnecting client and every close code: https://carbium.sh/docs#websocket

---

## 3. Swap API - Quotes and Swap Transactions

### Get a Key
1. Sign in on https://carbium.sh/ and add the Quote module (it has a free plan).

### How it works
Quotes are JSON-RPC methods on the RPC endpoint, `POST https://services.carbium.sh`, with the same key carriers as RPC: `quote`, `swap`, `prices`, `health`. There are no REST paths. Send one call per request (no batches).

- `quote` takes `src_mint`, `dst_mint`, `amount_in` (base units, as a string) and `slippage_bps`. It answers a `quoteId`, valid for 30 s.
- `swap` takes `quote_id` and `user_pubkey` (the wallet that signs) and returns one unsigned `transaction` (base64).
- Your app signs it as `user_pubkey` only, never modifies it, sends it through RPC `sendTransaction` with `skipPreflight: true` and confirms with `getSignatureStatuses`.

### TypeScript - Quote, then Swap
```typescript
// npm i @solana/web3.js
import fs from "node:fs";
import { Keypair, VersionedTransaction } from "@solana/web3.js";

const DOOR = "https://services.carbium.sh";
const KEY = process.env.CARBIUM_KEY; // the FULL raw key, never the short c_serv_ prefix the dashboard lists
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function call(method, params) {
  const r = 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 j = await r.json();
  if (j.error) throw Object.assign(new Error(`${method} ${j.error.code}: ${j.error.message}`), { http: r.status, code: j.error.code, data: j.error.data });
  return j.result;
}

const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(fs.readFileSync(process.env.WALLET_PATH, "utf8")))); // solana-keygen JSON

// 1. Quote 0.01 SOL to USDC
const q = await call("quote", [{ src_mint: "So11111111111111111111111111111111111111112", dst_mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", amount_in: String(10_000_000), slippage_bps: 50 }]);

// 2. Build the unsigned transaction within 30 s
const s = await call("swap", [{ quote_id: q.quoteId, user_pubkey: wallet.publicKey.toBase58() }]);

// 3. Sign as user_pubkey only, send, confirm
const tx = VersionedTransaction.deserialize(Buffer.from(s.transaction, "base64"));
tx.sign([wallet]); // wallet = Keypair for user_pubkey: fee payer and only signer
const wire = Buffer.from(tx.serialize()).toString("base64");
const sig = await call("sendTransaction", [wire, { encoding: "base64", skipPreflight: true }]);
for (;;) {
  const { value: [st] } = await call("getSignatureStatuses", [[sig]]);
  if (st?.err) throw new Error("failed on chain: " + JSON.stringify(st.err));
  if (st && (st.confirmationStatus === "confirmed" || st.confirmationStatus === "finalized")) break;
  const height = await call("getBlockHeight", [{ commitment: "confirmed" }]);
  if (height > s.lastValidBlockHeight) throw new Error("expired: quote again");
  await sleep(1000);
}
console.log("Signature:", sig, "got at least", s.minAmountOut);
```

Amounts are decimal strings in base units: use `BigInt`. The router fee is already inside `destAmountOut` and `minAmountOut`. On expiry or an on-chain slippage failure (`Custom:6004`), quote again; never re-sign the old message.

Reference, with retries, every refusal and a complete client: https://carbium.sh/docs#quote and https://carbium.sh/docs#swap

---

## 4. Carbon Stream (gRPC)

### Endpoint
```bash
https://services.carbium.sh:9443
Metadata: x-token: YOUR_KEY
```

Yellowstone-compatible gRPC stream: slots, accounts and transactions matching your filters. It is gRPC only, with the same key as RPC sent as `x-token` metadata (`x-api-key` and `?api-key=` are not read here). It needs a paid plan and the gRPC scope on the key.

- Send the whole Subscribe request with the open: a stream with no request within 10 seconds is closed.
- Account filters name their accounts (`account: [...]`); follow wallets with `transactions.accountInclude`.
- There is no startup snapshot: load current state over RPC first.
- Ping every 10 s on the stream and set the receive limit to 64 MiB.

### TypeScript - Transaction Subscription (`@triton-one/yellowstone-grpc` v8)
```typescript
// npm i @triton-one/yellowstone-grpc@8 @solana/kit
import Client, { CommitmentLevel } from "@triton-one/yellowstone-grpc";
import { getBase58Decoder } from "@solana/kit";

const ENDPOINT = "https://services.carbium.sh:9443";
const KEY = process.env.CARBIUM_KEY;              // full key, never the c_serv_xxxx prefix
const b58 = getBase58Decoder();

// Every map and list must be present (the TS type requires it); empty ones are not sent on the wire.
const EMPTY = { accounts: {}, slots: {}, transactions: {}, transactionsStatus: {}, blocks: {},
                blocksMeta: {}, entry: {}, accountsDataSlice: [], blockFooter: {} };

const REQUEST = {
  ...EMPTY,
  commitment: CommitmentLevel.CONFIRMED,
  slots: { s: { filterByCommitment: true } },
  transactions: { pool: { vote: false, failed: false, accountExclude: [], accountRequired: [],
    accountInclude: ["675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"] } },
};

const client = new Client(ENDPOINT, KEY, { grpcMaxDecodingMessageSize: 64 * 1024 * 1024 });
await client.connect();
const stream = await client.subscribe(REQUEST);                    // a refused key throws here; other refusals end the stream
const pinger = setInterval(() => stream.write({ ...EMPTY, ping: { id: 1 } }), 10_000);
stream.on("data", (u) => {
  if (u.ping || u.pong) return;                                   // server ping every 15 s; pong answers ours
  if (u.transaction) {
    const t = u.transaction.transaction;
    console.log("tx", u.transaction.slot, b58.decode(t.signature), t.meta?.err ? "failed" : "ok");
  }
});
stream.on("error", (e) => { clearInterval(pinger); console.error(e); }); // reconnect with backoff
stream.on("end", () => clearInterval(pinger));
```

Reference, with covered programs, every status and a reconnecting client: https://carbium.sh/docs#stream

---

## Common Token Mints

| Token | Mint Address |
|-------|-------------|
| SOL | `So11111111111111111111111111111111111111112` |
| USDC | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` |
| USDT | `Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB` |

---

## Production Requirements

### Timeout Guidelines
- RPC read calls: 5-10 seconds
- Swap quote: 3-5 seconds
- Transaction confirmation: 30-60 seconds (with polling)

### Retry with Backoff
- Retry only what waiting can fix: a 429, a 5xx on a read, a network error. Never loop on a 4xx.
- Wait the larger of the server's hint (`retry-after-ms`, else `Retry-After`) and an exponential backoff, plus random jitter. Stop after a few attempts.
- **Critical:** never auto-retry `sendTransaction`. Check `getSignatureStatuses` first, and resend only the same signed bytes until the block height passes `lastValidBlockHeight`.

### Stream Reconnection
Reconnect WebSocket and Carbon Stream connections with exponential backoff and jitter, resubscribe everything, and re-read state over RPC.

### Latency Optimization Tips
- `sendTransaction` with `skipPreflight: true` costs fewer credits and has the higher send rate
- Pre-build transaction templates
- Reuse one keep-alive connection for RPC and one socket for many subscriptions

---

## Failure Handling Matrix

| Failure Type | Action |
|-------------|--------|
| Quote: `-32051` `no route` (HTTP 200) | No path for this pair and size: act on `error.data.why`; change the pair or amount; do not loop faster than every 30 s |
| Swap: `-32095` quote unknown or expired | Quote again |
| Simulation failure | Do NOT send - inspect, log, alert |
| sendTransaction failure | Check getSignatureStatuses first |
| Tx not confirmed | Poll with timeout; quote or rebuild after `lastValidBlockHeight` passes |
| Stream disconnect | Reconnect with exponential backoff |
| HTTP 429 rate limit | Wait `retry-after-ms` plus jitter; retry |

## HTTP Error Codes

| Code | Meaning | Action |
|------|---------|--------|
| 401 | The key is refused: `unknown api key` (send the full key, not the prefix), the key is not enabled for this service, or it is suspended, revoked or disabled | Fix the key or turn on its scope on the dashboard. Do not retry |
| 402 | `-32002` `credits exhausted`: the remaining credits cannot cover the call | Do not retry: renew or buy a plan on https://carbium.sh/ |
| 403 | The caller's IP is not on the key's allowlist; or `-32050` `module not enabled for this account` (quotes need the Quote module); on WebSocket, the key is not enabled for websocket | Add the address, the module or the scope. Do not retry unchanged |
| 429 | `-32005` rate limit or capacity; or `CREDITS_PENDING` (credits still loading on this node) | Wait `retry-after-ms` plus jitter, then retry. For `CREDITS_PENDING`, do not buy anything |
| gRPC status (not HTTP) | UNAUTHENTICATED: key refused or no gRPC scope. PERMISSION_DENIED: the plan has no stream, or the filter is not served | Fix the key, scope, plan or filter. Do not retry |

Every other code, with the action for each: https://carbium.sh/docs#errors

---

## Architecture Concepts

- **One host, one key:** RPC, WebSocket and quotes on `services.carbium.sh` (port 443), Carbon Stream on port 9443.
- **Commitment Levels:** `processed` (fastest, rollback risk) -> `confirmed` (recommended) -> `finalized` (guaranteed, slowest)

---

## Environment Variables
```env
CARBIUM_KEY=your_carbium_key
```

## Reference Links
- Full reference for agents: https://carbium.sh/skill.md
- Reference docs: https://carbium.sh/docs
- Endpoints: https://carbium.sh/docs#endpoints
- Auth: https://carbium.sh/docs#auth
- Limits: https://carbium.sh/docs#limits
- Account and keys: https://carbium.sh/docs#account
- Moving from another provider: https://carbium.sh/docs#migrate
- Plans: https://carbium.sh/v1/plans
- llms.txt: https://carbium.sh/llms.txt
- Guides: https://carbium.io/docs/
- Dashboard and API keys: https://carbium.sh/
- Blog: https://carbium.io/blog
- Discord: https://discord.gg/82y3FXCqWw
- X: https://x.com/carbiumio
