carbium
Typed async Rust client for Carbium's Solana services on services.carbium.sh: JSON-RPC (every served method, DAS included), the quote plane (quote, swap, prices, health), the account API, webhook signature checks, the DCA API on the dex, the token API, WebSocket subscriptions and Carbon Stream (Yellowstone gRPC). Built on tokio and reqwest, with addresses and signatures as strings, so the default features pull in no Solana crate.
The crate never holds a private key, signs or sends on its own: swap returns one unsigned transaction for your own
wallet to sign, and send_transaction takes bytes you signed. Every method the crate offers is served; what the
services do not serve is not here.
Carbon Stream, WebSocket subscriptions and webhook checks are features: cargo add carbium --features stream,ws,webhooks.
Quick start
A service key (c_serv_…) comes from the dashboard at carbium.sh. Without one the call reaches the door and is refused
with 401, which the quick start prints.
use ;
async
RPC, DAS and the quote plane
# async
A result number is a serde_json::Number: an integer stays exact (read it with as_u64), a fraction stays a
fraction. Token amounts and quote-plane amounts are decimal strings. Token scans (getTokenAccountsByOwner,
getTokenAccountsByDelegate), getProgramAccounts and getTransactionsForAddress walks are billed by what they read:
name a mint, keep limit small, and read the method notes at https://carbium.sh/skill.md before running one in a loop.
Swap: quote, build, sign with your own wallet, send
The quote plane needs the account's quote module (free plan) and a key with the quote scope.
# async
The same quote is also served as REST: client.cq1_quote(src_mint, dst_mint, amount_in, slippage_bps) gets
GET /cq1/quote with the key in x-api-key, and answers one object of strings (Cq1Quote).
Decode swap.transaction from base64, sign it with your own wallet (for example as a VersionedTransaction from
solana-sdk), encode it as base64 again and pass it to send_transaction with encoding: base64 and
skipPreflight: true, as above. Then poll
get_signature_statuses and resend the same bytes until the block height passes swap.last_valid_block_height. The
crate never retries send_transaction. Quote again (never re-sign the old message) when the blockhash expires or when
swap answers a route error that asks for a new quote (-32095, -32074, -32081 to -32083, -32096, -32093).
Errors and retries
Every failure is a carbium::Error:
| Method | Meaning |
|---|---|
kind() |
Auth, Credits, RateLimit, Request, Upstream, Node, Route, Transport (and Socket, Stream, Account, Dca, Tokens, Webhook for the other clients) |
http_status() |
the HTTP status, 0 when nothing answered |
code() |
the JSON-RPC code, or an HTTP API's error string |
reason() |
the door's error.data.reason |
is_retryable() |
whether waiting and sending the same request can change the answer |
retry_after_ms() |
the server's wait hint |
request_id() |
x-request-id, to quote to support |
data() |
error.data as served |
The retry policy is the one published in skill.md and applies to every HTTP call on services.carbium.sh: wait the larger of the server's hint
(retry-after-ms, else retryAfterMs in the error's data, else Retry-After) and 250 ms doubling to 4 s, plus up to 250 ms of jitter; a hint is never cut, and a hint over max_hint_ms (30 s by default) is not waited for: the error comes back at once with it in retry_after_ms();
at most 4 attempts unless the published row says otherwise (a scan index behind: about 6 from 100 ms).
sendTransaction, 401, 402 (credits exhausted), 403, bad params (apart from getTransactionsForAddress's -32602 "the walk read no history", which is retried), unknown methods and every answer marked
retryable: false are never retried. ClientOptions { retry: None, .. } turns retries off, and
RetryOptions { max_attempts, .. } lowers the attempt count. Keys never appear in error messages, data, Debug output
or URLs: an endpoint that carries a key is refused.
WebSocket subscriptions
Turn on the ws feature. A tokio runtime must be running.
#
# async
All eight served subscriptions have a method (account_subscribe, program_subscribe, logs_subscribe,
signature_subscribe, slot_subscribe, root_subscribe, slots_updates_subscribe, block_subscribe). The client
follows the server's close codes: it reconnects and binds every live subscription again after 1013, 1012, 1001 and
network drops, reconnects once after 1008 credits_exhausted, retries a 429 handshake after its Retry-After, and stops
with SocketEvent::Fatal on a key refusal. Nothing is replayed by the server after a disconnect: SocketEvent::Reseed
comes after every reconnect, with gap: true after stream_gap_reseed_required. signature_subscribe fires once;
after a reconnect, check get_signature_statuses. Dropping a Subscription ends it, and ending the last one closes
the socket. unsubscribe returns before its frame is necessarily written, so a program that exits at once may not
have told the server; closing the socket ends its subscriptions either way.
The key travels in the x-api-key handshake header by default (Carrier::Header); Carrier::Subprotocol sends it in
Sec-WebSocket-Protocol instead, the browsers' form. It never goes in the URL.
Carbon Stream (Yellowstone gRPC)
Turn on the stream feature. The key needs the grpc scope and a plan with streams (DEV and above).
#
# async
The key travels as x-token metadata, never in the URL. subscribe_with_reconnect sends the whole filter set in the
first message, pings every 10 s with never more than one pong outstanding, and follows the published rules: it stops on
UNAUTHENTICATED, PERMISSION_DENIED, INVALID_ARGUMENT, UNIMPLEMENTED and on RESOURCE_EXHAUSTED for exhausted credits;
it re-seeds on OUT_OF_RANGE and goes on live; any other end is retried after the larger of the table wait (2 s, 1 s
while the service is still loading, or the server's retry-after) and a backoff from 2 s doubling to 30 s, plus up to
1 s of jitter, reset after any data. At processed commitment it resumes from the last slot seen when the retained floor
(SubscribeReplayInfo) still holds it, and asks you to re-seed when it does not; a resume can replay one slot you
already saw, so dedupe on slot and signature. The seven filter kinds the service serves (accounts, slots, transactions,
transactions_status, blocks, blocks_meta, entry) are the only ones offered, and shapes it refuses are refused before
any call: cuckoo filters, token_accounts, include_update_parent, a bare transaction filter with nothing named, and
from_slot above processed commitment. The unary calls are get_slot, get_block_height, get_latest_blockhash,
is_blockhash_valid, get_version, ping and subscribe_replay_info; calls on one client run side by side.
subscribe opens one plain stream with no reconnect, which you can ping. Updates wait in a small queue (32 frames): a
slow reader slows the stream, and the service cuts a reader that takes nothing for 10 s. close() ends the events with
Stopped(None).
What the feature pulls in: the stock yellowstone-grpc-client 17.0.0 and yellowstone-grpc-proto 14.0.1, and through
them tonic 0.14 (with native TLS roots), prost and solana-pubkey; the message types are re-exported as
carbium::stream::proto. To build it needs nothing installed: the proto crate compiles its .proto files with a
vendored protoc (protoc-bin-vendored) at build time.
Webhooks
Turn on the webhooks feature: cargo add carbium --features webhooks.
#
#
Standard Webhooks: HMAC-SHA256 over webhook-id.webhook-timestamp.body with the secret's base64 after whsec_,
v1, entries in webhook-signature (two during a rotation), 300 s of clock tolerance, compared in constant time.
Header names match in any case; headers can be a reqwest::header::HeaderMap, a HashMap, a BTreeMap, or a list
of name and value pairs. A timestamp or clock that cannot be compared is refused as stale. A failure is an error of
kind Webhook with reason missing_header, bad_timestamp, stale, bad_secret, no_match or bad_json. Dedupe on
webhook-id: it stays the same across retries.
Account API
An account API key (c_acct_…, made on the dashboard) runs the account by API: service keys, webhooks, usage and
records. Calls cost no credits; 600 per 10 minutes per key. Nothing here is retried: a 429 comes back with
retry_after_ms.
# async
Groups: keys() (list, create, rotate, revoke, delete, rename, set_scope, set_caps, set_allowlist, set_limits),
webhooks() (list, get, deliveries, create, update, delete, rotate_secret, test), usage() (daily, per_key, load,
hourly, latency), account() (get, balance, invoices, payments, modules, crypto_intent), modules().enable_free,
self_record and activity. A raw key or webhook secret in an answer is a carbium::Secret: its Debug shows only the
prefix, and expose() gives the value. Payments, plan changes and making account keys stay on the dashboard.
DCA API
# async
Reads: quote, positions, history, position, health. Builders: open, update, withdraw, close. send
relays bytes the owner's wallet signed, once. Amounts travel as decimal strings. Server-side only: a browser page is
refused with forbidden_origin. Errors are kind Dca with the API's err string as code.
Token API
# async
Keyless, 300 requests a minute per client. These four are the token API's public routes; a lookup of a mint not indexed
yet is None. A token's symbol and name are '' until the mint is resolved.
Features and what the default build pulls in
The default build is the JSON-RPC client, the REST quote and the account, DCA and token clients on reqwest (rustls with
the platform's certificate roots, HTTP/2, the system proxy), serde, serde_json, serde_path_to_error, thiserror and
tokio's timer. webhooks adds hmac, sha2 and base64; ws adds tokio-tungstenite and futures-util; stream adds the Yellowstone gRPC client (see Carbon Stream). native-tls uses
the system's TLS library instead of rustls: default-features = false, features = ["native-tls"].
How answers are read
Results are typed from the published spec, and reading them is tolerant where that costs nothing. An extra field never
fails a call: open objects keep it in extra. An enum value this version does not know is kept as Other(String).
A field of the wrong type fails the call with an Upstream error whose message names the field path (for example
at `value.blockhash` ) and whose data() holds the raw answer; call::<serde_json::Value>() reads any answer
untyped. Generated structs and enums are #[non_exhaustive] so new fields and values can arrive without breaking a
build: build params and config structs with new(), which takes only the required fields, then set the optional ones.
Limits the crate checks before sending
Body 51,200 bytes; batch 1 to 100 calls with at most two permit methods; DAS only with DAS; scans, getSupply,
getLargestAccounts, the fee extras, getTransactionsForAddress and the quote plane never batch; a method the services
do not serve is refused before it is sent; token batch takes 1 to 500 mints.
Working on the crate
src/gen.rs is generated from the spec repo's openrpc.json: python3 scripts/generate.py <openrpc.json>, then
cargo fmt. Once per clone, point git at the hooks folder with git config core.hooksPath hooks: the leak check in
scripts/leak-check.sh then guards every upload, as it does in CI.
MIT. Issues: https://github.com/carbium-sh/carbium-rs/issues. Docs: https://carbium.sh/docs and https://carbium.sh/skill.md.