---
id: HS0014
title: "Anchor instruction decoder"
url: https://carbium.sh/library/howsolana/anchor-instruction-decoder
collection: How to use Solana
category: Anchor
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Anchor instruction decoder

One TypeScript file takes an Anchor program id, picks a recent successful transaction (or the signature you pass), and prints each instruction's name, named accounts and decoded arguments. The IDL comes from chain too. Every call is a read, so it needs no keypair.

## What a transaction holds

A Solana transaction is a list of instructions. Each one names the program to call, the accounts it touches in a fixed order, and a single blob of bytes. Nothing on chain says what those accounts are for or what the bytes mean. For an Anchor program the blob has a known shape: an 8-byte tag that selects the instruction, then the arguments in Borsh encoding.

The meaning lives in the program's IDL, a JSON file that lists each instruction with its account names and argument types. Decoding takes three steps. Find the instructions aimed at your program, match their first 8 bytes against the tags the IDL implies, then read the arguments and put a name on every account by position.

Anchor builds a tag from the first 8 bytes of the SHA-256 hash of `global:` plus the instruction's snake case name. IDLs from Anchor 0.30 and later write that tag into the file as a `discriminator` array. Older IDLs list only the camelCase name, so the file uses the `discriminator` array when it is there and otherwise hashes the snake case name itself. Accounts and events get their own tags the same way, from `account:` and `event:` plus the type name.

Many Anchor programs also store the IDL on chain, in an account at a derived address. The file reads it from there, so a program id is the only input it needs.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips the TypeScript types on load. The first argument is the program id. The second is an optional signature. With no signature the file asks for the program's recent signatures, keeps the newest three that succeeded and decodes the first one `getTransaction` returns a transaction for.

`main.ts` (run: `node main.ts <anchor-program-id> [signature]`)

```ts
// HS0014 · Anchor instruction decoder
// https://carbium.sh/library/howsolana/anchor-instruction-decoder
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { setTimeout as sleep } from "node:timers/promises";
import { createHash } from "node:crypto";
import { inflateSync } from "node:zlib";
import {
  address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, getAddressEncoder,
  getBase58Encoder, getProgramDerivedAddress, isSolanaError, signature, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,
} from "@solana/kit";

type Acc = { name: string; accounts?: Acc[] };
type Ins = { name: string; discriminator?: number[]; accounts: Acc[]; args: { name: string; type: unknown }[] };
type Ix = { programId: string; accounts?: string[]; data?: string };

const key = process.env.CARBIUM_KEY;
const [programArg, sigArg] = process.argv.slice(2);
if (!key || !programArg) {
  console.error("Set CARBIUM_KEY, then run: node main.ts <anchor-program-id> [signature]");
  process.exit(1);
}
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));
const program = address(programArg);
const addr = getAddressDecoder();
// One retry on HTTP 429, after the retry-after seconds.
const retry = <T>(f: () => Promise<T>): Promise<T> =>
  f().catch(async (e) => {
    if (!isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) || e.context.statusCode !== 429) throw e;
    await sleep((Number(e.context.headers.get("retry-after")) || 1) * 1000);
    return f();
  });
// An instruction's tag: the IDL's discriminator, or sha256("global:<snake_case_name>")[0..8].
const tag = (d: Ins) => d.discriminator ? Buffer.from(d.discriminator)
  : createHash("sha256").update("global:" + d.name.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase())).digest().subarray(0, 8);
const flat = (a: Acc[]): string[] => a.flatMap((x) => (x.accounts ? flat(x.accounts) : [x.name]));
// The IDL account: createWithSeed(PDA of no seeds, "anchor:idl", program). Data: 8 tag, 32 authority, u32 length, zlib JSON.
async function loadIdl(): Promise<{ instructions: Ins[] } | undefined> {
  const part = (a: typeof program) => Uint8Array.from(getAddressEncoder().encode(a));
  const [base] = await getProgramDerivedAddress({ programAddress: program, seeds: [] });
  const idlAddress = addr.decode(createHash("sha256").update(part(base)).update("anchor:idl").update(part(program)).digest());
  const { value } = await retry(() => rpc.getAccountInfo(idlAddress, { encoding: "base64", commitment: "finalized" }).send());
  if (!value) return undefined;
  const raw = Buffer.from(value.data[0], "base64");
  return JSON.parse(inflateSync(raw.subarray(44, 44 + raw.readUInt32LE(40))).toString());
}
function arg(t: unknown, b: Buffer, o: number): [string, number] | undefined {
  const int = typeof t === "string" ? /^([ui])(\d+)$/.exec(t) : null;
  if (int) {
    const bits = Number(int[2]);
    const v = BigInt("0x" + Buffer.from(b.subarray(o, o + bits / 8)).reverse().toString("hex"));
    return [String(int[1] === "i" ? BigInt.asIntN(bits, v) : v), o + bits / 8];
  }
  if (t === "bool") return [String(b[o] === 1), o + 1];
  if (t === "pubkey" || t === "publicKey") return [addr.decode(b.subarray(o, o + 32)), o + 32];
  if (t === "string") {
    const n = b.readUInt32LE(o);
    return [JSON.stringify(b.toString("utf8", o + 4, o + 4 + n)), o + 4 + n];
  }
}

const get = (s: string) => retry(() => rpc.getTransaction(signature(s), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" }).send());
// The newest three successful signatures; the first one the node returns is decoded.
const list = sigArg ? [sigArg] : (await retry(() => rpc.getSignaturesForAddress(program, { limit: 20, commitment: "finalized" }).send()))
  .filter((s) => s.err === null).slice(0, 3).map((s) => s.signature);
let sig = "", tx: Awaited<ReturnType<typeof get>> = null;
for (sig of list) if ((tx = await get(sig))) break;
if (!tx) throw new Error("No transaction found.");
const ixs = [
  ...(tx.transaction.message.instructions as unknown as Ix[]),
  ...(tx.meta?.innerInstructions ?? []).flatMap((g) => g.instructions as unknown as Ix[]),
].filter((ix) => ix.programId === program && ix.data);
const idl = await loadIdl();
console.log(`${sig}: ${ixs.length} instruction(s) for ${program}, IDL ${idl ? "found" : "not found"}`);
const b58 = getBase58Encoder();
for (const ix of ixs) {
  const data = Buffer.from(Uint8Array.from(b58.encode(ix.data ?? "")));
  const hit = idl?.instructions.find((d) => tag(d).equals(data.subarray(0, 8)));
  if (!hit) {
    console.log(`unknown tag ${data.subarray(0, 8).toString("hex")}, ${data.length} bytes`);
    continue;
  }
  const names = flat(hit.accounts);
  const out: string[] = [];
  let o = 8;
  for (const { name, type } of hit.args) {
    const r = arg(type, data, o);
    out.push(r ? `${name}=${r[0]}` : `${name}=? ${JSON.stringify(type)}`);
    if (!r) break;
    o = r[1];
  }
  console.log(`${hit.name}\n  accounts ${(ix.accounts ?? []).map((a, i) => `${names[i] ?? "remaining"}=${a}`).join(" ")}\n  args ${out.join(" ")}`);
}
```

Three parts of the file do the work. `loadIdl` derives the IDL address, reads that account, cuts out the length-prefixed zlib payload and parses it. `tag` turns an IDL entry into its 8 bytes, and `arg` reads one argument at a time and hands back the new offset.

`getTransaction` runs with the `jsonParsed` encoding. For a program the node has no parser for, each instruction comes back with `programId`, an `accounts` array of addresses and `data` as base58, so no account index needs resolving by hand. `maxSupportedTransactionVersion: 1` lets legacy, v0 and v1 transactions through. The file also walks `meta.innerInstructions`, because a program reached through a CPI shows up there and never at the top level.

## Reading the output

Each matched instruction prints its name, one line of `account=address` pairs and one line of `argument=value` pairs. An instruction whose tag matches nothing in the IDL prints the tag in hex and the byte count.

| Part | Bytes | What the file does |
|---|---|---|
| Tag | 0 to 7 | Compares it with the tag of each instruction in the IDL. |
| Arguments | 8 onward | Reads them in IDL order: integers little endian, bool as 1 byte, pubkey as 32 bytes, string as a u32 length plus UTF-8. |
| Accounts | The instruction's account list | Names them by position from the IDL, with composite groups flattened in order. Extra accounts print as `remaining`. |

Integers print through `BigInt`, so a `u64` keeps every digit. A token amount in an argument is in the mint's base units. Scale it with the mint's decimals before showing it to anyone, as in [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).

## On Carbium

A run makes three kinds of read. `getSignaturesForAddress` costs 50 cells, `getTransaction` costs 50 and the IDL read through `getAccountInfo` costs 10. A run with no signature spends 110 cells when the first candidate answers and 210 when it needs all three. A run given a signature spends 60.

`getSignaturesForAddress` is [allowed](https://carbium.sh/docs#rpc) 0.24 requests per second on Free, 1.2 on Dev, 100 on Business and 500 on Pro. `getAccountInfo`, an account read, is allowed 0.5, 15, 50 and 400.

To decode many transactions, read the IDL once and keep it. A JSON-RPC batch of up to 100 calls goes out as one plain `fetch` POST of a JSON array.

Finding signatures by address uses Carbium's own address index, which keeps up to 30 days. Pass a signature you already hold as the file's second argument and it goes straight to `getTransaction`, which drops one 50-cell call from the run.

## Where it ends

The file decodes only what the on-chain IDL describes. Some programs never publish an IDL, some close it and some leave an old one in place after an upgrade. With no IDL the file prints the tag and the byte count for each instruction and stops. Get the IDL from the program's source repository and parse that file in `loadIdl` in place of the chain account.

The argument reader covers integers, `bool`, pubkeys and strings. For a struct, enum, option, vec or array it prints the IDL type and stops for that instruction, because the offset of everything after it depends on that type. Anchor's own TypeScript client ships a full Borsh coder that takes the same IDL, and that is the next step when your arguments are structs.

A program that is not built with Anchor has no 8-byte tag, so a match is luck. Check that the program has an IDL account before you trust any output. The file also leaves out account data and events. Account data starts with a tag from `account:` plus the type name, and an event rides in the logs as a `Program data:` line with a tag from `event:`.

Searching by address reaches back 30 days at most, and older history is not served by that call. A signature that appears in a list can still read back as null if the node answering has not reached it at the commitment you ask for, which is why the file tries up to three.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The first output line says the IDL was not found. | The program has no IDL account at the derived address, or it was closed. Load the IDL JSON from the program's repository and parse that file in `loadIdl`. |
| An instruction prints `unknown tag` although the IDL loaded. | The deployed program differs from the IDL on chain, or the instruction belongs to a program without Anchor tags. Hash `global:<name>` for the names you expect, compare the first 8 bytes, and get the IDL that matches the deployed build. |
| An argument prints as `name=?` followed by a type object. | That type is a struct, enum, option, vec or array, which the small reader stops at. Decode that instruction with a full Borsh coder and the same IDL. |
| A `RangeError` from a buffer read. | The data is shorter than the IDL says, so the IDL belongs to another version of the program. Fetch the IDL again or use the one from the matching release. |
| HTTP 429 with a retry-after hint. | The `retry` helper already waits the seconds in the header and tries once more. If it repeats, pass a signature to save a 50-cell call, or move to a plan with higher rates. |
| The run ends with `No transaction found.` | The address has no successful transaction among its last 20 signatures inside the 30-day index, or none of the newest three reads back yet at `finalized`. Pass a signature of your own, or run it again. |

## Questions

### Do I need the IDL to decode an instruction?

For names and argument types, yes. Without it you can hash the instruction names you already know and compare them with the first 8 bytes, but the arguments stay raw bytes.

### Can I decode events and account data the same way?

The idea is the same with another prefix: `account:` for accounts and `event:` for events, then the same Borsh read. This file handles instructions only.

### Does this need a private key?

No. Every call is a read, and the Carbium key only identifies your account to the RPC.

### Why does the file also read inner instructions?

When another program calls yours through a CPI, your instruction is listed under `meta.innerInstructions`. Reading both finds it either way.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Failed-mint monitor](https://carbium.sh/library/blockchainideas/failed-mint-monitor) (Blockchain ideas, BI0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
