library / AI and blockchain / SI0018
Oracle accounts explained
How an oracle gets its data onto Solana, what the account holds, and what a reader must check before acting on it. The file decodes the chain's clock account, refuses a wrong owner or size and flags a stale value.
Where the data lives
A Solana program cannot make an HTTP call, so it cannot ask the outside world anything. An oracle gets outside data in by writing it down first. A program owned by the oracle holds one account per feed, and its publishers send transactions that update the bytes in those accounts. Anyone who wants the value reads the account.
A client calls getAccountInfo on the feed's address and gets lamports, owner, data and an executable flag, the same shape as for any wallet or token account. A program that needs the value takes the feed account as an input to its instruction and reads the same bytes. Nothing is pushed to you and nobody answers a request. The latest value sits in the account until the next publisher transaction replaces it.
An oracle is a convention about three things: who may write, how the bytes are laid out, and how often they change. The account itself has no idea it is an oracle, so every check that makes its value safe to use sits in the reader. SPL token balance reads a token account by its address, owner and layout.
What the bytes hold
The oracle program defines the layout, and its documentation gives the offsets. A price-style feed usually carries a value, a scale for it (an exponent or a decimals count), some measure of uncertainty, and the time or slot of the last update. Without the scale the integer means nothing. Without the update time you cannot tell a live value from a dead one.
The Clock sysvar has a layout the chain itself fixes, so it works as a stand-in with no outside document. The runtime writes it, the Sysvar program owns it, and it is 40 bytes of little-endian integers.
| Offset | Bytes | Field | Meaning |
|---|---|---|---|
| 0 | 8 | slot | the slot the clock was written for |
| 8 | 8 | epoch start timestamp | Unix time at the start of the epoch, signed |
| 16 | 8 | epoch | the current epoch |
| 24 | 8 | leader schedule epoch | the epoch the leader schedule is known for |
| 32 | 8 | unix timestamp | the cluster's estimate of Unix time, signed |
A real price feed has its own owner, its own size or discriminator and its own offsets. To point the file at one, change FEED and the offsets in readFeed, and keep the checks.
Checks before you trust a value
A feed address is a string, and anyone can create an account with the layout of a real feed and a value they chose.
| Check | What it catches |
|---|---|
| owner equals the oracle program | an account someone created with copied bytes; only the owning program can write the data of an account it owns |
| data.length matches the layout | an account of another type, or a layout that changed, which would decode into nonsense |
| age within a limit you chose | a feed whose publishers stopped; the last value is still there and looks fine |
| scale applied, uncertainty read | a value off by a power of ten, or one so uncertain that acting on it is a guess |
Age needs a clock to compare against. The file reads getSlot next to the account and subtracts the slot written in the data. A slot is about 200 ms, so a limit of 150 slots is about 30 s. Choose the limit from how quickly your decision goes stale.
For an agent, return the decoded fields and the verdict in one tool result, as Read-only model tools does for account reads: the value with its scale applied, the age in slots and a fresh flag. A model that receives only a number will use it, so the flag has to stop the action in your loop.
The reader file
One file, with @solana/kit and Node 24 only. Set CARBIUM_KEY first; the file exits with a message when it is unset. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh.
// SI0018 · Oracle accounts explained// https://carbium.sh/library/si/oracle-accounts-explained// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read one oracle-style account and check it before trusting it. Run: CARBIUM_KEY=... node main.ts [address]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = 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 } }));// What a reader must know about a feed: who owns it and how long its data is.// These are the Clock sysvar's values; a price feed has its own, from its program's docs.const FEED = { owner: "Sysvar1111111111111111111111111111111111111", size: 40 };const CLOCK = "SysvarC1ock11111111111111111111111111111111";const MAX_AGE_SLOTS = 150; // about 30 s at 200 ms a slotasync function readFeed(pubkey: string) { const [info, now] = await Promise.all([ rpc.getAccountInfo(address(pubkey), { encoding: "base64" }).send(), rpc.getSlot().send(), ]); const account = info.value; if (!account) throw new Error("account not found"); if (account.owner !== FEED.owner) throw new Error(`owner is ${account.owner}, expected ${FEED.owner}`); const bytes = Buffer.from(account.data[0], "base64"); if (bytes.length !== FEED.size) throw new Error(`data is ${bytes.length} bytes, expected ${FEED.size}`); // Little-endian fields at fixed offsets: slot at 0, epoch at 16, unix timestamp at 32. const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length); const slot = view.getBigUint64(0, true); const ageSlots = Number(now > slot ? now - slot : 0n); return { slot: Number(slot), epoch: Number(view.getBigUint64(16, true)), ageSlots, skewSeconds: Math.round(Date.now() / 1000 - Number(view.getBigInt64(32, true))), fresh: ageSlots <= MAX_AGE_SLOTS, };}// The second read is an account that must fail the owner check: the USDC mint unless you pass another.const other = process.argv[2] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const labels = ["clock", "other"];const results = await Promise.allSettled([readFeed(CLOCK), readFeed(other)]);results.forEach((r, i) => { if (r.status === "fulfilled") console.log(labels[i], JSON.stringify(r.value)); else console.log(labels[i], "refused:", (r.reason as Error).message);});if (results[0].status === "rejected") process.exitCode = 1;
run: node main.ts
readFeed fetches the account and getSlot together, then throws on a missing account, a wrong owner or a wrong size. A stale value does not throw: it comes back with fresh: false and the ageSlots that explain it. The run reads the Clock sysvar, then a second account to show a refusal: the USDC mint by default, or the address you pass as the first argument. The clock line is one JSON object with slot, epoch, ageSlots, skewSeconds and fresh. The second line is the refusal, which names the token program as the owner it did not expect.
Timing and cost
Two calls can be served from slightly different points, so the account's slot can be ahead of getSlot. Both calls leave commitment out, so @solana/kit sends them at confirmed commitment. That is why the file clamps ageSlots at 0 and why a limit of a few slots would raise false alarms.
getAccountInfo costs 10 cells and getSlot costs 1, so one check is 11 cells. Account reads run at 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro, so a Free key re-reads a feed about every two seconds, around ten slots apart. Several feeds in one call go through getMultipleAccounts, which charges 10 cells per pubkey, and the 1,024-cell burst caps a call at 100 pubkeys below Pro.
Limits are per Carbium account, so its keys share one budget. The file does not retry, so a polling loop around it sets its own interval from the account-read rate.
Where it ends
- The Clock is the chain's own data. A price feed carries a claim from outside, and how far to believe it depends on who publishes and how the oracle program combines their reports. Code that decodes the bytes sees neither, so read the oracle program's documentation before putting value behind a feed.
- A read is a copy at one slot. A program that uses a value does its own owner, size and age checks inside its instruction, because the value in your client may be a slot old by the time a transaction lands.
- The owner, size and offsets in this file are the Clock's. A real feed has its own, and a program upgrade can change a layout.
- The file does not poll or subscribe. accountSubscribe sends account state on change for streamed accounts, so confirm a notification arrives for your feed before building on it, and poll when none does.
- The quote, swap, health and prices methods on the RPC endpoint are not account reads. prices is a quote-plane answer, with no owner, scale or update slot for this file's checks to run on, so a feed's bytes still come from getAccountInfo.
- There is no signing here. Acting on a value, with funds or otherwise, needs its own design and a human step.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The value is off by a power of ten. | Apply the feed's scale before the value reaches a person or a model, and send the scale along in the result. |
| The feed looks fine and has not updated for a long time. | Compare the update slot or time in the data with getSlot and refuse past a limit you chose. The bytes carry no expiry of their own. |
| A copied account passes the decode. | Check owner before reading any field. Only the owning program can write an account's data, so a copy owned by someone else decodes cleanly and still fails this check. |
| The decode throws a RangeError or returns garbage after the oracle program changed. | Compare data.length with the layout size before reading any offset and refuse on a mismatch. Then read the program's documentation for the new layout. |
| ageSlots goes negative when you subtract the two slots yourself. | The two calls were served from slightly different points, so the account's slot can be ahead of getSlot. Clamp at 0 as the file does and set the age limit well above a few slots. |
| A polling loop gets 429. | Size the poll interval from the plan's account-read rate and back off when the retry-after hint arrives. Other keys on the same account spend the same budget. |
Questions
Can a Solana program call an oracle's API directly?
No. A program cannot make HTTP requests. Outside data arrives as account bytes written by publishers' transactions, and your program reads the account.
Does reading a feed cost anything on chain?
A client read through getAccountInfo is an RPC call with no transaction and no fee; on Carbium it costs 10 cells. A program that reads the account inside an instruction pays only the compute that instruction uses.
How do I find a feed's layout?
The oracle program's documentation gives its owner, size and offsets. Check them on a live account: getAccountInfo returns owner and space, and a decoded value should match what the feed shows elsewhere.
Why read getSlot as well as the account?
The account holds the slot it was last written at but not the current slot. The gap between them is the age, and only your reader can judge whether it is too old.