---
id: HS0035
title: "Inner instruction tree"
url: https://carbium.sh/library/howsolana/inner-instruction-tree
collection: How to use Solana
category: History and parsing
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Inner instruction tree

One TypeScript file fetches a transaction with jsonParsed encoding and prints its instructions as a tree, each cross-program call under the instruction that made it, with Explorer's flat number and a depth path. It takes a signature or an address and only reads.

## What Explorer is showing

A transaction carries a flat list of top-level instructions. When one of them calls another program, the runtime records that call as an inner instruction. Explorer draws the result as a tree: instruction 3 is a swap, and under it sit the token transfers and account writes the swap program made on its way.

The RPC returns the same material under `meta.innerInstructions`. It is a list of groups. Each group has an `index`, which is the position of the top-level instruction that caused it, and an `instructions` array holding every call made beneath that instruction, in the order they ran. The groups are flat. Nothing in the array says which inner call belongs to which parent except one field, `stackHeight`.

`stackHeight` is the depth of the call: 1 for a top-level instruction, 2 for a program it called directly, 3 for a program that one called, and so on. Walk the array in order, keep a stack, and a `stackHeight` tells you where each call hangs.

The other half is decoding. Ask for `encoding: "jsonParsed"` and the node translates the instructions of programs it knows (System, SPL Token, Token-2022, Memo, stake and a few more) into named types with fields. A program it does not know comes back with its `programId`, its account list and base58 data. Explorer decodes those with published IDLs. A plain RPC call cannot, so for those lines you see the program and nothing more.

## 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 signature, or an address, or nothing. For an address it lists the five newest signatures at `confirmed` commitment, skips the failed ones and prints the first transaction that has inner instructions. With no argument it uses the Jupiter v6 program, which is busy enough that its newest signatures nearly always carry a swap.

`main.ts` (run: `node main.ts [signature | address]`)

```ts
// HS0035 · Inner instruction tree
// https://carbium.sh/library/howsolana/inner-instruction-tree
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress, signature } from "@solana/kit";
import type { Signature } 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 Ix = { programId: string; program?: string; parsed?: { type?: string } | string; stackHeight?: number | null };
type Group = { index: number; instructions: Ix[] };
type Frame = { path: string; kids: number };

// A signature, an address (its newest signatures are used) or nothing (Jupiter v6, a busy program).
const input = process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";

function describe(ix: Ix): string {
  const kind = typeof ix.parsed === "object" ? ix.parsed.type : undefined;
  return (ix.program ?? ix.programId) + (kind ? ` (${kind})` : "");
}

function printTree(top: Ix[], groups: Group[]): void {
  top.forEach((root, i) => {
    const stack: Frame[] = [{ path: String(i + 1), kids: 0 }];
    let run = 0; // Explorer's flat number: every inner call of this instruction, in run order
    console.log(`#${stack[0].path} ${describe(root)}`);
    for (const call of groups.find((g) => g.index === i)?.instructions ?? []) {
      stack.length = Math.max(1, Math.min((call.stackHeight ?? 2) - 1, stack.length));
      const parent = stack[stack.length - 1];
      parent.kids += 1;
      run += 1;
      const frame: Frame = { path: `${parent.path}.${parent.kids}`, kids: 0 };
      stack.push(frame);
      console.log(`${"  ".repeat(stack.length - 1)}#${i + 1}.${run} [${frame.path}] ${describe(call)}`);
    }
  });
}

async function candidates(): Promise<Signature[]> {
  if (!isAddress(input)) return [signature(input)];
  const page = await client.getSignaturesForAddress(input, { limit: 5, commitment: "confirmed" }).send();
  return page.filter((row) => row.err === null).map((row) => row.signature);
}

const list = await candidates();
let printed = false;
for (const sig of list) {
  try {
    const tx = await client
      .getTransaction(sig, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "confirmed" })
      .send();
    if (tx === null) {
      console.log(`${sig}: null (older than the ledger)`);
      continue;
    }
    const top = tx.transaction.message.instructions as unknown as Ix[];
    const groups = (tx.meta?.innerInstructions ?? []) as unknown as Group[];
    if (groups.length === 0 && isAddress(input)) continue;
    console.log(`${sig} ${tx.meta?.err ? "failed" : "ok"}, ${top.length} top-level, ${groups.length} with inner calls`);
    printTree(top, groups);
    printed = true;
    break;
  } catch (e) {
    console.error(`${sig}: ${e instanceof Error ? e.message : String(e)}`);
  }
}
if (!printed) console.log("No transaction with inner instructions found.");
```

`getTransaction` is called with `commitment: "confirmed"` written out, so the call reads at confirmed commitment. The call also sets `maxSupportedTransactionVersion: 1`. Without it, a version 1 transaction comes back as an error, covered in [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015).

The tree is built in one pass per top-level instruction. A stack starts with that instruction. For each inner call the stack is cut back to `stackHeight - 1` entries, the call is attached to the last entry left and then pushed. A call at height 2 after a deep branch lands under the root again; a call at height 3 lands under the height 2 call before it. Each line carries two numbers. The first, such as `#5.3`, is Explorer's: Explorer numbers inner calls flat in run order, so it counts every call under top-level instruction 5 in the order they ran, whatever their depth. The second, in brackets, such as `[5.2.1]`, is the file's own depth path. It reads as the first call under the second call under instruction 5.

The types are cast through `unknown` because the parsed and partially decoded shapes form a union that is awkward to narrow, and the file only reads four fields from it. The fields are `programId`, `program`, `parsed` and `stackHeight`.

## Reading the output

| Field | Present on | Meaning |
|---|---|---|
| programId | every instruction | The program that ran, as a base58 address. |
| program | parsed instructions | The name the node gave the program, such as `spl-token` or `system`. |
| parsed | parsed instructions | An object with `type` and `info`, or a plain string for programs such as Memo. |
| accounts, data | unparsed instructions | The raw account list and base58 instruction data. |
| stackHeight | inner instructions | The call depth. It can be `null` on transactions old enough to predate the field. |

A typical swap prints a router call at the top, a transfer from the sender's token account under it, then a call into a pool program with its own transfers one level further down. The compute budget instructions at the front of most transactions have no children, and they print as single lines.

The `logMessages` array in `meta` is a good cross-check. Each program writes an `invoke [n]` line when it starts, where `n` is the same depth number as `stackHeight`. If a tree looks wrong, line it up against those lines and the two should agree.

> A failed transaction still lists the inner instructions that ran before the failure. The tree stops where the error hit.

## On Carbium

`getTransaction` costs 50 cells and runs at 0.24 req/s on Free, 1.2 on Dev, 5 on Business and 25 on Pro. A rate class absorbs bursts up to 1,024 cells, about 20 `getTransaction` calls, so the file's six calls at most fit inside the burst on a Free key. Sustained fetching past that burst suits a paid plan. The file stops at the first transaction with inner instructions, which is usually the first one it fetches, and prints the error of any call that fails and moves to the next signature.

The address mode adds one `getSignaturesForAddress`, also 50 cells, at 0.24, 1.2, 100 and 500 req/s on Free, Dev, Business and Pro. To decode several known signatures, send them as a JSON-RPC batch sized to the burst: 20 `getTransaction` calls come to 1,000 cells in one POST.

If you already track an address with a feed and only need a decoded view of each landed transaction, [Transaction explainer](https://carbium.sh/library/blockchainideas/transaction-explainer) shows a fuller reader built on the same call.

## Where it ends

The tree shows which programs ran and in what order. A call into a program the node cannot parse is a program id and a blob of data, and turning that into a named swap or a deposit needs the program's IDL and a decoder of your own, such as the [Anchor instruction decoder](https://carbium.sh/library/howsolana/anchor-instruction-decoder).

`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.

The field `meta.innerInstructions` can be `null` or missing when the node that served the transaction did not record inner instructions for it. If the list is empty on a transaction you know made cross-program calls, check its `invoke [n]` log lines.

Explorer also shows token labels and program names from IDLs, and those come from outside sources. Balance changes are in the same response, in `meta.preBalances`, `meta.postBalances`, `meta.preTokenBalances` and `meta.postTokenBalances`, and this file leaves them unprinted.

## When it goes wrong

| What goes wrong | What 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. Try a newer signature; the file prints the null and moves to the next. |
| Every inner line prints only a program id and no type. | The node has no parser for that program. Decode the data with the program's IDL, or read the logs for its own messages. |
| Calls land under the wrong parent. | Check that the array is walked in its given order and that `stackHeight` is read per call. Sorting or grouping the array breaks the stack. |
| For an address the file finds no transaction with inner instructions. | The five newest signatures were failed transactions or had no inner instructions. Pass a signature you know, or rerun a moment later. |

## Questions

### Why is `index` different from the position in the inner array?

`index` names the top-level instruction that caused the group. The inner array holds every call beneath it, flattened in execution order, and `stackHeight` supplies the nesting.

### Can I get the same data without `jsonParsed`?

Yes. Other encodings return the same groups with raw account indexes and base58 data, so you decode every instruction yourself. `jsonParsed` is the only one where the node names the common programs for you.

### Does a version 1 or lookup-table transaction change the tree?

The structure is the same. With `jsonParsed` the node resolves lookup-table accounts for you, and version 1 needs `maxSupportedTransactionVersion: 1` on the call.

### Why do I see Explorer lines my tree does not have?

Explorer adds program names from IDLs and token labels from other sources. Balance changes are in the response's `meta` balance arrays, which this tree does not print.

## Related

- [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) (How to use Solana, HS0012)
- [Transaction explainer](https://carbium.sh/library/blockchainideas/transaction-explainer) (Blockchain ideas, BI0003)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
