services
Get a key

library / Blockchain ideas / BI0075

memcmp offset finder

A script that takes one sample account and a value, prints every byte offset where the value sits with a ready memcmp filter, then reads a second account at that offset to show whether the layout holds.

By Carbium · Developer tools · BI0075 · updated 2026-11-22

01

What memcmp compares

A memcmp filter keeps an account when the bytes at one position in its data equal the bytes you give. It has three fields: offset, the count of bytes from the start of the account data; bytes, the value to match; and encoding, which names how bytes is written, here base58. Nothing else is compared. The filter knows no field names or types, so finding the right offset is the whole job.

Programs store an account as fields in a fixed order. An SPL token account starts with the mint (32 bytes), then the owner (32 bytes), then the amount (8 bytes). Offset 0 with a mint address selects every token account of that mint, and offset 32 with a wallet address selects the token accounts that wallet owns.

Program documentation tends to name the fields and leave the offsets to you. An Anchor account also starts with an 8-byte discriminator, and every offset counts from the first byte of the data, discriminator included. When you hold a value that sits somewhere inside an account, looking is faster than counting: fetch one real account, search its bytes for the value and print where it was found.

02

Encoding the needle

The needle is the value in the form the program stores it, and that form depends on the type.

ValueStored asNeedle length
Public keyThe 32 raw bytes behind the address text32
StringA Borsh string: a 4-byte little-endian length, then the UTF-8 bytes4 plus the text length
u64 number8 bytes, least significant byte first8

A string needle includes its length prefix on purpose. Without it, a filter for abc also matches a field holding abcd, since the first three bytes agree. With the prefix the filter matches that string exactly.

$Searching an account for an address written as text finds nothing. Accounts hold the 32 raw bytes, and base58 is the way those bytes are written for people and for the bytes field of a filter.

Once the needle is found, the filter's bytes is the needle written back in base58. For a public key that is the address you started with. The finder writes the other kinds with the base58 codec in @solana/kit.

03

Scanning and printing offsets

main.ts searches locally, on bytes it reads once. It asks for the sample and the check account in one getMultipleAccounts call with base64 encoding. Account reads cost 10 cells each and getMultipleAccounts charges 10 per pubkey, so the two-account call costs 20. The call names no commitment, so @solana/kit fills in confirmed.

With no argument it picks its own accounts, so a first run needs no setup.

  1. Read the newest signatures of the Token program with getSignaturesForAddress and drop the failed ones.
  2. Fetch each with getTransaction, jsonParsed encoding and maxSupportedTransactionVersion: 1, until two token accounts have appeared in postTokenBalances with their mint and owner.
  3. Build two needles from the first account: its mint and its owner.
  4. Read both accounts in one getMultipleAccounts call.
  5. Search the first account's bytes for each needle with Buffer.indexOf, continuing past each hit so repeats show, and print a ready filter for every offset.
main.ts
// BI0075 · memcmp offset finder// https://carbium.sh/library/blockchainideas/memcmp-offset-finder// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, getAddressEncoder, getBase58Decoder } from "@solana/kit";const key = process.env.CARBIUM_KEY ?? (console.error("Set CARBIUM_KEY to your Carbium API key."), process.exit(1));const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({  url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key },}));const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");// A needle: the bytes to find, and how to read a value of the same kind at any offset.type Needle = { label: string; bytes: Buffer; read: (d: Buffer, at: number) => string; expect?: string };const pubkey = (label: string, a: string, expect?: string): Needle => ({  label, expect, bytes: Buffer.from(Uint8Array.from(getAddressEncoder().encode(address(a)))),  read: (d, at) => getAddressDecoder().decode(d.subarray(at, at + 32)),});function parse(spec: string): Needle {  const [kind, ...rest] = spec.split(":");  const v = rest.join(":");  if (kind === "pubkey") return pubkey(spec, v);  if (kind === "u64") {    const bytes = Buffer.alloc(8);    bytes.writeBigUInt64LE(BigInt(v));    return { label: spec, bytes, read: (d, at) => d.readBigUInt64LE(at).toString() };  }  if (kind === "text") return { label: spec, bytes: Buffer.from(v), read: (d, at) => d.toString("utf8", at, at + Buffer.byteLength(v)) }; // raw UTF-8, no prefix  if (kind !== "string") throw new Error("needle must be pubkey:<address>, u64:<number>, string:<text> or text:<text>");  const bytes = Buffer.concat([Buffer.alloc(4), Buffer.from(v)]); // Borsh string: u32 length, then UTF-8  bytes.writeUInt32LE(bytes.length - 4);  return { label: spec, bytes, read: (d, at) => d.toString("utf8", at + 4, at + 4 + Math.min(d.readUInt32LE(at), 64)) };}const readAt = (n: Needle, d: Buffer, at: number) => { try { return n.read(d, at); } catch { return "(past the end of the account)"; } };type Tx = { transaction: { message: { accountKeys: { pubkey: string }[] } }; meta: { postTokenBalances?: { accountIndex: number; mint: string; owner?: string }[] } | null };// Two token accounts with their mint and owner, taken from the newest Token program transactions.async function sample(): Promise<[string, { mint: string; owner: string }][]> {  const found = new Map<string, { mint: string; owner: string }>();  const sigs = await rpc.getSignaturesForAddress(TOKEN_PROGRAM, { limit: 10 }).send();  for (const s of sigs.filter((x) => !x.err)) {    if (found.size >= 2) break;    try {      const tx = (await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()) as unknown as Tx | null;      if (!tx) continue; // the signature index reaches below the ledger floor, so null happens      for (const t of tx.meta?.postTokenBalances ?? [])        if (t.owner) found.set(tx.transaction.message.accountKeys[t.accountIndex].pubkey, { mint: t.mint, owner: t.owner });    } catch (e) {      console.error(`getTransaction ${s.signature.slice(0, 8)} failed:`, e instanceof Error ? e.message : e);    }  }  return [...found];}async function main() {  const args = process.argv.slice(2);  if (args.length === 1 || args.length === 2) throw new Error("usage: node main.ts <sample> <other> <needle>... (needle: pubkey:<address>, u64:<number>, string:<text>, text:<text>)");  let accounts = args.slice(0, 2);  let needles = args.slice(2).map(parse);  if (!args.length) {    const [a, b] = await sample();    if (!b) throw new Error("fewer than two token accounts found, run again");    accounts = [a[0], b[0]];    needles = [pubkey("mint", a[1].mint, b[1].mint), pubkey("owner", a[1].owner, b[1].owner)];  }  const res = await rpc.getMultipleAccounts(accounts.map((x) => address(x)), { encoding: "base64" }).send();  const [dataA, dataB] = res.value.map((v) => (v ? Buffer.from(([] as unknown[]).concat(v.data)[0] as string, "base64") : null));  if (!dataA) throw new Error(`${accounts[0]} was not found`);  console.log(`sample ${accounts[0]} (${dataA.length} bytes), check ${accounts[1]} (${dataB ? `${dataB.length} bytes` : "not found"})`);  for (const n of needles) {    const hits: number[] = [];    for (let i = dataA.indexOf(n.bytes); i !== -1; i = dataA.indexOf(n.bytes, i + 1)) hits.push(i);    console.log(`${n.label}: ${hits.length ? `offset ${hits.join(", ")}` : "not found"}`);    const bytes = getBase58Decoder().decode(n.bytes);    for (const at of hits) {      console.log(`  filter ${JSON.stringify({ memcmp: { offset: at, bytes, encoding: "base58" } })}`);      if (!dataB) continue;      const got = readAt(n, dataB, at);      console.log(`  second account at ${at}: ${got}${n.expect ? (got === n.expect ? " (matches its own value)" : " (differs from its own value)") : ""}`);    }  }}main().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1); });

run: CARBIUM_KEY=<YOUR_KEY> node main.ts

Run as shown, it finds the mint at offset 0 and the owner at offset 32. That is the token layout from the first section, so the finder proves itself before you point it at an unknown program. For your own accounts, pass the sample, the account to check and one or more needles: node main.ts <sample> <other> string:<text> text:<text> u64:<number> pubkey:<address>. Each needle prints its offsets and a filter shaped like {"memcmp":{"offset":32,"bytes":"<base58>","encoding":"base58"}}.

Sampling is the larger cost. getSignaturesForAddress costs 50 cells and each getTransaction costs 50, so a run that reads ten transactions spends 550 cells on sampling and 570 with the account read. A rate class absorbs bursts up to 1,024 cells, which holds a run.

04

Confirming on a second account

An offset found in one account holds in another only when every field before the value has a fixed size. Put a Borsh string in front and the next field moves. Take a record with a name string followed by an authority public key. With a name of 5 bytes the authority starts at 4 + 5 = 9. With a name of 11 bytes it starts at 15. A filter built from the first account matches the second only by accident.

That is why the finder reads a second account at the same offset. It decodes the bytes there as the needle's own kind and prints the result. In the default run it also knows the second token account's real mint and owner, and prints whether the bytes at offset 0 and offset 32 agree with them. A token account has no variable-length field before the owner, so both agree. The check needs no second call: the other account comes back in the same getMultipleAccounts read and adds its 10 cells.

For your own accounts, pick the second one with care: choose an account whose string field has a different length from the sample's. If the value read back is the one you expect, the offset survives that change. Garbage, a shifted fragment or a number that makes no sense means a variable-length field sits earlier in the layout.

!A filter proven on one account can match nothing on the rest. Run it against a second account with a different string length before it goes anywhere.

When the layout does move, filter on a field that sits before the variable-length one, where the offset is the same in every account, and check the string after the accounts come back.

05

Where it ends

  • The finder never sends a filter anywhere. It prints the filter and stops. getProgramAccountsV2 is not served on Carbium, so check which methods are served before wiring the filter into a scan. -32601 means the method is not served, and a retry will not change that.
  • The string:<text> needle assumes a Borsh string whose 4-byte prefix holds the text length. Token Metadata and similar programs pad a Borsh string with zeros to a fixed length, so the prefix holds the padded length and string:<text> finds nothing. Use text:<text>, the raw UTF-8 bytes with no prefix. It matches the start of the text, so a longer value that begins with the same bytes also matches.
  • A short or common value, such as a small number, turns up at many offsets. The finder lists all of them and leaves the choice to you. A distinctive sample value gives one hit.
  • The offset belongs to one layout. A program upgrade that reorders or inserts a field moves it, so run the finder again on a fresh account after an upgrade.
  • getMultipleAccounts takes at most 100 pubkeys a call below Pro, and up to 300 on Pro, at 10 cells each. The finder sends two. Checking many accounts means more calls or a Pro key.
  • The account arrives whole as base64 before the search runs, so a very large account is a large download.
06

When it goes wrong

what goes wrongwhat to do
The needle is not found in the sample account.Search for the stored form: raw 32 bytes for an address, a 4-byte length prefix for a string, least significant byte first for a number. If the program keeps the string in a zero-padded fixed array, or pads a Borsh string with zeros to a fixed length, use text:<text>, the raw UTF-8 bytes with no prefix.
The value shows up at several offsets.Take the offset whose neighbours match the program's field order, or pick a sample account with a more distinctive value. A short number is the usual cause.
The second account shows garbage or a different value at the printed offset.A variable-length field sits before the value. The offset holds only for accounts whose earlier fields have the same length. Build one filter per length, or filter on a field that comes earlier.
The second account comes back as not found.The address is wrong or the account was closed. Read the address again or pick another account.
The default run stops with fewer than two token accounts.A signature the index lists can answer null from getTransaction, and some transactions carry few token balances. Run it again, since the newest signatures change.
07

Questions

Why does searching for the address text find nothing?

The account stores the 32 raw bytes of the address. The base58 text is a way of writing those bytes, so the needle must be the decoded bytes, which the finder builds from pubkey:<address>.

Does the offset include the Anchor discriminator?

Yes. Offsets count from the first byte of the account data, so the 8-byte discriminator is part of the count. The finder searches the full data, so the printed offset already includes it.

Can I combine the filter with a size filter?

Yes. A dataSize filter and a memcmp filter in the same list must both match. A token account of the base Token program is 165 bytes, so dataSize: 165 with a mint filter selects token accounts of one mint.

Does the offset change when the program is upgraded?

Only when the upgrade changes the layout. After any upgrade, run the finder on a fresh account and compare its offsets with the ones you use.

Can I search for a number?

Yes, with u64:<number>, which searches the 8 little-endian bytes. For other widths, change the byte length in parse.