services
Get a key

library / How to use Solana / HS0064

Logs grouped by instruction

One TypeScript file reads a transaction's logMessages and hands every line to the instruction that wrote it, with outer index, program id and call depth, then checks its frame count against the transaction's own instruction total.

By Carbium · History and parsing · HS0064 · updated 2026-11-22

01

The lines in logMessages

meta.logMessages is one flat array of strings for the whole transaction. No line in it carries an instruction index. What the array does carry is a bracket structure: the runtime writes a line when a program starts and another when it ends, so the lines of a call always sit between the two.

LineWritten whenUse in the walk
Program <id> invoke [n]A program starts. n is the call depth, 1 for a top-level instruction.Opens a frame.
Program <id> successThe program returned without an error.Closes the frame.
Program <id> failed: <reason>The program returned an error.Closes the frame, with the reason.
Program <id> consumed <a> of <b> compute unitsJust before the success or failed line, from on-chain programs; built-ins such as System and Compute Budget skip it.Stays in the frame.
Program consumption: <n> units remainingA program called sol_log_compute_units.Stays in the open frame.
Program log: <text>The program printed a message.Belongs to the open frame.
Program data: <base64>The program emitted raw data, which is how many programs write events.Belongs to the open frame.
Program return: <id> <base64>The program set return data.Belongs to the open frame.

Every instruction except a signature precompile (Ed25519, secp256k1, secp256r1) opens a frame, compute budget instructions included. They write an invoke line and a success line with nothing between them, and they count toward the total later on.

The n in an invoke line is the same number as stackHeight on an inner instruction, so a frame at depth 2 or more has a matching entry in meta.innerInstructions.

02

Walking the stack

Keep two things: a stack of open frames and a counter of top-level instructions that starts below zero. Read the lines in order. An invoke line with depth 1 bumps the counter. Every invoke line then creates a frame stamped with the counter's current value, pushes it on the stack and adds it to a result list.

Any other line goes onto the frame at the top of the stack. A success or failed line that names the program at the top also pops it. A parent's lines before and after a child call land on the parent, because the child's frame is popped first and the parent is on top again when its next line arrives.

The counter gives each frame its outer index, which is the position of the top-level instruction at the root of its call chain. The invoke depth gives the call depth. The lines gathered on the frame are what that one program wrote, with nested calls kept in their own frames.

03

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types on load. Give it a program address, or nothing. It lists the eight newest signatures of the program at confirmed commitment, drops the failed ones and reads the first two transactions in parallel. With no argument it uses the id of a busy DEX router, so its newest signatures nearly always carry several nested calls.

main.ts
// HS0064 · Logs grouped by instruction// https://carbium.sh/library/howsolana/logs-grouped-by-instruction// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (apiKey === undefined || apiKey === "") {  console.error("CARBIUM_KEY is not set; export your Carbium API key first.");  process.exit(1);}const client = createSolanaRpcFromTransport(  createDefaultRpcTransport({    headers: { "x-api-key": apiKey },    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",  }),);type Frame = { outer: number; depth: number; program: string; lines: string[] };type Ix = { programId: string };type Group = { index: number; instructions: Ix[] };// Every invoke line opens a frame; every other line goes to the frame on top of the stack.function walk(logs: readonly string[]): Frame[] {  const frames: Frame[] = [];  const stack: Frame[] = [];  let outer = -1;  for (const line of logs) {    const open = /^Program (\w+) invoke \[(\d+)\]$/.exec(line);    if (open) {      const depth = Number(open[2]);      if (depth === 1) outer += 1;      const frame: Frame = { outer, depth, program: open[1], lines: [] };      frames.push(frame);      stack.push(frame);      continue;    }    const top = stack.at(-1);    top?.lines.push(line);    const end = /^Program (\w+) (success|failed)/.exec(line);    if (end && end[1] === top?.program) stack.pop();  }  return frames;}// A program address, or nothing (a busy DEX router).const program = address(process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");const page = await client.getSignaturesForAddress(program, { limit: 8, commitment: "confirmed" }).send();const sigs = page.filter((row) => row.err === null).slice(0, 2).map((row) => row.signature);if (sigs.length === 0) console.log("No successful signatures found.");const config = { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "confirmed" } as const;const results = await Promise.allSettled(sigs.map((sig) => client.getTransaction(sig, config).send()));results.forEach((res, n) => {  const sig = sigs[n];  if (res.status === "rejected") {    console.error(`${sig}: ${res.reason instanceof Error ? res.reason.message : String(res.reason)}`);    return;  }  const tx = res.value;  if (tx === null) {    console.log(`${sig}: null (older than the ledger)`);    return;  }  const logs = tx.meta?.logMessages ?? [];  const top = tx.transaction.message.instructions as unknown as Ix[];  const groups = (tx.meta?.innerInstructions ?? []) as unknown as Group[];  const frames = walk(logs);  const seen = new Map<number, number>();  let mismatch = 0;  for (const f of frames) {    const k = seen.get(f.outer) ?? 0;    const want = f.depth === 1 ? top[f.outer] : groups.find((g) => g.index === f.outer)?.instructions[k];    if (f.depth > 1) seen.set(f.outer, k + 1);    if (want?.programId !== f.program) mismatch += 1;  }  const total = top.length + groups.reduce((sum, g) => sum + g.instructions.length, 0);  const cut = logs.includes("Log truncated") ? ", log truncated" : "";  console.log(`${sig}: ${frames.length} frames, ${total} instructions, ${mismatch} program mismatches${cut}`);  for (const f of frames.slice(0, 12)) {    const pad = "  ".repeat(f.depth - 1);    console.log(`${pad}#${f.outer} depth ${f.depth} ${f.program}`);    for (const line of f.lines.slice(0, 3)) console.log(`${pad}    ${line.slice(0, 100)}`);  }});

run: node main.ts [program address]

Both calls write commitment: "confirmed" out, so the read level is visible in the file. The transaction call sets maxSupportedTransactionVersion: 1, because a call that omits it gets -32015 for a version 1 transaction, as in Transaction version error -32015. The two reads go through Promise.allSettled, so one failing call prints its error and the other still runs.

For each transaction the file prints one summary line, then the first twelve frames. Each frame shows its outer index, depth and program id, indented by depth, with the first three lines it wrote. Long lines are cut at 100 characters.

04

Matching frames to instructions

Frames at depth 1 come out in the order of the transaction's top-level instructions, so a frame with outer index i is message.instructions[i]. Frames deeper than 1 follow the order of the group in meta.innerInstructions whose index is i. The third deeper frame under outer index 4 is the third entry of that group's instructions array.

The file keeps one counter per outer index, looks up the instruction each frame should be, and compares program ids. It prints the number of frames that disagree. Once the numbers agree, a log line has a program, an instruction with accounts and data, and a position in the call tree. For the tree view of the instruction side alone, see Inner instruction tree.

$The count check is arithmetic: frames found must equal the top-level instruction count plus the length of every inner group. A match says the walk saw every call. A gap says some lines are missing or the stack lost its place.
05

What breaks the walk

  • Truncation. The runtime stops recording once a transaction's log output reaches a byte limit and writes a single Log truncated line. Frames that would have come after it never appear, the stack may stay open to the end, and the frame count falls short of the instruction total. The file prints a flag when it sees that line, and a truncated transaction is read as a partial view.
  • Look-alike text. Output from program code starts with Program log: , Program data: or Program consumption: , so a line that starts with Program <id> success was written by the runtime. A walker that tests with includes, or with a pattern that is not anchored at the start of the line, can still be fooled by a program that prints such words in its message. The walk here anchors each pattern and pops only when the closing id equals the program on top.
  • A failed transaction. The failing program writes a failed line, and the frames above it close with failed lines of their own. The array can also stop with frames still open. Treat a non-empty stack at the end as normal for a failed transaction and keep the frames you have.
  • Instructions that write no invoke line. A signature precompile (Ed25519, secp256k1, secp256r1) runs without opening a frame. When a transaction holds one, the frame count falls below the instruction total by that many, and the mismatch counter will also point at the later frames.
06

On Carbium

A run makes three calls: one getSignaturesForAddress and two getTransaction, each costing 50 cells. That is 150 cells, well inside the 1,024-cell burst a rate class absorbs. getTransaction is rated at 0.24 req/s on Free, 1.2 on Dev, 5 on Business and 25 on Pro; getSignaturesForAddress at 0.24, 1.2, 100 and 500. Reading a long list of transactions one by one is a job for a paid plan. A JSON-RPC batch carries up to 100 calls in one POST, and cells are the admission charge per call, so each call in it still costs its 50 cells and a batch of 100 is 5,000 cells.

For a live view of the same lines as they land, Multi-wallet log watcher subscribes to them, and the walk above applies to each notification's logs array.

07

Where it ends

The lines show what each program chose to print. A program that writes nothing leaves a frame holding only the runtime's own closing lines, and a program that prints a short message gives you the message and no account or amount. Amounts live in the balance fields of meta, and decoded instruction names need the program's IDL, as in the Anchor instruction decoder. The text after Instruction: in a log line is whatever the program author wrote and can change between versions.

getSignaturesForAddress on Carbium reaches back 30 days at most, from its own address index. Its pages go below the validator's ledger floor, so getTransaction can answer null for an older signature the list returned. The file prints that case and moves on. An empty page past 30 days is the index's age limit and does not prove the address has no older transactions.

meta.logMessages can be missing when a node did not record logs for a transaction. The walk then returns no frames, and the count check shows the full instruction total against zero.

08

When it goes wrong

what goes wrongwhat to do
getTransaction answers -32015 for a transaction that exists.Set maxSupportedTransactionVersion: 1 in the config. With it absent or 0, a version 1 transaction is refused.
getTransaction answers null for a signature from getSignaturesForAddress.The address index reaches below the validator's ledger floor, so an older signature can be listed and still be unreadable. Use the newest signatures; the file prints the null and carries on.
The frame count is lower than the instruction total.Look for the Log truncated line at the end of the array. When it is there, the missing frames were never recorded. When it is absent, check whether the transaction holds instructions that write no invoke line.
A log line lands under the wrong frame.The match on the closing line is too loose. Anchor each pattern at the start of the line and pop only when the program id equals the one on top of the stack.
The summary shows program mismatches on a transaction that looks fine.A signature precompile at outer index p writes no invoke line, so every frame after it lands one outer index too low. Increment the outer counter past any precompile id in message.instructions before stamping the next depth-1 frame.
09

Questions

Can I tell which top-level instruction wrote a line without parsing?

No. The array holds no index. The call depth in each invoke line and the order of the lines are all you have, which is why the walk keeps a stack.

Why not match logs to instructions by program id alone?

One program id can appear several times in a transaction, as a router calling the same token program for each hop. Position in the order is the only link that stays unambiguous.

Do events from `Program data:` lines belong to the frame that printed them?

Yes. The line sits between that program's invoke and its closing line, so it is stored on that frame. Decoding the base64 needs the program's own layout.

Does the same walk work on live `logsNotification` messages?

Yes. A notification carries a logs array in the same format for one transaction, so the walk applies unchanged.