Canonical: https://solanashreds.xyz/docs/decode/anchor-instructions

# Decoding Anchor instructions: discriminators and Borsh

One decoder for every Anchor program: give it the program's IDL and it turns raw instruction bytes into the instruction's name, its arguments and its accounts by name. Tested on real mainnet instructions from eight programs.

To decode Anchor instruction data, load the program's IDL, map each instruction's 8-byte discriminator to its definition, then read the arguments that follow in Borsh, in the order the IDL lists them. Accounts are positional: the instruction's first account is the IDL's first account. One small decoder covers every Anchor program, given a correct IDL.

## Steps

1. Load the IDL and index its instructions by discriminator. Use the IDL's `discriminator` field when present, and compute `sha256("global:<snake_case_name>")[..8]` only when it is not.
2. Keep only instructions whose program ID equals the IDL's `address`.
3. Look up the first eight bytes of the data. No match means another instruction set or an IDL that is out of date: report it, never guess.
4. Read each argument by its type: integers little-endian, strings and vectors with a `u32` length, options and enums with a one-byte tag, named types from the IDL's `types`.
5. Require that the arguments use every byte. Data that ends exactly at an argument boundary means newer trailing arguments were left out by an older client: mark them absent.
6. Name the accounts by position. An optional account the sender left out is passed as the program's own ID; anything after the IDL's list is a remaining account.

## anchor.ts

```typescript file="src/anchor.ts"
// Anchor instruction matching and Borsh decoding from an IDL (new spec 0.30+, and the legacy spec Jupiter v6 uses).
// Discriminator: sha256("global:<snake_case_name>")[..8] (anchor lang/syn codegen/program/common.rs), unless the
// IDL gives one explicitly (new spec always lists it; custom discriminators exist since Anchor 0.31).
import { createHash } from "node:crypto";
import { b58 } from "./base58.ts";

export const snake = (s: string) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
export const sighash = (name: string) => createHash("sha256").update(`global:${snake(name)}`).digest().subarray(0, 8);

type Idl = { address?: string; instructions: any[]; types?: any[] };
export type Decoded = { name: string; args: Record<string, unknown> };
export type Labeled = Decoded & { accounts: Record<string, string | null>; remaining: string[] };

export class AnchorDecoder {
  private byDisc = new Map<string, any>();
  private types = new Map<string, any>();
  private lenientTrailing: boolean;
  constructor(idl: Idl, lenientTrailing = true) {
    this.lenientTrailing = lenientTrailing;
    for (const t of idl.types ?? []) this.types.set(t.name, t.type);
    for (const ix of idl.instructions) {
      const disc = ix.discriminator ? Uint8Array.from(ix.discriminator) : sighash(ix.name);
      this.byDisc.set(Buffer.from(disc).toString("hex"), ix);
    }
  }
  /** Decode and name the accounts too. `addresses` are the instruction's accounts, already resolved (static keys
   *  plus lookup tables). IDL accounts are positional. An optional account that the sender left out is passed as
   *  the program's own ID (Anchor's convention), reported here as null. Extra accounts are "remaining accounts". */
  decodeWithAccounts(data: Uint8Array, addresses: string[], programId: string): Labeled | null {
    const d = this.decode(data);
    if (!d) return null;
    const ix = this.byDisc.get(Buffer.from(data.subarray(0, 8)).toString("hex"));
    const flat: any[] = [];
    const walk = (list: any[]) => { for (const a of list) a.accounts ? walk(a.accounts) : flat.push(a); };
    walk(ix.accounts ?? []);
    const accounts: Record<string, string | null> = {};
    flat.forEach((a, i) => { const addr = addresses[i]; accounts[a.name] = addr === undefined || (a.optional && addr === programId) ? null : addr; });
    return { ...d, accounts, remaining: addresses.slice(flat.length) };
  }
  /** The IDL entry for a discriminator (for callers that want signer and writable flags). */
  instructionFor(data: Uint8Array): any { return this.byDisc.get(Buffer.from(data.subarray(0, 8)).toString("hex")); }

  /** Returns null when the first 8 bytes match no instruction in this IDL. */
  decode(data: Uint8Array): Decoded | null {
    const ix = this.byDisc.get(Buffer.from(data.subarray(0, 8)).toString("hex"));
    if (!ix) return null;
    const r = { b: data, o: 8 };
    const args: Record<string, unknown> = {};
    for (const a of ix.args) {
      // Programs add trailing arguments over time and old clients keep sending the shorter form
      // (seen on mainnet: one pump.fun buy without track_volume and partial_fill, 13 buy_exact_quote_in_v3
      // without partial_fill). Data that ends exactly
      // at an argument boundary means "absent", never a guessed default.
      if (r.o === data.length && this.lenientTrailing) { args[a.name] = undefined; continue; }
      args[a.name] = this.read(a.type, r);
    }
    if (r.o !== data.length) throw new Error(`${ix.name}: ${data.length - r.o} trailing bytes (IDL out of date?)`);
    return { name: ix.name, args };
  }
  private read(t: any, r: { b: Uint8Array; o: number }): unknown {
    const v = new DataView(r.b.buffer, r.b.byteOffset, r.b.byteLength);
    const take = (n: number) => { if (r.o + n > r.b.length) throw new Error("data too short"); const o = r.o; r.o += n; return o; };
    switch (t) {
      case "bool": return r.b[take(1)] !== 0;
      case "u8": return r.b[take(1)];
      case "i8": return v.getInt8(take(1));
      case "u16": return v.getUint16(take(2), true);
      case "i16": return v.getInt16(take(2), true);
      case "u32": return v.getUint32(take(4), true);
      case "i32": return v.getInt32(take(4), true);
      case "u64": return v.getBigUint64(take(8), true);
      case "i64": return v.getBigInt64(take(8), true);
      case "u128": { const o = take(16); return v.getBigUint64(o, true) | (v.getBigUint64(o + 8, true) << 64n); }
      case "i128": { const o = take(16); return BigInt.asIntN(128, v.getBigUint64(o, true) | (v.getBigUint64(o + 8, true) << 64n)); }
      case "pubkey": case "publicKey": { const o = take(32); return b58(r.b.subarray(o, o + 32)); }
      case "string": { const n = v.getUint32(take(4), true); const o = take(n); return Buffer.from(r.b.subarray(o, o + n)).toString("utf8"); }
      case "bytes": { const n = v.getUint32(take(4), true); const o = take(n); return r.b.subarray(o, o + n); }
    }
    if (t.option !== undefined) return r.b[take(1)] ? this.read(t.option, r) : null;
    if (t.vec !== undefined) { const n = v.getUint32(take(4), true); return Array.from({ length: n }, () => this.read(t.vec, r)); }
    if (t.array !== undefined) return Array.from({ length: t.array[1] }, () => this.read(t.array[0], r));
    if (t.defined !== undefined) {
      const name = typeof t.defined === "string" ? t.defined : t.defined.name;
      const def = this.types.get(name);
      if (!def) throw new Error(`type ${name} not in IDL`);
      if (def.kind === "struct") return Object.fromEntries((def.fields ?? []).map((f: any, i: number) => [f.name ?? i, this.read(f.type ?? f, r)]));
      if (def.kind === "enum") {
        const variant = def.variants[r.b[take(1)]];
        if (!variant) throw new Error(`bad ${name} variant`);
        const fields = variant.fields ?? [];
        return { [variant.name]: Object.fromEntries(fields.map((f: any, i: number) => [f.name ?? i, this.read(f.type ?? f, r)])) };
      }
    }
    throw new Error("unsupported IDL type " + JSON.stringify(t));
  }
}
```

## decode-anchor.ts: one transaction, one program

```typescript file="src/decode-anchor.ts"
// Decode every instruction of one program in one transaction, with named arguments and accounts.
//   node src/decode-anchor.ts <idl.json> <transaction-base64> [loaded-writable,...] [loaded-readonly,...]
// The program ID comes from the IDL's "address"; v0 lookup addresses come from your resolver (or RPC meta).
import fs from "node:fs";
import { AnchorDecoder } from "./anchor.ts";
import { decodeTx } from "./tx.ts";

const [idlPath, txBase64, loadedW = "", loadedR = ""] = process.argv.slice(2);
const idl = JSON.parse(fs.readFileSync(idlPath, "utf8"));
const decoder = new AnchorDecoder(idl);
const tx = decodeTx(Buffer.from(txBase64, "base64"));
const keys = [...tx.staticKeys, ...loadedW.split(",").filter(Boolean), ...loadedR.split(",").filter(Boolean)];

tx.instructions.forEach((ix, i) => {
  if (keys[ix.programIndex] !== idl.address) return; // only this program's top-level instructions
  const out = decoder.decodeWithAccounts(ix.data, ix.accounts.map((a) => keys[a]), idl.address);
  // BigInt does not serialize to JSON by default, so print integers as strings
  console.log(JSON.stringify({ instruction: i, ...out }, (_k, v) => (typeof v === "bigint" ? v.toString() : v), 2));
});
```

`decodeTx` is the transaction parser from the [TypeScript decoder](https://solanashreds.xyz/docs/decode/typescript) workspace. For a v0 transaction, pass the addresses your [lookup table resolver](https://solanashreds.xyz/docs/decode/resolve-lookup-tables) returns, or account indexes past the static keys will not resolve.

## What it prints

Run on a real Pump.fun transaction from mainnet slot 470,901,816 with the IDL at pump-public-docs commit 639b87f, it prints the instruction below. The output is shortened here to the arguments and a few accounts; the full run names all 17.

```json
{
  "instruction": 0,
  "name": "sell_v3",
  "args": { "amount": "25199613253678", "min_sol_output": "2918125" },
  "accounts": {
    "global": "4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf",
    "base_mint": "7Mo99iGXj7rwXDj5oD8MULSEBngjVamqwX2pV632pump",
    "base_token_program": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",
    "quote_token_program": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
    "bonding_curve": "FDXLg79YtxoradzqJXQHFtxiCUaLYJDkHDCPUsKZP5DR",
    "program": "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"
  },
  "remaining": []
}
```

The labels already answer questions the bytes cannot: this token's mint runs on Token-2022 while the quote side is ordinary SPL Token, which matters for the next decoding step.

## How this code was tested

Every instruction to eight Anchor programs found in real mainnet transactions on 18 November 2026 was decoded with the pinned IDLs.

| Check | Result |
| --- | --- |
| Discriminators computed from names equal the IDL's own | all instructions in seven IDLs; Jupiter has one custom value (`create_idempotent_associated_token_account`) |
| Decoded name equals the "Instruction:" line the program logged on mainnet | 37 of 37 instructions |
| Accounts the IDL pins to a fixed address land on that label | 60 of 60 |
| Required accounts missing | 0 |
| Short forms real clients sent: 1 Pump.fun `buy` without `track_volume` and `partial_fill`, 13 `buy_exact_quote_in_v3` without `partial_fill` | all 14 decoded with those arguments marked absent; strict decoding rejects all 14 |

Programs: Pump.fun, PumpSwap, Raydium CPMM and CLMM, Orca Whirlpool, Meteora DLMM and DAMM v2, Jupiter v6. Node 24, no dependencies.

## Things that break IDL decoders

- **A stale IDL.** Jupiter's IDL in its CPI repository has no `route_v2` and an older swap enum; the on-chain IDL decodes current traffic. Pin each IDL and record where it came from, as [reading an IDL](https://solanashreds.xyz/learn/reading-an-idl) explains.
- **Enum order.** Variants are numbered by position. A new variant in the middle of a list renumbers everything after it.
- **Assuming the hash.** Since Anchor 0.31 a program may set custom discriminators; [the Anchor discriminator page](https://solanashreds.xyz/learn/anchor-discriminators) has a real one.
- **Trailing arguments.** Programs add arguments at the end and keep accepting the short form. Reject only data that ends mid-argument.
- **Integer width.** A `u64` read as a JavaScript number loses precision above 2^53; keep it as a `BigInt` until you format it. The [Borsh rules](https://solanashreds.xyz/learn/borsh-encoding) list every width.

## What this decoder cannot tell you

It reads what the sender asked for. The amounts in a sell are the amount offered and the least the sender would accept, not what they received, and nothing here says whether the instruction succeeded. Events from `emit!` and `emit_cpi!` and the token transfers the program made are execution data, so they are not in the transaction at all. Programs that are not built with Anchor need their own layouts. For any of that, see [what your decoder cannot see](https://solanashreds.xyz/blog/what-your-decoder-cannot-see).

## Program recipes

Apply it program by program: [Pump.fun](https://solanashreds.xyz/docs/programs/pump-fun), [PumpSwap](https://solanashreds.xyz/docs/programs/pumpswap), [Raydium CPMM and CLMM](https://solanashreds.xyz/docs/programs/raydium-cpmm-and-clmm), [Orca Whirlpool](https://solanashreds.xyz/docs/programs/orca-whirlpool), [Meteora](https://solanashreds.xyz/docs/programs/meteora) and [Jupiter](https://solanashreds.xyz/docs/programs/jupiter). It fits after the transaction stage of the [decoding pipeline](https://solanashreds.xyz/docs/decode/pipeline); to run it on your own feed, [see pricing](https://solanashreds.xyz/pricing).
