library / How to use Solana / Accounts and balances / HS0077
Zero-copy account decoder
One TypeScript file finds a pool state account in a busy program's newest transaction, checks its 8-byte discriminator, reads fixed offsets from the C layout and proves them by matching the two mints' decimals. Every call is a read.
Borsh against zero-copy
Most Anchor accounts are written with Borsh: fields in declaration order, integers little endian, no padding, and a length or a tag in front of every Vec and Option. A zero_copy account skips that step. The program maps the account's bytes straight onto a Rust struct, so after the 8-byte discriminator the stored bytes are the struct's memory image.
A struct with repr(C) follows C layout rules. Each field starts at a multiple of its own alignment, and the compiler adds padding bytes to get there. A u8 followed by a u32 leaves 3 padding bytes between them. A Borsh decoder reads the u32 from the very next byte, and every field after it lands 3 bytes off.
With repr(C, packed) there is no padding, and a struct made only of integers, byte arrays and keys is byte for byte what Borsh would write. That is why a Borsh decoder can work on one zero-copy account and return garbage on the next: the first padding byte shifts everything below it.
Offsets come from the struct, added up field by field. Integers are little endian, because that is how the program's memory holds them.
Reading the layout from the IDL
Since Anchor 0.30 the IDL carries what you need. The accounts list gives each account's name and discriminator. The entry of the same name under types carries "serialization" set to bytemuck for a zero-copy type, or bytemuckunsafe for zero_copy(unsafe), which is what the pool state of the program in the file uses. It also holds a repr object such as {"kind": "c", "packed": true} and the fields in order. An entry with no serialization key is Borsh.
Walk fields from byte 8. For an unpacked C layout, round the running offset up to the field's alignment before placing it. For a packed layout, add the sizes. The pool state of the program in the file is packed, so the walk is plain addition:
| Field | Type | Offset | Bytes |
|---|---|---|---|
| discriminator | [u8; 8] | 0 | 8 |
| bump | [u8; 1] | 8 | 1 |
| amm_config | pubkey | 9 | 32 |
| owner | pubkey | 41 | 32 |
| token_mint_0 | pubkey | 73 | 32 |
| token_mint_1 | pubkey | 105 | 32 |
| token_vault_0 | pubkey | 137 | 32 |
| token_vault_1 | pubkey | 169 | 32 |
| observation_key | pubkey | 201 | 32 |
| mint_decimals_0 | u8 | 233 | 1 |
| mint_decimals_1 | u8 | 234 | 1 |
The file decodes four of these: the two mints and the two decimals bytes. The fields below byte 235 stay unread, because nothing in the run checks them.
Computing the discriminator
An account's tag is the first 8 bytes of the SHA-256 hash of account: plus the type name, in the case it has in the Rust source, here PoolState. Instruction tags use global: and snake case, and account tags keep the type name as written. A 0.30 IDL prints the bytes in the account's discriminator array, and hashing the name gives the same bytes for an older IDL or for none.
A transaction lists many accounts: mints, vaults, tick arrays, the signer. Every Anchor account type named PoolState in any program carries the same 8 bytes, and a routed transaction can list the pool states of two programs side by side. The file matches the 8 bytes and also checks that the account's owner is the program, and it ignores where the account sits in the list.
The run
Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types on load. The optional argument is a program id. It must be a program whose PoolState has this exact layout, a fork of the same program, because the tag and the four offsets are hardcoded. With none, the file uses a busy concentrated-liquidity program that stores its pool state as a zero-copy account.
// HS0077 · Zero-copy account decoder// https://carbium.sh/library/howsolana/zero-copy-account-decoder// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createHash } from "node:crypto";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, signature,} from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY, then run: node main.ts [program-id]"); process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));// Default: a busy concentrated-liquidity program whose PoolState is a zero_copy account.// A program given as the argument needs a PoolState with the exact layout below.const program = address(process.argv[2] ?? "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK");// Anchor's account tag: the first 8 bytes of sha256("account:" + type name, exact case).// Every program with a type named PoolState shares it, so the owner is checked too.const tag = createHash("sha256").update("account:PoolState").digest().subarray(0, 8);const addr = getAddressDecoder();const read = async (keys: string[]) => (await rpc.getMultipleAccounts(keys.map((k) => address(k)), { encoding: "base64" }).send()).value.map((a) => a ? { owner: a.owner as string, data: Buffer.from(a.data[0], "base64") } : null);// Offsets after the tag, added up from the IDL's repr(C, packed): no padding bytes.const OFF = { mint0: 73, mint1: 105, decimals0: 233, decimals1: 234 };const sigs = (await rpc.getSignaturesForAddress(program, { limit: 10 }).send()) .filter((s) => s.err === null).slice(0, 5);let pool: Buffer | null = null;let from = "";for (const s of sigs) { try { const tx = await rpc.getTransaction(signature(s.signature), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send(); if (!tx) { console.log(`${s.signature}: null, trying the next`); continue; } const keys = (tx.transaction.message.accountKeys as unknown as { pubkey: string }[]).map((k) => k.pubkey); const found = await read(keys.slice(0, 100)); // 100 pubkeys is the most one call takes below Pro const i = found.findIndex((a) => a !== null && a.owner === program && a.data.length > OFF.decimals1 && a.data.subarray(0, 8).equals(tag)); console.log(`${s.signature}: ${keys.length} keys, ${i < 0 ? "no PoolState" : "PoolState " + keys[i]}`); if (i >= 0) { pool = found[i]?.data ?? null; from = keys[i]; break; } } catch (e) { console.log(`${s.signature}: ${(e as Error).message}`); }}if (!pool) throw new Error("No PoolState found in the newest transactions.");const mints = [OFF.mint0, OFF.mint1].map((o) => addr.decode(pool.subarray(o, o + 32)));const decimals = [pool[OFF.decimals0], pool[OFF.decimals1]];// Proof: each decoded mint must exist, and byte 44 of a mint account (its decimals) must equal the pool's byte.const onChain = await read(mints);const ok = onChain.every((m, n) => m !== null && m.data[44] === decimals[n]);mints.forEach((m, n) => console.log(`token_mint_${n} ${m} decimals ${decimals[n]}, mint account says ${onChain[n]?.data[44] ?? "missing"}`));console.log(ok ? `Layout verified on ${from}.` : "Layout mismatch: do not trust these offsets.");process.exitCode = ok ? 0 : 1;
run: node main.ts [program-id]
The file asks for the program's newest signatures and keeps the first five that succeeded. For each it calls getTransaction with jsonParsed and maxSupportedTransactionVersion: 1, so legacy, v0 and v1 transactions all read back and lookup table addresses are already resolved. It then reads the transaction's account keys in one getMultipleAccounts call, at most 100, and keeps the account that the program owns and whose first 8 bytes equal the tag. A try that fails or answers null is printed and the next signature is used. Every call in the file runs at confirmed commitment, the value @solana/kit 8.6.0 fills in when a call leaves it out.
The proof is the last step. The file decodes the two mint addresses at bytes 73 and 105, reads those two accounts, and compares byte 44 of each mint account, its decimals, with the decimals bytes the pool carries at 233 and 234. An address cut from the wrong offset is a random 32 bytes, so the mint read comes back missing. A right mint with a wrong decimals offset fails the comparison. The run ends with Layout verified. or a mismatch and exit code 1.
On Carbium
A run makes three kinds of read. getSignaturesForAddress and getTransaction cost 50 cells each, and getMultipleAccounts costs 10 cells per pubkey and serves both the pool read and the mint read. A transaction that lists 59 accounts costs 590 cells for the pool read, plus 20 for the two mints, so a run that finds the pool on its first try spends 710 cells.
getMultipleAccounts is an account read, allowed 0.5 requests per second on Free, 15 on Dev, 50 on Business and 400 on Pro. One call takes up to 300 pubkeys on Pro. Below Pro the 1,024-cell burst caps a call at 100, which is why the file slices the key list at 100. A call with 100 pubkeys is priced at 1,000 cells, and at 1,001 once the body passes 4 KiB. A body with 100 base58 keys is about 4.6 KiB, so a full call lands there.
Where it ends
The offsets belong to one layout of one program. A program upgrade that adds or reorders a field moves everything below it, and the account tag stays the same. Run the decimals check after every upgrade of the program you read, and read the new IDL's fields before trusting an old table.
The file decodes only what the run verifies. Liquidity, price and tick sit lower in the struct as 128-bit and 32-bit integers, and a u128 read needs BigInt. Add a field to the file when you have a second account or a vault balance to check it against, the way the mints check the decimals.
An unpacked repr(C) struct needs the padding rule from the IDL walk. A repr with an align value raises the struct's alignment and its tail padding, which changes its size and the offset of any struct nested after it, while the first field still starts at byte 8. The packed case here is the easy one. A packed struct can also hold a field that is unaligned in memory, which the program reads with care, and Buffer reads at any offset without trouble.
The file looks at one transaction's accounts. If the pool sits past the 100th key of a large v0 transaction it is not read, and the file moves to the next signature. Older history is out of reach, since a signature list covers 30 days at most and getTransaction can still answer null for a listed signature.
A type whose repr is unknown, or one with a custom serialization, needs its struct read from the program source. Without an IDL, the discriminator and the source repository's struct are all you have.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The run ends with No PoolState found in the newest transactions. | None of the five newest successful transactions listed a pool owned by the program, or the pool sat past the 100th key. Run again a moment later, or pass a fork of the same program whose transactions name the account. |
| The decimals check prints Layout mismatch and a mint reads as missing. | The argument is a program whose PoolState has another layout, or the offsets are for another build of the program. Pass a fork of the same program, or fetch the IDL that matches the deployed program, redo the field walk from its repr, and update the four offsets. |
| getTransaction fails with -32015. | The call left maxSupportedTransactionVersion out, or set it to 0, and the transaction is v1. Pass 1. |
| A Borsh decoder returns plausible numbers up to one field and nonsense after it. | The account is zero-copy and padding sits above that field. Switch to fixed offsets from the struct's repr. |
| A signature from the list reads back as null. | Its transaction lies below the node's ledger floor or has not reached the node. The file prints it and takes the next signature. |
Questions
How do I know an account is zero-copy?
In a 0.30 or later IDL, the type of the account has serialization set to bytemuck, or to bytemuckunsafe for zero_copy(unsafe). An account type with no serialization key is Borsh.
Why check decimals against the mint?
A wrong offset can still produce 32 plausible bytes. A mint account that exists and carries the same decimals byte the pool holds is a check a wrong offset almost never passes.
Can I decode the whole struct this way?
Yes, by adding rows to the walk. Check each new field against something outside the pool, such as a vault balance, before you rely on it.
Do I need the IDL at run time?
No. The file hardcodes four offsets from the IDL's repr and the type name for the tag. The IDL gave you the layout once, and the run checks it again.