library / Integrations / I0066
Expo Anchor account decoding
A Node script that finds a live Orca Whirlpool account, decodes it from base64 with Uint8Array and DataView, then checks the decoded mint on chain. The DataView reads port to an Expo app with no Buffer polyfill once the discriminator is pasted as a constant.
Where the error comes from
readUIntLE is a method of Node's Buffer. Anchor's account coder reads fields through buffer-layout, and buffer-layout calls b.readUIntLE(offset, length) on whatever bytes it was handed. The error b.readUIntLE is not a function means those bytes are an object without that method, almost always a plain Uint8Array.
Expo runs your code on Hermes, which has no Node core modules and no global Buffer. Apps add the buffer package and assign it to global.Buffer so libraries can find it. The decode still breaks when a value that never passed through that package reaches the coder: bytes from a base64 helper or bytes from a newer client library. Each is a plain Uint8Array without readUIntLE.
- Fix it in place. Wrap the bytes with Buffer.from(bytes) before they reach program.coder.accounts.decode, and make sure global.Buffer is set before any Solana import runs.
- Remove the dependency. A fixed-size Anchor account is a flat run of little-endian fields, and DataView reads them on any JavaScript engine with no polyfill.
The second route needs only getUint16, getBigUint64 and a 32-byte slice, shown here on one real Whirlpool account.
The eight-byte discriminator
Every Anchor account starts with eight bytes that name its type: the first eight bytes of the SHA-256 hash of account: followed by the type name. For an Orca Whirlpool pool that is the hash of account:Whirlpool. The fields follow in declaration order, with no padding, and every integer is little-endian.
Compare the discriminator before you trust anything else. A program owns several account types, and a list that mixes them hands you bytes of another type that decode into plausible nonsense. The code computes the eight bytes with crypto.subtle.digest, which Node 24 has. Hermes has no crypto.subtle, so in the app paste the eight values as a constant that you printed once from Node.
Reading integers and keys with DataView
These are the leading fields of a Whirlpool account. Offsets count from byte 0 of the account data after base64 decoding, and the Read column shows how the code reads each field it uses.
| Field | Offset | Type | Read |
|---|---|---|---|
| discriminator | 0 | 8 bytes | compare byte by byte |
| whirlpoolsConfig | 8 | pubkey | skipped |
| whirlpoolBump | 40 | 1 byte | skipped |
| tickSpacing | 41 | u16 | getUint16(41, true) |
| feeTierIndexSeed | 43 | 2 bytes | skipped |
| feeRate | 45 | u16 | skipped |
| protocolFeeRate | 47 | u16 | skipped |
| liquidity | 49 | u128 | two getBigUint64 reads |
| sqrtPrice | 65 | u128 | two getBigUint64 reads |
| tickCurrentIndex | 81 | i32 | skipped |
| protocolFeeOwedA | 85 | u64 | skipped |
| protocolFeeOwedB | 93 | u64 | skipped |
| tokenMintA | 101 | pubkey | 32-byte slice, base58 |
The second argument true selects little-endian. Leave it out and DataView reads big-endian, which gives wrong numbers and no error. DataView has no 128-bit read, so the code reads the low eight bytes and the high eight bytes as BigInt and joins them with a shift of 64. Hermes in current Expo releases supports BigInt.
A public key is 32 raw bytes in the account data, with no base58 in it. The code turns the slice into an address with getAddressDecoder from @solana/kit; in an app, any base58 encoder works on the same slice.
Fetching the bytes over RPC
Ask for encoding: "base64". The answer carries the data as a base64 string, which atob turns into bytes in Node and in current Expo releases. The code calls Carbium's RPC endpoint with the key in the x-api-key header. @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, so every read here is at confirmed.
A decode demo needs a live Whirlpool account, and a hard-coded pool address goes stale. So the code takes the program's newest signatures from getSignaturesForAddress, keeps up to eight successful ones, and tries each transaction in turn. One can fail to load: those pages come from an address index that keeps up to 30 days and reaches below the validator's ledger floor, so getTransaction can answer null for a signature the index lists. The code prints the reason for each skipped signature and moves to the next.
Mainnet carries v1 transactions, so getTransaction takes maxSupportedTransactionVersion: 1; with the value absent or 0 it answers -32015 for a v1 transaction. From a served transaction the code collects the static account keys and the keys loaded from address lookup tables, and sends them to one getMultipleAccounts call, at most 100 pubkeys. That call costs 10 cells per pubkey, so 100 pubkeys is 1000 cells and fits the 1,024-cell burst. Pro takes up to 300 pubkeys a call. The code keeps the accounts whose owner is the Whirlpool program and whose first eight bytes match, and decodes the first one.
The last step reads the decoded tokenMintA with getAccountInfo and decodes that mint's supply and decimals with the same DataView approach. If the offset 101 slice were wrong, that address would not exist or would not hold a mint.
Install with npm install @solana/[email protected], set "type": "module" in package.json and export CARBIUM_KEY. CARBIUM_RPC_URL is optional. Node 24 strips the types on load.
// I0066 · Expo Anchor account decoding// https://carbium.sh/library/integrate/expo-anchor-account-decoding// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium key."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const WHIRLPOOL = address("whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc");const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode("account:Whirlpool"));const DISC = new Uint8Array(digest).slice(0, 8);const fromBase64 = (s: string) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));const u128 = (v: DataView, at: number) => v.getBigUint64(at, true) | (v.getBigUint64(at + 8, true) << BigInt(64));type Tx = { transaction: { message: { accountKeys?: string[] } }; meta: { loadedAddresses?: { writable?: string[]; readonly?: string[] } } | null;} | null;const sigs = (await rpc.getSignaturesForAddress(WHIRLPOOL, { limit: 8 }).send()).filter((s) => s.err === null);let pool: { pubkey: string; bytes: Uint8Array } | undefined;for (const { signature } of sigs) { const tag = signature.slice(0, 8); try { const tx = (await rpc .getTransaction(signature, { encoding: "json", maxSupportedTransactionVersion: 1 }) .send()) as unknown as Tx; if (!tx) { console.log("skip", tag, "getTransaction answered null"); continue; } const loaded = tx.meta?.loadedAddresses; const keys = [...new Set([...(tx.transaction.message.accountKeys ?? []), ...(loaded?.writable ?? []), ...(loaded?.readonly ?? [])])].slice(0, 100); const { value } = await rpc .getMultipleAccounts(keys.map((k) => address(k)), { encoding: "base64" }) .send(); for (let i = 0; i < value.length; i++) { const a = value[i]; if (!a || a.owner !== WHIRLPOOL) continue; const bytes = fromBase64(a.data[0]); if (bytes.length >= 133 && DISC.every((b, j) => bytes[j] === b)) { pool = { pubkey: keys[i] as string, bytes }; break; } } if (pool) break; console.log("skip", tag, `no Whirlpool account among ${keys.length} keys`); } catch (e) { console.log("skip", tag, e instanceof Error ? e.message : String(e)); }}if (!pool) { console.error("No transaction produced a Whirlpool account."); process.exit(1);}const view = new DataView(pool.bytes.buffer, pool.bytes.byteOffset, pool.bytes.byteLength);const mintA = getAddressDecoder().decode(pool.bytes.subarray(101, 133));console.log({ pool: pool.pubkey, tickSpacing: view.getUint16(41, true), liquidity: u128(view, 49).toString(), sqrtPrice: u128(view, 65).toString(), tokenMintA: mintA,});const { value: mint } = await rpc.getAccountInfo(mintA, { encoding: "base64" }).send();if (!mint) { console.error("tokenMintA does not exist on chain: the offset is wrong."); process.exit(1);}const m = fromBase64(mint.data[0]);const mv = new DataView(m.buffer, m.byteOffset, m.byteLength);console.log("mint", { owner: mint.owner, decimals: m[44], supply: mv.getBigUint64(36, true).toString() });
run: node main.ts
Run node main.ts. It prints one line per skipped signature, then the decoded pool and the mint check, and exits with code 1 when no transaction produced a Whirlpool account.
Where it ends
- It decodes one account type. Another Anchor account needs its own offsets from the program's IDL, and a field behind a Vec, a String or an enum shifts every offset after it.
- The offsets match the Whirlpool layout as deployed today. A program upgrade that changes the struct moves them, while the discriminator stays.
- The pool it decodes is whichever one the newest transactions touched. It does not look a pool up by token pair.
- A call holds at most 100 pubkeys below Pro. The code reads only the newest eight signatures, which lie inside the 30-day index.
- The run is Node 24. The DataView reads behave the same on Hermes, but run them in your app before you rely on them there.
- The key stays on the machine that runs the script. An app bundle can be unpacked, so put a relay between the phone and Carbium, as in React Native getBalance fix. For the same offset technique on token accounts, see Token account layout decoder.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| b.readUIntLE is not a function still appears after the DataView read is in place. | Another import in the bundle still calls the Anchor coder. Find buffer-layout or coder.accounts.decode in the stack and route that account through the offsets above. |
| Every getTransaction in the run answers null and the script exits with code 1. | The signatures came from the 30-day address index, which reaches below the validator's ledger floor. Run it again for newer signatures; the code only asks for the newest eight. |
| getTransaction answers -32015. | Send maxSupportedTransactionVersion: 1 with the call. Without it a v1 transaction is refused. |
| Liquidity or tickSpacing decodes to a huge or tiny number. | Check the little-endian flag on every DataView read, then the offset, then the discriminator. An offset off by one reads the neighbouring field. |
| getMultipleAccounts answers 429 on a longer list. | Keep each call at 100 pubkeys below Pro, wait for the retry-after hint, and retry once. |
| atob is not defined in the app. | Older React Native releases lack it. Use a small base64 decoder of your own that returns a Uint8Array. |
Questions
Can I keep Anchor and polyfill Buffer instead?
Yes. Install buffer, assign it to global.Buffer in the entry file before other imports, and wrap raw bytes with Buffer.from. The DataView route removes the dependence for the accounts you read yourself.
Where do the offsets come from?
From the program's IDL. Add the field sizes in order after the 8-byte discriminator: a u16 takes 2 bytes, a u128 takes 16 and a pubkey takes 32.
Is it safe to put the Carbium key in the app?
Anything bundled into an app can be extracted, and limits are per account, so a copied key draws on your own budget. Keep the key on a server and let the app call that.
Do the mint reads work for Token-2022 mints?
The first 82 bytes of a Token-2022 mint share the SPL layout, so the supply and decimals reads hold. Extension data follows after those bytes.