# Solana Python SDK

## Python

A typed Python client for every Carbium service, with a blocking client and an asyncio client.

carbium is the Python package for Carbium's services. It has a blocking client and an asyncio client for RPC and DAS, WebSocket, Carbon Stream, quote and swap, webhooks, the account API, DCA and tokens. It needs Python 3.11 or later. The examples read a service key from CARBIUM_KEY.

### Install

`pip install carbium` installs the package with its two dependencies, httpx and websockets. Carbon Stream needs the stream extra, which adds grpcio and protobuf.

```
pip install carbium
# Carbon Stream (Yellowstone gRPC)
pip install 'carbium[stream]'
```

### Key and first call

`Carbium` is the blocking client. Pass it the service key from the environment. It sends the key in the x-api-key header, never in a URL.

```
import os

from carbium import Carbium

WALLET = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9"

with Carbium(os.environ["CARBIUM_KEY"]) as carbium:
    answer = carbium.get_balance(WALLET, {"commitment": "confirmed"})

print(answer["value"], "lamports at slot", answer["context"]["slot"])
```

### Async

`AsyncCarbium` has the same calls for asyncio. Each one is awaited.

```
import asyncio
import os

from carbium import AsyncCarbium

WALLET = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9"


async def main() -> None:
    async with AsyncCarbium(os.environ["CARBIUM_KEY"]) as carbium:
        answer = await carbium.get_balance(WALLET, {"commitment": "confirmed"})
    print(answer["value"], "lamports at slot", answer["context"]["slot"])


asyncio.run(main())
```

### RPC and DAS

Solana methods take their params in wire order and have snake case names. DAS methods take their fields by name. `rpc()` calls any served method by its wire name, and `batch()` sends up to 100 calls in one request.

```
import os

from carbium import Carbium

MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"  # USDC

with Carbium(os.environ["CARBIUM_KEY"]) as carbium:
    asset = carbium.get_asset(id=MINT)
    supply = carbium.get_token_supply(MINT)["value"]

metadata = (asset.get("content") or {}).get("metadata") or {}
print(metadata.get("symbol"), supply["uiAmountString"])
```

### WebSocket

`CarbiumSocket` runs subscriptions on asyncio. It has one call for each of the eight served subscriptions and sends the key in the x-api-key header. It reconnects and binds every live subscription again. The server replays nothing it sent while you were disconnected, so `on_reseed` runs after every reconnect for you to read state again.

```
import asyncio
import os

from carbium import CarbiumSocket

WALLET = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9"


async def main() -> None:
    async with CarbiumSocket(os.environ["CARBIUM_KEY"], on_fatal=print) as socket:
        sub = socket.logs_subscribe({"mentions": [WALLET]}, lambda n: print(n["context"]["slot"], n["value"]["signature"]), {"commitment": "confirmed"})
        print("subscription", await sub.ready)
        await asyncio.sleep(10)
        await sub.unsubscribe()


asyncio.run(main())
```

### Carbon Stream

`CarbiumStream` connects to services.carbium.sh:9443 with a key that has the grpc scope, on a plan that includes streams. `subscribe_with_reconnect` takes filters by their proto field names and calls `on_update` with each `SubscribeUpdate`. It reconnects on its own, and `on_update` must not block.

```
import asyncio
import os

from carbium import CarbiumStream


async def main() -> None:
    async with await CarbiumStream.connect(os.environ["CARBIUM_KEY"]) as stream:
        live = stream.subscribe_with_reconnect(
            {"slots": {"slots": {"filter_by_commitment": True}}},
            on_update=lambda u: print("slot", u.slot.slot) if u.HasField("slot") else None,
        )
        await asyncio.sleep(10)
        live.close()
        await live.done


asyncio.run(main())
```

### Quote, swap and prices

`quote` takes amounts as strings in base units and returns the route and a `quoteId`. `swap` builds one unsigned transaction from that `quoteId`, in base64, for the wallet at `user_pubkey` to sign. `prices` returns a USD table with one row per mint.

```
import os

from carbium import Carbium

SOL = "So11111111111111111111111111111111111111112"
USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
# The wallet that would sign and pay the fees. Put your own public key here.
USER_PUBKEY = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9"

with Carbium(os.environ["CARBIUM_KEY"]) as carbium:
    quote = carbium.quote(src_mint=SOL, dst_mint=USDC, amount_in="10000000", slippage_bps=50)
    swap = carbium.swap(quote_id=quote["quoteId"], user_pubkey=USER_PUBKEY)
    table = carbium.prices(mints=[SOL, USDC])

print(quote["destAmountOut"], swap["minAmountOut"], {row[0]: row[1] for row in table["rows"]})
print(swap["transaction"])  # base64, unsigned: your own wallet signs it
```

### Webhooks

`verify_webhook` checks a delivery's HMAC-SHA256 signature over webhook-id.webhook-timestamp.body, allowing 300 s of clock difference, and returns the events it carries. The example below signs a sample delivery offline with a made-up secret. In your receiver, pass the raw body bytes, the request headers and `os.environ["CARBIUM_WEBHOOK_SECRET"]`.

```
import base64
import hashlib
import hmac
import json
import secrets
import time

from carbium import verify_webhook

# A made-up secret for this sample. In your receiver: os.environ["CARBIUM_WEBHOOK_SECRET"].
secret = "whsec_" + base64.b64encode(secrets.token_bytes(24)).decode()

timestamp = str(int(time.time()))
event = {"slot": 0, "blockTime": int(timestamp), "signature": "1" * 64, "err": None, "test": True}
body = json.dumps([event], separators=(",", ":")).encode()
webhook_id = "evt_test_" + secrets.token_hex(8)
key = base64.b64decode(secret[len("whsec_"):])
signature = base64.b64encode(hmac.new(key, f"{webhook_id}.{timestamp}.".encode() + body, hashlib.sha256).digest()).decode()
headers = {"webhook-id": webhook_id, "webhook-timestamp": timestamp, "webhook-signature": "v1," + signature}

events = verify_webhook(body, headers, secret)
print(len(events), "event, test:", events[0]["test"])
```

### Account API

`CarbiumAccount` calls the account API on carbium.sh with an account key (c_acct_...) from the dashboard, read from CARBIUM_ACCOUNT_KEY. It has one call for each of the API's 53 operations, such as `keys_list`, `webhooks_create`, `usage_daily` and `account_balance`.

```
import os

from carbium import CarbiumAccount

with CarbiumAccount(os.environ["CARBIUM_ACCOUNT_KEY"]) as account:
    keys = account.keys_list()

print([(k["key_id"], k["prefix"], k["status"]) for k in keys])
```

### Errors and retries

Every failure raises `CarbiumError`. It carries `kind`, `http_status` (0 when nothing answered), `code`, `reason` and `message`, and `retryable` says whether sending the same request again could change the answer. The RPC client retries a call that got no answer, 425, 429, 503, every 502 and 504 the service does not mark as final, and the node errors that waiting can fix, such as a node still behind `min_context_slot`. Before each try it waits the server's hint or a backoff from 250 ms doubling to 4 s, whichever is longer, plus up to 250 ms of jitter, and it makes at most 4 tries in most cases. It never retries `send_transaction`, 400, 401, 402, 403 or answers marked retryable false. It refuses a method the services do not serve before sending it. `Carbium(retry=False)` turns retries off and `max_attempts` lowers the count. The account, DCA and token clients never retry.

```
import os

from carbium import Carbium, CarbiumError

carbium = Carbium(os.environ.get("CARBIUM_KEY"))
try:
    answer = carbium.get_latest_blockhash()
    value = answer["value"]
    print("blockhash", value["blockhash"], "valid until block height", value["lastValidBlockHeight"], "at slot", answer["context"]["slot"])
except CarbiumError as error:
    print(error.kind, error.http_status, error.code, error.reason, error.message)
```

[carbium on PyPI](https://pypi.org/project/carbium/) · [carbium-sh/carbium-py on GitHub](https://github.com/carbium-sh/carbium-py) · [Cookbook](https://github.com/carbium-sh/cookbook) · [Docs](https://carbium.sh/docs)
