# Carbium - Solana Infrastructure Skill

> You are integrating with Carbium, a bare-metal Solana infrastructure provider.
> This file gives you everything needed to use Carbium's APIs programmatically.

## Products

| Product | URL | Purpose |
|---------|-----|---------|
| RPC | https://rpc-service.carbium.io | Solana JSON-RPC reads and writes |
| Standard WebSocket | wss://wss-rpc.carbium.io | Native Solana pubsub (account, slot, logs, program, signature subscriptions) |
| gRPC Stream | wss://grpc.carbium.io | Yellowstone streaming of transactions and accounts matching your filters (~22ms) |
| Swap API | https://api.carbium.io | 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 |
| Docs | https://docs.carbium.io | Full API reference & guides |

---

## API Key Management

- API keys: https://carbium.sh/
- Environment variables: `CARBIUM_RPC_KEY`, `CARBIUM_API_KEY`
- **Security:** Never embed keys client-side, avoid version control commits, rotate regularly

---

## Primary Use Cases

| Use Case | Product |
|----------|---------|
| Account data / balance reads | RPC |
| Transaction submission | RPC |
| Wallet application building | RPC + WSS + Swap API |
| Token swap quotes | Swap API |
| Programmatic swap transactions | Swap API |
| Submit a signed transaction as a Jito bundle | Swap API (older v1 bundle route) |
| Real-time wallet balance updates | Standard WSS (accountSubscribe) |
| Transaction confirmation (no polling) | Standard WSS (signatureSubscribe) |
| Program account monitoring | Standard WSS (programSubscribe) |
| Log-based event indexing | Standard WSS (logsSubscribe) |
| Slot / block clock monitoring | Standard WSS (slotSubscribe) |
| Full-block streaming | gRPC streaming |
| Transaction indexing (by account filter) | gRPC streaming |
| Wallet monitoring (all activity) | gRPC streaming |
| Portfolio tracking | RPC |

---

## 1. RPC - Solana JSON-RPC

### Endpoint
```bash
POST https://rpc-service.carbium.io/?apiKey=YOUR_RPC_KEY
```

### Authentication
The key goes in the query string:
```bash
https://rpc-service.carbium.io/?apiKey=YOUR_RPC_KEY
```

### Example - getBalance (curl)
```bash
curl -s "https://rpc-service.carbium.io/?apiKey=YOUR_RPC_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getBalance",
    "params": ["YOUR_WALLET_ADDRESS"]
  }'
```

### Example - sendTransaction (curl)
```bash
curl -s "https://rpc-service.carbium.io/?apiKey=YOUR_RPC_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "sendTransaction",
    "params": ["BASE64_SIGNED_TX", {"skipPreflight": true}]
  }'
```

### TypeScript / Node.js
```typescript
import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js";

const connection = new Connection(
  `https://rpc-service.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`,
  "confirmed"
);

const pubkey = new PublicKey("YOUR_WALLET_ADDRESS");
const balance = await connection.getBalance(pubkey);
console.log(`Balance: ${balance / LAMPORTS_PER_SOL} SOL`);
```

### JavaScript (fetch)
```javascript
const RPC = `https://rpc-service.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`;

const res = await fetch(RPC, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "getHealth"
  })
});

const data = await res.json();
```

### Python
```python
from solana.rpc.api import Client
from solders.pubkey import Pubkey
import os

rpc = Client(f"https://rpc-service.carbium.io/?apiKey={os.environ['CARBIUM_RPC_KEY']}")
pubkey = Pubkey.from_string("YOUR_WALLET_ADDRESS")
resp = rpc.get_balance(pubkey)
print(resp)
```

### Python (requests)
```python
import requests, os

res = requests.post(
    f"https://rpc-service.carbium.io/?apiKey={os.environ['CARBIUM_RPC_KEY']}",
    headers={"Content-Type": "application/json"},
    json={"jsonrpc": "2.0", "id": 1, "method": "getHealth"}
)

print(res.json())
```

### Rust
```rust
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use std::str::FromStr;

let url = format!(
    "https://rpc-service.carbium.io/?apiKey={}",
    std::env::var("CARBIUM_RPC_KEY").unwrap()
);
let client = RpcClient::new(url);
let pubkey = Pubkey::from_str("YOUR_WALLET_ADDRESS").unwrap();
let balance = client.get_balance(&pubkey).unwrap();
println!("Balance: {} lamports", balance);
```

### Supported Methods
All standard Solana JSON-RPC methods: `getBalance`, `getTransaction`, `getAccountInfo`, `sendTransaction`, `getSlot`, `getBlockHeight`, `getTokenAccountsByOwner`, `getSignatureStatuses`, etc.

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

---

## 2. Standard WebSocket - Solana Pubsub

### Endpoint
```bash
wss://wss-rpc.carbium.io/?apiKey=YOUR_RPC_KEY
```

Same API key as HTTP RPC. Native Solana subscription protocol - any Solana SDK works out of the box.

### WSS vs gRPC - When to Use Which

| | Standard WSS | gRPC / Yellowstone |
|---|---|---|
| **Protocol** | JSON-RPC over WebSocket | JSON-RPC over WS; protobuf over HTTP/2 |
| **What you get** | Account changes, slot updates, logs, signatures | Transactions and accounts matching your filters; blocks, entries and replay over HTTP/2 |
| **Best for** | Wallets, dApps, monitoring specific accounts | Indexers of the accounts and programs you filter on; full-block processing |

**Rule of thumb:** watching specific accounts or signatures -> WSS. Processing every transaction that touches accounts or programs you name -> gRPC (a transaction stream needs an account filter). Full blocks -> gRPC.

### Subscription Methods

| Method | What it streams | Use case |
|---|---|---|
| `accountSubscribe` | Account data changes | Wallet balance updates, PDA state |
| `programSubscribe` | All accounts owned by a program | DEX pool state |
| `signatureSubscribe` | Transaction confirmation | Confirm sent tx in real time |
| `logsSubscribe` | Transaction logs | Program event monitoring |
| `slotSubscribe` | New slot numbers | Block clock, liveness |
| `rootSubscribe` | Finalized slots | Finality tracking |
| `blockSubscribe` | Full block data | Block explorers |

### TypeScript - accountSubscribe

```typescript
import WebSocket from "ws";

const ws = new WebSocket(
  `wss://wss-rpc.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`
);

ws.on("open", () => {
  ws.send(JSON.stringify({
    jsonrpc: "2.0", id: 1,
    method: "accountSubscribe",
    params: [
      "YOUR_WALLET_ADDRESS",
      { encoding: "base64", commitment: "confirmed" },
    ],
  }));
});

ws.on("message", (raw) => {
  const msg = JSON.parse(raw.toString());
  if (msg.method === "accountNotification") {
    const { lamports } = msg.params.result.value;
    console.log(`Balance: ${lamports / 1e9} SOL`);
  }
});
```

### Python - accountSubscribe

```python
import asyncio, json, os
import websockets

async def watch_account(wallet: str):
    uri = f"wss://wss-rpc.carbium.io/?apiKey={os.environ['CARBIUM_RPC_KEY']}"
    async with websockets.connect(uri) as ws:
        await ws.send(json.dumps({
            "jsonrpc": "2.0", "id": 1, "method": "accountSubscribe",
            "params": [wallet, {"encoding": "base64", "commitment": "confirmed"}],
        }))
        ack = json.loads(await ws.recv())
        print(f"Subscribed: {ack['result']}")
        async for raw in ws:
            msg = json.loads(raw)
            if msg.get("method") == "accountNotification":
                val = msg["params"]["result"]["value"]
                print(f"Balance: {val['lamports'] / 1e9} SOL")

asyncio.run(watch_account("YOUR_WALLET_ADDRESS"))
```

### Using @solana/web3.js (Recommended)

```typescript
import { Connection, PublicKey } from "@solana/web3.js";

const connection = new Connection(
  `https://rpc-service.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`,
  {
    commitment: "confirmed",
    wsEndpoint: `wss://wss-rpc.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`,
  }
);

// Account changes
connection.onAccountChange(
  new PublicKey("YOUR_WALLET"),
  (info, ctx) => console.log(`Balance: ${info.lamports / 1e9} SOL`),
  "confirmed"
);

// Transaction confirmation
connection.onSignature(
  "YOUR_TX_SIG",
  (result) => console.log(result.err ? "Failed" : "Confirmed!"),
  "confirmed"
);

// Program account changes
connection.onProgramAccountChange(
  new PublicKey("PROGRAM_ID"),
  (info) => console.log(`Account ${info.accountId} changed`),
  "confirmed"
);

// Logs
connection.onLogs(
  new PublicKey("PROGRAM_ID"),
  (logs) => logs.logs.forEach(l => console.log(l)),
  "confirmed"
);
```

### Reconnection (Required for Production)

```typescript
import WebSocket from "ws";

class CarbiumWSS {
  private ws: WebSocket | null = null;
  private backoff = 1000;

  connect() {
    this.ws = new WebSocket(`wss://wss-rpc.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`);
    this.ws.on("open", () => { this.backoff = 1000; this.subscribe(); });
    this.ws.on("close", () => {
      setTimeout(() => this.connect(), this.backoff);
      this.backoff = Math.min(this.backoff * 2, 30_000);
    });
    this.ws.on("message", (raw) => this.handle(JSON.parse(raw.toString())));
    this.ws.on("error", (e) => console.error(e)); // close follows and reconnects
    // Keepalive ping every 30s
    setInterval(() => this.ws?.readyState === 1 && this.ws.ping(), 30_000);
  }

  private subscribe() { /* re-subscribe after every reconnect */ }
  private handle(msg: any) { /* route by msg.method */ }
}
```

### Unsubscribe

```typescript
// ws is the open socket from the accountSubscribe sample; SUBSCRIPTION_ID is the number the subscribe answered in result
ws.send(JSON.stringify({
  jsonrpc: "2.0", id: 2,
  method: "accountUnsubscribe", // slotUnsubscribe, logsUnsubscribe, etc.
  params: [SUBSCRIPTION_ID],
}));
```

---

## 3. Swap API - Quotes and Swap Transactions

### Get a Key
1. Get an API key at https://carbium.sh/

### Get a Quote
```bash
GET https://api.carbium.io/api/v2/quote
```

**Query Parameters:**
| Param | Required | Description |
|-------|----------|-------------|
| `src_mint` | Yes | Source token mint address |
| `dst_mint` | Yes | Destination token mint address |
| `amount_in` | Yes | Amount in smallest unit (lamports) |
| `slippage_bps` | Yes | Slippage tolerance in basis points |
| `user_account` | No | The wallet that will sign. With it, the response also carries the unsigned transaction in `txn` |

**Headers:**
```bash
X-API-KEY: YOUR_API_KEY
```

### Example - Get SOL->USDC Quote
```bash
curl -s "https://api.carbium.io/api/v2/quote?src_mint=So11111111111111111111111111111111111111112&dst_mint=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&amount_in=1000000000&slippage_bps=100" \
  -H "X-API-KEY: YOUR_API_KEY"
```

### Build a Swap Transaction
Send the quote request with `user_account`, the wallet that will sign:
```bash
GET https://api.carbium.io/api/v2/quote?src_mint=...&dst_mint=...&amount_in=...&slippage_bps=...&user_account=YOUR_WALLET_ADDRESS
```

The response carries a base64-encoded unsigned transaction in `txn`. Your app signs it and submits it. A response with no `txn` has no transaction to sign. A swap can pay rent to open token accounts: the output token's, any a route passes through and, the first time the router fee is paid in a token, Carbium's fee account for it (one-time, about 0.0015 SOL). Close empty accounts in your own wallet to get their rent back.

### Jito Bundle Endpoint (older v1 API)
```bash
GET https://api.carbium.io/api/v1/swap/bundle?signedTransaction=BASE58_SIGNED_TRANSACTION
X-API-KEY: YOUR_API_KEY
```
Takes your signed transaction (`signedTransaction`, base58). Submits as a Jito bundle. Jito refuses a transaction with no tip, and a `txn` from `/api/v2/quote` has none. The older `/api/v1/swap` builds one when you send `mevSafe=true`: it adds a Jito tip (100,000 lamports when read) and, on that route, a flat fee (350,000 lamports when read) in place of the 0.05% router fee. Required: fromMint, toMint, amount, slippage, owner, provider (a venue, e.g. raydium). The answer is data.base64Transaction. Read the signature on chain to know the result: the bundle route can answer an error after it has submitted.

### JavaScript - Full Swap Flow
```javascript
import { Connection, Keypair, VersionedTransaction } from "@solana/web3.js";

const API = "https://api.carbium.io/api/v2";
const KEY = process.env.CARBIUM_API_KEY;
// The wallet that signs: your own key as a JSON byte array, never sent to Carbium
const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(process.env.WALLET_SECRET_KEY)));

// 1. Get a quote and its unsigned transaction: user_account names the wallet
const quote = await fetch(
  `${API}/quote?src_mint=So11111111111111111111111111111111111111112&dst_mint=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&amount_in=1000000000&slippage_bps=100&user_account=${wallet.publicKey.toBase58()}`,
  { headers: { "X-API-KEY": KEY } }
).then(async r => {
  if (!r.ok) throw new Error(`Quote failed: ${r.status} ${await r.text()}`);
  return r.json();
});
if (!quote.txn) throw new Error("No transaction to sign");

// 2. Deserialize, sign and send via RPC
const tx = VersionedTransaction.deserialize(Buffer.from(quote.txn, "base64"));
tx.sign([wallet]);
const connection = new Connection(`https://rpc-service.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`, {
  commitment: "confirmed",
  wsEndpoint: `wss://wss-rpc.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`,
});
const sig = await connection.sendRawTransaction(tx.serialize(), { maxRetries: 3 });
const { value } = await connection.confirmTransaction(sig, "confirmed");
if (value.err) throw new Error(`Swap failed: ${JSON.stringify(value.err)}`);
console.log("Signature:", sig);
```

### Python
```python
import requests, os

API = "https://api.carbium.io/api/v2"
KEY = os.environ["CARBIUM_API_KEY"]

# Get quote
quote = requests.get(
    f"{API}/quote",
    params={
        "src_mint": "So11111111111111111111111111111111111111112",
        "dst_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        "amount_in": 1000000000,
        "slippage_bps": 100
    },
    headers={"X-API-KEY": KEY}
).json()

print(quote)
```

### Key Features
- Quote generation by the CQ1 engine
- Quotes across Solana liquidity

---

## 4. gRPC Streaming

### Endpoints
```bash
# WebSocket (TypeScript, JavaScript, Python)
wss://grpc.carbium.io/?apiKey=YOUR_RPC_KEY

# HTTP/2 gRPC (Rust)
https://grpc.carbium.io
Header: x-token: YOUR_RPC_KEY
```

Yellowstone-compatible streaming at ~22ms latency: transactions and accounts matching your filters; blocks, entries and replay over HTTP/2. A transaction stream needs an account filter. Uses the same API key as RPC.

### Rust Client
```rust
use yellowstone_grpc_client::{ClientTlsConfig, GeyserGrpcClient};

let mut client = GeyserGrpcClient::build_from_shared("https://grpc.carbium.io")?
    .x_token(Some("YOUR_RPC_KEY"))?
    .tls_config(ClientTlsConfig::new().with_native_roots())?
    .connect()
    .await?;
```

### TypeScript - Transaction Subscription
```typescript
import WebSocket from "ws";

const ws = new WebSocket(`wss://grpc.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`);

const PROGRAM_ID = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"; // Raydium AMM v4

ws.on("open", () => {
  ws.send(JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "transactionSubscribe",
    params: [{
      vote: false,
      failed: false,
      accountInclude: [PROGRAM_ID],
      accountExclude: [],
      accountRequired: []
    }, {
      commitment: "confirmed",
      encoding: "base64",
      transactionDetails: "full",
      maxSupportedTransactionVersion: 0
    }]
  }));
});

ws.on("message", (data) => {
  const msg = JSON.parse(data.toString());
  console.log(msg);
});
```

### Subscription Filter Fields

| Field | Type | Purpose |
|-------|------|---------|
| `vote` | bool | Include voting transactions |
| `failed` | bool | Include failed transactions |
| `accountInclude` | string[] | At least one listed account involved |
| `accountExclude` | string[] | Exclude these accounts |
| `accountRequired` | string[] | All listed accounts must be present |

### Unsubscribe
```json
{"jsonrpc": "2.0", "id": 2, "method": "transactionUnsubscribe", "params": [SUBSCRIPTION_ID]}
```

---

## 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)

### Exponential Backoff Retry
```typescript
const delay = (ms: number) => new Promise(r => setTimeout(r, ms));

async function withRetry<T>(fn: () => Promise<T>, retries = 3, baseMs = 300): Promise<T> {
  for (let i = 0; i < retries; i++) {
    try { return await fn(); }
    catch (e) {
      if (i === retries - 1) throw e;
      await delay(baseMs * 2 ** i + Math.random() * 100);
    }
  }
  throw new Error("unreachable");
}
```

**Critical:** Check `getSignatureStatus` before retrying `sendTransaction` to avoid duplicate sends.

### Stream Reconnection
```typescript
import WebSocket from "ws";

// Resolves when the socket closes; rejects on a connection error
function connect(): Promise<void> {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(`wss://wss-rpc.carbium.io/?apiKey=${process.env.CARBIUM_RPC_KEY}`);
    ws.on("open", () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" })));
    ws.on("message", (raw) => console.log(JSON.parse(raw.toString())));
    ws.on("close", () => resolve());
    ws.on("error", reject);
  });
}

async function connectWithReconnect() {
  let backoff = 1000;
  while (true) {
    try {
      await connect();
      backoff = 1000; // the socket had opened, so start the wait over
    } catch (e) {
      console.error(e);
    }
    await new Promise((r) => setTimeout(r, backoff));
    backoff = Math.min(backoff * 2, 30_000);
  }
}

connectWithReconnect();
```

### Latency Optimization Tips
- `skipPreflight: true` saves ~200ms
- Pre-build transaction templates
- WebSocket keepalive ping every 30 seconds

---

## Failure Handling Matrix

| Failure Type | Action |
|-------------|--------|
| Quote: `no_route` or `route computation failed` | No route right now for this pair and amount: back off, then change the pair or amount; do not retry in a loop |
| Quote: no `txn` | No transaction to sign: retry, or change the amount |
| Simulation failure | Do NOT send - inspect, log, alert |
| sendTransaction failure | Check getSignatureStatus first |
| Tx not confirmed | Poll with timeout; verify blockhash |
| Stream disconnect | Reconnect with exponential backoff |
| HTTP 429 rate limit | Immediate backoff; retry after delay |

## HTTP Error Codes

| Code | Meaning | Action |
|------|---------|--------|
| 400 | Missing or invalid parameter | Read the message |
| 401 | Swap API: missing key. RPC: invalid key. gRPC WebSocket: a key whose plan has no gRPC is refused at the handshake | Check the key. On gRPC, read the message. Plans and keys: https://carbium.sh/ |
| 403 | Swap API: invalid key. RPC: key not in `?apiKey=` | Read the message |
| gRPC status 7 (not HTTP) | gRPC HTTP/2: `PERMISSION_DENIED` when the key's plan does not include that stream, or for blocks, entries or replay it does not include | Read the message. Plans and keys: https://carbium.sh/ |
| 422 | `no_route`: no route for this pair and amount | Change the pair or amount |
| 429 | Rate limit exceeded | Backoff + retry |
| 500 | Server error | Retry after 1 second |
| 503 | Temporary unavailability | Exponential backoff retry |

---

## Architecture Concepts

- **CQ1 Engine:** Decoupled write/read paths, binary-native state, ~10ms chain-to-query latency
- **gRPC vs Shreds:** Carbium gRPC streams what your filters match (~22ms), and full blocks. Shreds require reassembly (~9ms individual). Negligible difference vs ~400ms Solana slot time
- **Gasless Swaps:** In Carbium Swap, when Gasless applies, swap without holding SOL for the network fee. The same transaction repays the fee payer, with no separate Gasless fee.
- **Commitment Levels:** `processed` (fastest, rollback risk) -> `confirmed` (recommended) -> `finalized` (guaranteed, slowest)

---

## Environment Variables
```env
CARBIUM_RPC_KEY=your_rpc_api_key
CARBIUM_API_KEY=your_swap_api_key
```

## Reference Links
- Ecosystem: https://docs.carbium.io/docs/the-carbium-ecosystem
- RPC Quick Start: https://docs.carbium.io/docs/quick-start-rpc
- Swap API Quick Start: https://docs.carbium.io/docs/quick-start-dex-api
- gRPC / Streaming: https://docs.carbium.io/docs/solana-grpc
- CQ1 Engine: https://docs.carbium.io/docs/cq1-engine-overview
- CQ1 Data Layer: https://docs.carbium.io/docs/cq1-data-layer
- API Recipes: https://carbium.io/docs/carbium-cookbook
- FAQ: https://docs.carbium.io/docs/faq
- Dashboard and API keys: https://carbium.sh/
- Blog: https://carbium.io/blog
- Discord: https://discord.gg/82y3FXCqWw
- X: https://x.com/carbiumio
