A Go client for every Carbium service, built on the standard library.
carbium-go is a typed Go client for Carbium's services: JSON-RPC with DAS, WebSocket subscriptions, quote, swap and prices, webhook checks, the account API, the DCA API and the token API, with Carbon Stream in a module of its own. It needs Go 1.26 or later. The examples read a service key from CARBIUM_KEY.
Install
The main module uses the standard library and one WebSocket package. Carbon Stream is its own module, fetched on its own, so gRPC stays out of the main module.
go mod init examplego get github.com/carbium-sh/carbium-go# only for Carbon Streamgo get github.com/carbium-sh/carbium-go/stream
Key and first call
A service key (c_serv_...) comes from the dashboard at carbium.sh. This program reads it from CARBIUM_KEY, asks for the latest blockhash and prints it, or prints the error's fields when the call is refused.
package mainimport ( "context" "errors" "fmt" "os" carbium "github.com/carbium-sh/carbium-go")func main() { c, err := carbium.NewClient(os.Getenv("CARBIUM_KEY"), nil) if err != nil { panic(err) } bh, err := c.GetLatestBlockhash(context.Background(), nil) var e *carbium.Error if errors.As(err, &e) { fmt.Println(e.Kind, e.HTTPStatus, e.Code, e.Reason, e.Message) return } fmt.Println("blockhash", bh.Value.Blockhash, "valid until block height", bh.Value.LastValidBlockHeight, "at slot", bh.Context.Slot)}
RPC and DAS
Every served method is a method on *carbium.Client that takes a context.Context first. Solana methods take positional params and an optional config pointer (nil leaves it out); DAS methods take one params struct, and Call sends any served method by name.
package mainimport ( "context" "encoding/json" "fmt" "os" carbium "github.com/carbium-sh/carbium-go")const mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" // USDCfunc main() { c, err := carbium.NewClient(os.Getenv("CARBIUM_KEY"), nil) if err != nil { panic(err) } ctx := context.Background() supply, err := c.GetTokenSupply(ctx, mint, nil) if err != nil { panic(err) } asset, err := c.GetAsset(ctx, carbium.GetAssetParams{ID: mint}) if err != nil { panic(err) } var metadata struct { Symbol string `json:"symbol"` } _ = json.Unmarshal(asset.Content["metadata"], &metadata) fmt.Println(metadata.Symbol, "supply", supply.Value.UIAmountString, "decimals", supply.Value.Decimals)}
WebSocket
ws.New connects on the first subscribe and binds every live subscription again after a reconnect. This program follows the transactions that mention one wallet with LogsSubscribe, prints the subscription id, then prints the signature of each transaction it sees for 10 seconds.
package mainimport ( "context" "fmt" "os" "time" carbium "github.com/carbium-sh/carbium-go" "github.com/carbium-sh/carbium-go/ws")const wallet = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9"func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() socket, err := ws.New(os.Getenv("CARBIUM_KEY"), nil) if err != nil { panic(err) } defer socket.Close() // closing the socket ends its subscriptions // Callbacks run on the socket's reader and must not block. sub, err := socket.LogsSubscribe(ws.LogsMentioning(wallet), &ws.CommitmentConfig{Commitment: carbium.CommitmentConfirmed}, func(n carbium.WithContext[carbium.LogsNotification]) { fmt.Println("signature", n.Value.Signature) }) if err != nil { panic(err) } id, err := sub.Ready(ctx) if err != nil { panic(err) } fmt.Println("subscription", id) <-ctx.Done() // follow for 10 seconds}
Carbon Stream
stream.Connect dials services.carbium.sh:9443 and sends the key as x-token metadata; the key needs the grpc scope and a plan with streams. Subscribe sends the whole filter set in its first message, and SubscribeWithReconnect adds pings, retries and a resume from the last slot for a long-running stream.
package mainimport ( "context" "fmt" "os" "github.com/carbium-sh/carbium-go/stream" "github.com/carbium-sh/carbium-go/stream/geyserpb")func main() { sc, err := stream.Connect(os.Getenv("CARBIUM_KEY"), nil) if err != nil { panic(err) } defer sc.Close() ctx, cancel := context.WithCancel(context.Background()) defer cancel() sub, err := sc.Subscribe(ctx, stream.Filters{Slots: map[string]*geyserpb.SubscribeRequestFilterSlots{"s": {}}}) if err != nil { panic(err) } for { u, err := sub.Recv() if err != nil { panic(err) } if s := u.GetSlot(); s != nil { fmt.Println("slot", s.GetSlot()) return } }}
Quote, swap and prices
Prices returns USD prices for a list of mints. Quote takes amounts in base units as strings, and Swap builds from the quote id one unsigned transaction that the user's own wallet signs; the quote and swap calls need the account's quote module and a key with the quote scope.
package mainimport ( "context" "fmt" "os" carbium "github.com/carbium-sh/carbium-go")const ( sol = "So11111111111111111111111111111111111111112" usdc = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" // The wallet that would sign and pay the fees. Put your own public key here. userPubkey = "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9")func main() { c, err := carbium.NewClient(os.Getenv("CARBIUM_KEY"), nil) if err != nil { panic(err) } ctx := context.Background() prices, err := c.Prices(ctx, carbium.PricesParams{Mints: []string{sol, usdc}}) if err != nil { panic(err) } fmt.Println("SOL in USD", prices.SolUSD) quote, err := c.Quote(ctx, carbium.QuoteParams{SrcMint: sol, DstMint: usdc, AmountIn: "10000000", SlippageBps: 50}) if err != nil { panic(err) } swap, err := c.Swap(ctx, carbium.SwapParams{QuoteID: quote.QuoteID, UserPubkey: userPubkey}) // the quote id lasts 30 seconds if err != nil { panic(err) } fmt.Println("out", quote.DestAmountOut, "min out", swap.MinAmountOut, "valid until block height", swap.LastValidBlockHeight) // swap.Transaction is base64. Decode it as a versioned transaction and sign it with your own wallet. fmt.Println("unsigned transaction,", len(swap.Transaction), "base64 characters")}
Webhooks
webhooks.Verify checks a delivery's signature over the raw body bytes and returns its events. This program signs a sample delivery with a made-up whsec_ secret, verifies it, then shows a different body refused with no_match. In your receiver, read the secret from CARBIUM_WEBHOOK_SECRET and pass the body bytes exactly as they arrived. A failed check is a *carbium.Error of kind webhook with Reason missing_header, bad_timestamp, stale, bad_secret, no_match or bad_json; the webhook-id header stays the same across retries, so dedupe on it.
package mainimport ( "crypto/hmac" "crypto/sha256" "encoding/base64" "fmt" "time" "github.com/carbium-sh/carbium-go/webhooks")func main() { // A made-up secret and a sample delivery. In your receiver, use CARBIUM_WEBHOOK_SECRET and the raw body bytes. key := []byte("a made-up webhook secret") secret := "whsec_" + base64.StdEncoding.EncodeToString(key) id, stamp := "evt_test_1", fmt.Sprint(time.Now().Unix()) body := []byte(`[{"slot":0,"blockTime":null,"indexWithinBlock":0,"err":null,"test":true}]`) mac := hmac.New(sha256.New, key) mac.Write([]byte(id + "." + stamp + "." + string(body))) headers := map[string]string{"webhook-id": id, "webhook-timestamp": stamp, "webhook-signature": "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil))} events, err := webhooks.Verify(body, headers, secret, nil) if err != nil { panic(err) } fmt.Println(id, len(events), "event, test", events[0].Test) _, err = webhooks.Verify([]byte(`[{"slot":1}]`), headers, secret, nil) fmt.Printf("another body: %+v\n", err) // %+v adds the fields: reason="no_match"}
Account API
account.New takes an account API key (c_acct_..., made on the dashboard) from CARBIUM_ACCOUNT_KEY and refuses a service key. Account calls cost no credits and none is retried; this program lists the account's service keys, which needs the keys:read scope.
package mainimport ( "context" "fmt" "os" "github.com/carbium-sh/carbium-go/account")func main() { a, err := account.New(os.Getenv("CARBIUM_ACCOUNT_KEY"), nil) if err != nil { panic(err) } keys, err := a.Keys.List(context.Background()) if err != nil { panic(err) } for _, k := range keys { fmt.Println(k.KeyID, k.Tier, k.Status, k.Scope) }}
Errors and retries
Every failure is a *carbium.Error, read with errors.As: Kind is its category, HTTPStatus the status (0 when nothing answered), Code the JSON-RPC or close code, Reason the service's reason, Message its text, and Retryable says whether sending the same request again can help. Most calls to services.carbium.sh make at most 4 attempts, waiting the longer of the server's hint and 250 ms doubling to 4 s; SendTransaction, 400, 401, 402, 403 and answers marked retryable: false are never retried, and the account, DCA and token clients never retry.
package mainimport ( "context" "errors" "fmt" "os" carbium "github.com/carbium-sh/carbium-go")func main() { // MaxAttempts 1 turns retries off; 0, the default, keeps the published retry rules. c, err := carbium.NewClient(os.Getenv("CARBIUM_KEY"), &carbium.Options{MaxAttempts: 1}) if err != nil { panic(err) } _, err = c.GetBalance(context.Background(), "not-a-public-key", nil) var e *carbium.Error if errors.As(err, &e) { fmt.Println(e.Kind, e.HTTPStatus, e.Code, e.Reason, e.Message) fmt.Println("retryable", e.Retryable, "wait", e.RetryAfter, "request id", e.RequestID) }}
carbium-go on pkg.go.dev · carbium-go/stream on pkg.go.dev · carbium-sh/carbium-go on GitHub · Cookbook · Docs