# Solana Rust SDK

## Rust

An async Rust client for every Carbium service, built on tokio.

The `carbium` crate is an async Rust client for every Carbium service: RPC and DAS, WebSocket, Carbon Stream, quote, swap and prices, webhooks, and the account, DCA and token APIs. It runs on tokio. The examples read a service key from `CARBIUM_KEY` and pass it in `ClientOptions`.

### Install

Add the crate, tokio with a runtime and macros, and serde_json for the JSON values the examples pass. The crate's features are `rustls` (the default, TLS with the platform's certificate roots), `native-tls` (the system's TLS library instead, added with `--no-default-features --features native-tls`), `ws` (WebSocket subscriptions), `stream` (Carbon Stream) and `webhooks` (the webhook signature check).

```
cargo add carbium
cargo add tokio --features macros,rt-multi-thread
cargo add serde_json
```

### Key and first call

`Carbium::new` takes the service key from `ClientOptions` and posts to https://services.carbium.sh by default. It refuses an account key, and a call without a key is refused with 401.

```
use carbium::{Carbium, ClientOptions};

#[tokio::main]
async fn main() -> Result<(), carbium::Error> {
    let client = Carbium::new(ClientOptions {
        api_key: std::env::var("CARBIUM_KEY").ok(),
        ..Default::default()
    })?;
    let latest = client.get_latest_blockhash(None).await?;
    println!("blockhash {} at slot {}", latest.value.blockhash, latest.context.slot);
    Ok(())
}
```

### RPC and DAS

Solana methods take positional params, as on the wire. DAS methods take one params struct, built with `new()` from the required fields. `call` sends any served method by name and reads the answer as any serde type.

```
use carbium::{Carbium, ClientOptions, Commitment, CommitmentConfig, GetAssetParams};
use serde_json::{Value, json};

const WALLET: &str = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9";
const MINT: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; // USDC

#[tokio::main]
async fn main() -> Result<(), carbium::Error> {
    let client = Carbium::new(ClientOptions { api_key: std::env::var("CARBIUM_KEY").ok(), ..Default::default() })?;
    let mut config = CommitmentConfig::new();
    config.commitment = Some(Commitment::Confirmed);
    let balance = client.get_balance(WALLET, Some(&config)).await?;
    println!("lamports {} at slot {}", balance.value, balance.context.slot);
    let asset = client.get_asset(&GetAssetParams::new(MINT)).await?;
    let name = asset.content.as_ref().and_then(|c| c.get("metadata")).and_then(|m| m.get("name")).and_then(Value::as_str);
    println!("name {:?}", name);
    let slot: u64 = client.call("getSlot", Some(json!([{ "commitment": "confirmed" }]))).await?;
    println!("slot {slot}");
    Ok(())
}
```

### WebSocket

Turn on the `ws` feature with `cargo add carbium --features ws`. `client.socket` opens a socket on the same key, sent in the `x-api-key` handshake header; this example follows one wallet's transactions with `logs_subscribe` and waits up to 10 seconds for one notification.

```
use std::time::Duration;

use carbium::ws::Carrier;
use carbium::{Carbium, ClientOptions};
use serde_json::json;

const WALLET: &str = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9";

#[tokio::main]
async fn main() -> Result<(), carbium::Error> {
    let client = Carbium::new(ClientOptions { api_key: std::env::var("CARBIUM_KEY").ok(), ..Default::default() })?;
    let (socket, _events) = client.socket(Carrier::default())?;
    let mut sub = socket.logs_subscribe(json!({ "mentions": [WALLET] }), Some(json!({ "commitment": "confirmed" })))?;
    println!("subscription {}", sub.ready().await?);
    if let Ok(Some(n)) = tokio::time::timeout(Duration::from_secs(10), sub.next()).await {
        let n = n?;
        println!("slot {} signature {}", n.context.slot, n.value.signature);
    }
    sub.unsubscribe();
    Ok(())
}
```

### Carbon Stream

Turn on the `stream` feature with `cargo add carbium --features stream`. `CarbiumStream::connect` opens Yellowstone gRPC on https://services.carbium.sh:9443 with the key as x-token metadata. `subscribe_with_reconnect` reconnects on its own and yields `StreamEvent::Reseed` when you need to re-read state over RPC. The key needs the grpc scope and a plan with streams.

```
use carbium::stream::proto::SubscribeRequestFilterSlots;
use carbium::stream::{CarbiumStream, ReconnectOptions, StreamEvent, StreamFilters, StreamOptions};

#[tokio::main]
async fn main() -> Result<(), carbium::Error> {
    let key = std::env::var("CARBIUM_KEY").unwrap_or_default();
    let stream = CarbiumStream::connect(StreamOptions::new(key)).await?;
    println!("slot {}", stream.get_slot(None).await?.slot);
    let mut filters = StreamFilters::default();
    filters.slots.insert("s".into(), SubscribeRequestFilterSlots::default());
    let mut live = stream.subscribe_with_reconnect(&filters, ReconnectOptions::default())?;
    while let Some(event) = live.next().await {
        match event {
            StreamEvent::Update(update) => {
                println!("{:?}", update.update_oneof);
                break;
            }
            StreamEvent::Stopped(Some(error)) => return Err(error),
            StreamEvent::Stopped(None) => break,
            _ => {}
        }
    }
    Ok(())
}
```

### Quote, swap and prices

Quote and swap need the quote module on the account and a key with the quote scope. `quote` prices a swap in base units, `swap` returns one unsigned transaction, base64, for the user's own wallet to sign, and `prices` reads USD prices for a list of mints. The crate never signs or sends.

```
use carbium::{Carbium, ClientOptions, PricesParams, QuoteParams, QuoteParamsAmountIn, SwapParams};

const SOL: &str = "So11111111111111111111111111111111111111112";
const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
// The wallet that would sign and pay the fees. Put your own public key here.
const USER_PUBKEY: &str = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9";

#[tokio::main]
async fn main() -> Result<(), carbium::Error> {
    let client = Carbium::new(ClientOptions { api_key: std::env::var("CARBIUM_KEY").ok(), ..Default::default() })?;
    let params = QuoteParams::new(SOL, USDC, QuoteParamsAmountIn::Text("10000000".into()), 50);
    let quote = client.quote(&params).await?;
    println!("in {} out {} min {}", quote.src_amount_in, quote.dest_amount_out, quote.min_amount_out);
    let swap = client.swap(&SwapParams::new(quote.quote_id.clone(), USER_PUBKEY)).await?;
    // Base64. Decode it as a versioned transaction and sign it with your own wallet.
    println!("{} valid until block height {}", swap.transaction, swap.last_valid_block_height);
    let mut prices = PricesParams::new();
    prices.mints = Some(vec![SOL.to_string(), USDC.to_string()]);
    let table = client.prices(&prices).await?;
    println!("SOL {} USD, {} rows", table.sol_usd, table.rows.len());
    Ok(())
}
```

### Webhooks

Turn on the `webhooks` feature with `cargo add carbium --features webhooks`. `verify_webhook` checks a delivery's `webhook-signature` against the secret in `CARBIUM_WEBHOOK_SECRET` and returns its events. Pass the body bytes as they arrived; a failure is an error of kind `Webhook` with reason `missing_header`, `bad_timestamp`, `stale`, `bad_secret`, `no_match` or `bad_json`.

```
use carbium::webhooks::{VerifyOptions, verify_webhook};

/// Call from your HTTPS handler with the raw body bytes and the request's headers.
pub fn check(raw_body: &[u8], headers: &[(&str, &str)]) -> Result<(), carbium::Error> {
    let secret = std::env::var("CARBIUM_WEBHOOK_SECRET").unwrap_or_default();
    let events = verify_webhook(raw_body, headers, &secret, &VerifyOptions::default())?;
    println!("{} events, test {:?}", events.len(), events.first().and_then(|e| e.test));
    Ok(())
}
```

### Account API

`CarbiumAccount` takes an account key (`c_acct_`), here from `CARBIUM_ACCOUNT_KEY`, and calls the account API on carbium.sh. Its groups are `keys()`, `webhooks()`, `usage()`, `account()` and `modules()`. Calls cost no credits and are never retried.

```
use carbium::CarbiumAccount;
use carbium::account::AccountOptions;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let account = CarbiumAccount::new(AccountOptions::new(std::env::var("CARBIUM_ACCOUNT_KEY")?))?;
    let keys = account.keys().list().await?;
    let webhooks = account.webhooks().list().await?;
    println!("{} service keys, {} webhooks", keys.len(), webhooks.len());
    let balance = account.account().balance().await?;
    println!("credits remaining {}", balance.remaining);
    Ok(())
}
```

### Errors and retries

Every failure is a `carbium::Error` with `kind()`, `http_status()` (0 when nothing answered), `code()` (the JSON-RPC code or an HTTP API's error string), `reason()` and `message()`, plus `is_retryable()`, `retry_after_ms()` and `request_id()`. Keys never appear in its message, data or Debug output.

The client retries with the published policy: it waits the larger of the server's hint and 250 ms doubling to 4 s, plus up to 250 ms of jitter, for at most 4 attempts on most rows. A call with no answer, a 429, most 502, 503 and 504 answers and a few node errors, such as a block not available yet, are retried. `sendTransaction`, 400, 401, 402, 403, 413 and any answer marked `retryable: false` are never retried. `retry: None` sends each call once, and `RetryOptions` sets `max_attempts` and `max_hint_ms`.

```
use carbium::{Carbium, ClientOptions, RetryOptions};

#[tokio::main]
async fn main() -> Result<(), carbium::Error> {
    let client = Carbium::new(ClientOptions {
        api_key: std::env::var("CARBIUM_KEY").ok(),
        retry: Some(RetryOptions { max_attempts: Some(2), ..Default::default() }),
        ..Default::default()
    })?;
    match client.get_latest_blockhash(None).await {
        Ok(latest) => println!("blockhash {}", latest.value.blockhash),
        Err(e) => {
            let code = e.code().map(ToString::to_string).unwrap_or_default();
            println!("{} {} {} {} {}", e.kind(), e.http_status(), code, e.reason().unwrap_or(""), e.message());
        }
    }
    Ok(())
}
```

[carbium on crates.io](https://crates.io/crates/carbium) · [API reference on docs.rs](https://docs.rs/carbium) · [Source: carbium-sh/carbium-rs](https://github.com/carbium-sh/carbium-rs) · [Cookbook](https://github.com/carbium-sh/cookbook) · [Carbium docs](https://carbium.sh/docs)
