services

Solana TypeScript SDK

v0.1.1@carbium/sdknpm install @carbium/sdkGitHubnpm
Libraries

TypeScript

A typed TypeScript client for every Carbium service: RPC, DAS, WebSocket, Carbon Stream, quote and swap, webhooks, the account API, DCA and the token API. It runs on Node and in browsers and has no runtime dependencies.

The package is @carbium/sdk. The examples read a service key from CARBIUM_KEY.

Install

The package runs on Node 22.12 or later and in browsers, as ESM or CJS, with no runtime dependencies. Running a .ts file directly with node main.ts, as these examples do, needs Node 22.18 or later. Carbon Stream is Node only and needs the stock Yellowstone client installed beside it; in Node the ws package lets the WebSocket client send the key in a header.

typescript · npm.sh
npm install @carbium/sdknpm install @triton-one/yellowstone-grpc   # Carbon Stream, Node onlynpm install ws                             # WebSocket key in the x-api-key header, Node only

Key and first call

A service key (c_serv_...) comes from the dashboard at carbium.sh. createCarbium takes it once and every call carries it; without a key the call is refused with 401, which the catch prints.

typescript · main.ts
import { createCarbium, isCarbiumError } from '@carbium/sdk'const carbium = createCarbium({ apiKey: process.env.CARBIUM_KEY })try {  const { context, value } = await carbium.rpc.getLatestBlockhash()  console.log('blockhash', value.blockhash, 'valid until block height', value.lastValidBlockHeight, 'at slot', context.slot)} catch (error) {  if (!isCarbiumError(error)) throw error  console.log(error.kind, error.httpStatus, error.code, error.reason, error.message)}

RPC and DAS

carbium.rpc holds the Solana methods, each taking its positional params as on the wire. carbium.das holds the DAS methods, each taking one object in Helius field names.

typescript · main.ts
import { createCarbium } from '@carbium/sdk'const mint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // USDCconst carbium = createCarbium({ apiKey: process.env.CARBIUM_KEY })const asset = await carbium.das.getAsset({ id: mint })const metadata = asset.content?.['metadata'] as { name?: string; symbol?: string } | undefinedconst { value: supply } = await carbium.rpc.getTokenSupply(mint)console.log(metadata?.symbol, supply.uiAmountString, supply.decimals)

WebSocket

carbium.socket opens a subscription client on the same key, with one method per served subscription; it binds every live subscription again after a reconnect and calls onReseed so you re-read what you may have missed. By default the key travels in the WebSocket subprotocol. With the ws package and carrier: 'header' it goes in the x-api-key header. onFatal fires once when the socket stops for good.

typescript · main.ts
import { createCarbium } from '@carbium/sdk'import WebSocket from 'ws'const wallet = '5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9'const carbium = createCarbium({ apiKey: process.env.CARBIUM_KEY })const socket = carbium.socket({  WebSocket,  carrier: 'header',  onFatal: (error) => console.error(error.kind, error.code, error.message),})const sub = socket.logsSubscribe({ mentions: [wallet] }, (n) => {  console.log(n.context.slot, n.value.signature, n.value.err === null ? 'ok' : 'failed')}, { commitment: 'confirmed' })console.log('subscription', await sub.ready)await new Promise((resolve) => setTimeout(resolve, 10_000))await sub.unsubscribe()socket.close()

Carbon Stream

CarbiumStream.connect opens Carbon Stream, Yellowstone gRPC on port 9443, through the stock @triton-one/yellowstone-grpc client, with a key that has the grpc scope on a plan with streams. It checks the server against the system's CA certificates, so a slim container image needs the ca-certificates package or SSL_CERT_FILE set to a CA bundle. The object carries the seven unary calls such as getSlot, and subscribeWithReconnect(filters, { onUpdate, onReseed }) keeps one subscription open across reconnects.

typescript · main.ts
import { CarbiumStream } from '@carbium/sdk/stream'const stream = await CarbiumStream.connect({ apiKey: process.env.CARBIUM_KEY ?? '' })console.log('slot', (await stream.getSlot()).slot)

Quote, swap and prices

carbium.quote.quote prices a swap in base units and returns a quoteId, and carbium.quote.swap turns it into one unsigned transaction, base64, that the user's own wallet signs. carbium.quote.prices reads USD prices for a list of mints.

typescript · main.ts
import { createCarbium } from '@carbium/sdk'const SOL = 'So11111111111111111111111111111111111111112'const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'// The wallet that would sign and pay the fees. Put your own public key here.const userPubkey = '5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9'const carbium = createCarbium({ apiKey: process.env.CARBIUM_KEY })const quote = await carbium.quote.quote({ src_mint: SOL, dst_mint: USDC, amount_in: '10000000', slippage_bps: 50 })const swap = await carbium.quote.swap({ quote_id: quote.quoteId, user_pubkey: userPubkey })// swap.transaction is base64: decode it as a VersionedTransaction and sign it with your own wallet.console.log(quote.destAmountOut, swap.minAmountOut, swap.lastValidBlockHeight)const table = await carbium.quote.prices({ mints: [SOL, USDC] })console.log(table.solUsd, table.rows)

Webhooks

verifyWebhook checks a delivery's webhook-signature header, an HMAC-SHA256 of webhook-id.webhook-timestamp.body under the webhook's whsec_ secret, and returns its events. In a receiver, pass the raw body bytes as they arrived and the secret from CARBIUM_WEBHOOK_SECRET; this example signs a sample delivery with a made-up secret.

typescript · main.ts
import { createHmac, randomBytes } from 'node:crypto'import { verifyWebhook } from '@carbium/sdk/webhooks'const secret = `whsec_${randomBytes(24).toString('base64')}`const timestamp = String(Math.floor(Date.now() / 1000))const body = Buffer.from(JSON.stringify([{ slot: 0, blockTime: Number(timestamp), indexWithinBlock: 0, signature: '1'.repeat(64), err: null, status: { Ok: null }, test: true }]))const webhookId = `evt_test_${randomBytes(8).toString('hex')}`const key = Buffer.from(secret.slice('whsec_'.length), 'base64')const signature = createHmac('sha256', key).update(`${webhookId}.${timestamp}.`).update(body).digest('base64')const headers = { 'webhook-id': webhookId, 'webhook-timestamp': timestamp, 'webhook-signature': `v1,${signature}` }const events = await verifyWebhook(body, headers, secret)console.log(webhookId, events.length, events[0]?.test)

Account API

An account API key (c_acct_...), made on the dashboard and read from CARBIUM_ACCOUNT_KEY, runs the account by API: service keys, webhooks, usage and records. keys.list returns every service key's record, never its value.

typescript · main.ts
import { CarbiumAccount } from '@carbium/sdk/account'const account = new CarbiumAccount({ apiKey: process.env.CARBIUM_ACCOUNT_KEY ?? '' })const keys = await account.keys.list()for (const k of keys) console.log(k.key_id, k.name, k.scope.join(','), k.status)

Errors and retries

Every failure is a CarbiumError, checked with isCarbiumError: kind names the category (auth, credits, rate_limit, request, route, transport and others), httpStatus is 0 when nothing answered, code carries the JSON-RPC code or the API's error string, and retryable says whether the same request can change its answer. The services.carbium.sh client retries by itself, waiting the larger of the server's hint and 250 ms doubling to 4 s, at most 4 attempts unless the policy row says otherwise, and never retries sendTransaction, 400, 401, 402, 403 or an answer marked retryable: false; the account, DCA and token clients never retry and leave retryable and retryAfterMs for you to act on.

typescript · main.ts
import { createCarbium, isCarbiumError } from '@carbium/sdk'// retry: false turns retries off; { maxAttempts, maxHintMs } tightens them.const carbium = createCarbium({ apiKey: process.env.CARBIUM_KEY, retry: { maxAttempts: 2 } })try {  const { value } = await carbium.rpc.getBalance('5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9')  console.log('lamports', value)} catch (error) {  if (!isCarbiumError(error)) throw error  console.log(error.kind, error.httpStatus, error.code, error.reason, error.retryable, error.requestId)}

@carbium/sdk on npm · Source on GitHub · Cookbook · Carbium docs