library / AI and blockchain / Solana agent kits / SI0121
ElizaOS chain state provider
A read-only ElizaOS provider that adds one line of Solana state to every prompt: the confirmed slot, the finalized slot, the gap between them and the epoch progress. A short cache and a shared in-flight read keep a busy chat to one refresh.
What the provider gives the model
An ElizaOS agent builds each prompt from its character, the message history and the output of its providers. A provider is an object with a name, a description and a get function that returns text. Whatever get returns lands in the prompt before the model writes a word, so a provider is the place for facts the model should hold at the start of every turn and should never have to ask for.
This one returns the chain's current state as one line: the confirmed slot, the finalized slot, the gap between them, and how far through the epoch the network is. A model holding that line can answer "is Solana moving" or "which epoch is it" with no tool call, and it can date any number it quotes. Without the line the model fills the gap from training data, which stops on a fixed day and knows nothing about the current slot.
The plugin only reads. It holds no wallet and builds no transaction. The endpoint serves sendTransaction, at 20 cells without preflight and 70 with it, so the boundary lives in your code and the endpoint will not enforce it. ElizaOS account plugin pairs a slot provider with an action that reads one account, and Solana commitment levels explains the commitment levels this provider reports.
One read for many turns
A provider runs on every turn, and an agent in a busy room can handle several messages in the same second. A slot lasts about 200 ms, yet the line the model sees does not need to be fresher than a couple of seconds. Three RPC calls per message would repeat one answer many times over.
The file keeps two variables at module level. cached holds the last text and the time it was read, and a call inside two seconds of that time gets the stored text. inflight holds the promise of a refresh that is still running, and a call that arrives meanwhile awaits the same promise. Ten turns in one moment cause one refresh of three calls. A quiet agent causes one refresh per turn at most.
The window is the constant TTL_MS. Raise it when the agent chats slowly. The text carries its own read time, so the model can see how old the line is and say so.
The provider file
One file. Node 24 runs the TypeScript directly and @solana/kit 8.6.0 is the only dependency. Set CARBIUM_KEY first; the file exits with a message when it is missing. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh.
// SI0121 · ElizaOS chain state provider// https://carbium.sh/library/si/elizaos-chain-state-provider// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// ElizaOS-style chain state provider on Carbium. Run: CARBIUM_KEY=... node main.tsimport { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key: string = process.env.CARBIUM_KEY ?? "";if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url, headers: { "x-api-key": key } }),);const TTL_MS = 2000;let cached: { at: number; text: string } | undefined;let inflight: Promise<string> | undefined;let reads = 0;// Three calls, each allowed to fail alone. Commitment is named on every call.async function read(): Promise<string> { reads++; const [c, f, e] = await Promise.allSettled([ rpc.getSlot({ commitment: "confirmed" }).send(), rpc.getSlot({ commitment: "finalized" }).send(), rpc.getEpochInfo({ commitment: "confirmed" }).send(), ]); const slot = (label: string, r: PromiseSettledResult<bigint>): string => r.status === "fulfilled" ? `${label} slot ${r.value}` : `${label} slot unavailable`; const gap = c.status === "fulfilled" && f.status === "fulfilled" ? ` (confirmed minus finalized ${c.value - f.value})` : ""; const epoch = e.status === "fulfilled" ? `epoch ${e.value.epoch}, ${Number((e.value.slotIndex * 1000n) / e.value.slotsInEpoch) / 10}% done` : "epoch unavailable"; return `Solana mainnet at ${new Date().toISOString()}: ${slot("confirmed", c)}, ${slot("finalized", f)}${gap}, ${epoch}.`;}// The provider shape: name, description, get() returning text for the prompt.export const chainStateProvider = { name: "CARBIUM_CHAIN_STATE", description: "Solana mainnet state read from Carbium: confirmed and finalized slot, epoch progress. A gap of 0 or 1 slots is normal; a negative gap of a slot or two means the two reads landed out of order.", get: async (_runtime?: unknown, _message?: unknown, _state?: unknown): Promise<{ text: string }> => { if (cached && Date.now() - cached.at < TTL_MS) return { text: cached.text }; inflight ??= read().finally(() => { inflight = undefined; }); const text = await inflight; cached = { at: Date.now(), text }; return { text }; },};if (import.meta.main) { // Three turns at once share one read; the fourth, after they finish, hits the cache. const burst = await Promise.all([1, 2, 3].map(() => chainStateProvider.get())); const later = await chainStateProvider.get(); console.log(burst[0]?.text); console.log(`chain reads after 4 turns: ${reads}`, later.text === burst[0]?.text ? "" : "(text changed)");}
run: node main.ts
The main block plays four turns without the framework. Three arrive together and one follows after they finish. Expect a line that starts Solana mainnet at, followed by the two slots, their gap and the epoch, and a last line chain reads after 4 turns: 1. That last line is the cache and the shared read at work.
The three calls go through Promise.allSettled, so each can fail alone. A call that fails turns into the word unavailable in its place in the line, and the other two still report. The agent keeps talking.
Confirmed, finalized and the gap
@solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, while the JSON-RPC server's own default is finalized. The file names the commitment on every call, so the line never depends on which default applies.
Since the Alpenglow switch, finalized trails processed by 0 to 1 slots, where it used to trail by about 32, so the printed gap, confirmed minus finalized, is small: usually 0 or 1. The two slot reads are separate requests answered at slightly different moments. When the finalized one is answered a slot or two later, the gap goes negative, and a run can print -1 or -2. A small negative gap is a timing artifact and says nothing about the chain.
Put that in the provider's description so the model treats the gap the same way. A model told only "finalized slot" tends to describe finalized as far behind, which was true before October and is wrong now.
What a refresh costs
Each refresh makes three calls: getSlot at confirmed, getSlot at finalized and getEpochInfo. The two slot reads are cached reads at 1 cell each. The rate limits for that class are calls per second per plan.
| Plan | Cached read class, req/s |
|---|---|
| Free | 5 |
| Dev | 30 |
| Business | 100 |
| Pro | 500 |
At one refresh every two seconds, the two slot reads ask for 1 req/s together, which sits inside every row of the table. Limits are per account and an account's keys share one budget, so a second agent on a second key draws on the same cells.
Reads that run past the plan's rate get a 429 with a retry-after hint. The provider does not retry. A retry would hold the turn open while the model waits for its prompt, and the next turn refreshes anyway. A 429 shows up as unavailable in the line.
Where it ends
- The line is a snapshot. By the time the model reads it, it can be two seconds old, and a long chat can quote it later. Anything the user needs exactly, such as a balance or a transaction status, needs a tool call that reads at that moment.
- It describes the network and says nothing about any account. A plain SOL wallet gets no accountSubscribe notification, so a live balance needs logsSubscribe with mentions plus getBalance.
- It polls. A slot subscription would push the number, and slotSubscribe opens at 5 credits and then costs 20 credits per MiB sent. A slot its leader never produced sends no notification, and a slot notified at processed can still end up skipped when its fork is dropped. For a chat agent, polling at the cache window is the simpler design.
- Provider text goes into the prompt, so keep it to numbers the code computed. Never paste a string read from chain data into it, because account contents are chosen by whoever created the account.
- The file does not import the framework. Registering it, typing it against your @elizaos/core version and choosing which agents load it are steps you do.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The line shows confirmed slot unavailable on many turns. | The reads are hitting a 429. Limits are per account and an account's keys share one budget, so look for other consumers, then raise TTL_MS to make fewer refreshes. |
| Every message makes three RPC calls. | The cache is created inside get or the module is loaded twice. Keep cached and inflight at module level and register the provider once. |
| The model calls a negative gap a fault or says finalized is far behind. | Two requests at two moments can read out of order. State in the provider description that the gap is normally 0 or 1 and that a negative gap of a slot or two is read-order noise. |
| The model quotes the slot as current late in a long chat. | The line carries its read time. Tell the model in the description to quote the time with the slot, and lower TTL_MS when staleness matters. |
| The key appears in a log line or an error shown to the model. | Send it in the x-api-key header only. The ?api-key= form puts it in the URL, and URLs get logged. Never print the transport or its settings. |
Questions
Which commitment does each number use?
Both slots name theirs: confirmed for the first and finalized for the second. getEpochInfo is read at confirmed as well. The kit would pick confirmed on its own, and the JSON-RPC server would pick finalized.
How often does the provider call Carbium?
At most once per TTL_MS, which is two seconds, and one refresh is three calls. Turns that arrive during a refresh wait for it and add no calls.
Why poll when a slot subscription exists?
A chat agent reads the line a few times a minute. A subscription holds a socket open and meters 20 credits per MiB sent, and it needs reconnect logic. Polling at a two second window needs none of that.
Does it work with a plain function in place of the ElizaOS runtime?
Yes. get takes the runtime, message and state as ignored arguments, so the main block calls it with none of them. The framework passes real ones when it runs the provider.