Fetching & Decoding Accounts
Typed on-chain reads using generated decoders and kit RPC.
Recipe
import { createSolanaRpc, address } from "@solana/kit";
import { fetchCounter } from "./generated/clients/js";When to reach for this:
- Dashboards showing program state.
- Preflight checks before building instructions.
- Server Components reading chain data.
Working Example
import { createSolanaRpc, address } from "@solana/kit";
import { fetchCounter, decodeCounter } from "./generated/clients/js";
const rpc = createSolanaRpc(process.env.RPC_URL!);
const counterPk = address(process.env.COUNTER_PUBKEY!);
const account = await fetchCounter(rpc, counterPk);
console.log(account.data.count);
// Lower level: raw bytes
const info = await rpc.getAccountInfo(counterPk, { encoding: "base64" }).send();
if (info.value) {
const decoded = decodeCounter(Buffer.from(info.value.data[0], "base64"));
}What this demonstrates:
- High-level fetch helpers vs manual decode path.
- Handle missing accounts (null) before UI render.
- Use
finalizedcommitment for accounting snapshots.
Deep Dive
How It Works
getAccountInforeturns owner, lamports, and data bytes.- Discriminator prefix selects account variant.
- Generated decoders map bytes to typed objects.
- PDA derivation stays in client or shared util crate.
Gotchas
- Wrong owner - decode garbage. Fix: verify program id matches IDL.
- Account closed - null data. Fix: handle closed accounts in UI.
- Stale cache - show outdated counts. Fix: subscriptions or SWR refresh.
- Base64 vs base58 confusion - RPC encoding param matters.
- Large accounts - RPC payload limits. Fix: slice reads or use indexer.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| DAS for NFTs | Digital assets | Arbitrary program accounts |
| Indexer SQL | Heavy analytics | Single account lookup |
| getProgramAccounts | Enumerate all | Expensive on mainnet |
FAQs
Anchor 0.32.1 IDL?
Run anchor build; point Codama at target/idl JSON.
Regenerate when?
Every on-chain interface change in CI.
kit typed clients?
Codama renders @solana/kit native functions.
gill required?
Optional sugar atop kit.
Next.js?
Import generated clients in client components for writes.
Testing?
Surfpool + devnet integration tests.
web3.js?
Do not mix with generated kit clients.
Multiple programs?
One Codama config per program or monorepo workspace.
Account fetch?
Use generated decoders with getAccountInfo.
Errors?
Map program error codes from IDL metadata.
Related
- Codama - codegen
- Server-Side Reads - Next.js
- Codecs & Serialization - manual codecs
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, anchor-lang 0.32.1, Rust 1.91.1, @solana/kit 7.0.0, Surfpool 0.12.0, and LiteSVM 0.6.x.