services
Get a key

library / Blockchain ideas / BI0049

On-chain IDL extractor

Check up to 100 Solana programs for a published Anchor IDL in one account read, inflate and sanity-check each document, and get an idl folder of JSON files plus a printed table of program, IDL, bytes, name and instruction count.

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

01

Who uses it

An IDL is the JSON file that names a program's instructions, accounts and types. Explorers use it to label an instruction, wallets use it to show what a transaction asks for, and client generators turn it into typed code. A team that integrates twenty programs needs twenty of these files, and collecting them by hand from repositories and chat threads goes stale.

Tooling and explorer teams want the file as the program's authors published it on chain, gathered by one command that covers the whole list. A hackathon team can point the same script at the busiest programs of the moment and see which of them are decodable before choosing what to build on.

02

Where Anchor keeps an IDL

The anchor idl init command stores the IDL in an account owned by the program itself. The address comes from the program id alone, in two steps. A program address derived from an empty seed list gives a base key. Then createAddressWithSeed takes that base, the program as owner and the seed anchor:idl. The result stays the same across upgrades, so a sweep can compute it for any program without a lookup.

BytesContent
0 to 7account discriminator
8 to 39authority allowed to replace the IDL
40 to 43length of the compressed data, u32 little-endian
44 onwardthe IDL JSON, zlib-compressed

A program that never ran anchor idl init, or one not written in Anchor, has no account at that address, and the read answers null. That is a normal result, and a sweep over real programs returns plenty of them: native programs, hand-written Rust programs and teams that publish their IDL somewhere else all land there.

03

The sweep

The script is one file on @solana/kit and Node 24. It reads from the chain and writes only into an idl folder beside where you run it. Nothing is signed or sent.

  1. Take up to 100 program ids from the command line. With no argument, read a recent block at confirmed with maxSupportedTransactionVersion: 1, and take the programs its transactions invoke, most invoked first. If a slot was skipped, the script tries up to five slots further back.
  2. Derive the IDL address of each program.
  3. Read all the addresses in one getMultipleAccounts call at confirmed, with base64 encoding.
  4. For each answer, null means no IDL. Otherwise check the owner and the length, inflate inside a try, parse the JSON and check its name, instruction list and address.
  5. Write each document that passes to idl/<program>.json and print one row: program, IDL yes, no or bad, inflated bytes, name and instruction count.
main.ts
// BI0049 · On-chain IDL extractor// https://carbium.sh/library/blockchainideas/on-chain-idl-extractor// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createAddressWithSeed, createDefaultRpcTransport, createSolanaRpcFromTransport, getProgramDerivedAddress } from "@solana/kit";import { mkdirSync, writeFileSync } from "node:fs";import { inflateSync } from "node:zlib";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const given = process.argv.slice(2);if (given.length > 100) {  console.error("Usage: node main.ts [<program id> ...]  (up to 100 programs)");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);type Tx = { transaction?: { message?: { accountKeys?: string[]; instructions?: { programIdIndex: number }[] } } };// No argument: programs invoked at the top level of a recent block, most invoked first.async function recentPrograms(): Promise<string[]> {  const tip = await rpc.getSlot({ commitment: "confirmed" }).send();  for (let back = 2n; back < 8n; back++) {    try {      const block = await rpc        .getBlock((tip - back) as typeof tip, { commitment: "confirmed", encoding: "json", transactionDetails: "full", rewards: false, maxSupportedTransactionVersion: 1 })        .send();      if (!block) continue;      const counts = new Map<string, number>();      for (const tx of block.transactions as unknown as Tx[]) {        const m = tx.transaction?.message;        for (const ix of m?.instructions ?? []) {          const p = m?.accountKeys?.[ix.programIdIndex];          if (p) counts.set(p, (counts.get(p) ?? 0) + 1);        }      }      return [...counts].sort((a, b) => b[1] - a[1]).slice(0, 100).map(([p]) => p);    } catch (e) {      console.error(`slot ${tip - back} skipped:`, e instanceof Error ? e.message : e);    }  }  return [];}const ids = [...new Set(given.length > 0 ? given : await recentPrograms())];if (ids.length === 0) {  console.error("No programs to check.");  process.exit(1);}const programs = ids.map((id) => address(id));// Anchor's IDL account: create-with-seed from the program's empty-seed PDA, seed "anchor:idl", owner the program.const idlAddresses = await Promise.all(  programs.map(async (programAddress) => {    const [baseAddress] = await getProgramDerivedAddress({ programAddress, seeds: [] });    return createAddressWithSeed({ baseAddress, programAddress, seed: "anchor:idl" });  }),);const res = await rpc  .getMultipleAccounts(idlAddresses, { commitment: "confirmed", encoding: "base64" })  .send()  .catch((e) => {    console.error("getMultipleAccounts failed:", e instanceof Error ? e.message : e);    return process.exit(1);  });mkdirSync("idl", { recursive: true });console.log(["program", "idl", "bytes", "name", "instructions"].join("\t"));res.value.forEach((acct, i) => {  const program = programs[i];  const row = (idl: string, bytes: number | string = "-", name = "-", n: number | string = "-") =>    console.log([program, idl, bytes, name, n].join("\t"));  if (!acct) return row("no");  try {    // 8-byte discriminator, 32-byte authority, u32 length, then the zlib stream.    const raw = Buffer.from(acct.data[0], "base64");    if (acct.owner !== program || raw.length < 44) return row("bad: wrong owner or too short");    const json = inflateSync(raw.subarray(44, 44 + raw.readUInt32LE(40)));    const idl = JSON.parse(json.toString("utf8"));    const name = idl.metadata?.name ?? idl.name;    if (typeof name !== "string" || !Array.isArray(idl.instructions)) return row("bad: no name or instructions");    if (idl.address !== undefined && idl.address !== program) return row("bad: address field differs", json.length, name, idl.instructions.length);    writeFileSync(`idl/${program}.json`, json);    row("yes", json.length, name, idl.instructions.length);  } catch (e) {    row(`bad: ${e instanceof Error ? e.message : e}`);  }});

run: CARBIUM_KEY=<YOUR_KEY> node main.ts [<PROGRAM_ID> ...]

A document that fails a check is not saved, and its row says why in the IDL column. The folder holds only documents that passed, so a later step can read every file in it without guarding for junk.

04

Checks that raise confidence

Inflating and parsing prove little alone, since any JSON can sit in an account. Four cheap checks raise confidence that a file is the program's own IDL:

  • The account is owned by the program whose address was derived, which is what an account Anchor created for that program looks like.
  • The bytes inflate. A zlib error means the account holds something other than an IDL, or a cut-off one.
  • The JSON has a name and an instructions array. Files from Anchor 0.30 on put the name in metadata.name, and older files put it at the top level as name.
  • In the newer format the address field must equal the program id. A mismatch means the document was uploaded from another deployment. Older files carry no address field and skip this check.

A document that passes all four is likely the program's IDL. What it cannot show is that the deployed code behaves as the file describes.

05

What it costs

A sweep is one call. Cells are the admission charge per call, and getMultipleAccounts charges 10 cells per pubkey: 1000 cells for 100 programs, or 1001 when the request body passes 4 KiB, which a list of 100 base58 addresses is likely to do. Below Pro the 1,024-cell burst caps a call at 100 pubkeys, so the script exits above 100 and runs on every plan. A Pro key can send up to 300 pubkeys in a call.

PlanAccount reads (getAccountInfo, getMultipleAccounts), req/s
Free0.5
Dev15
Business50
Pro400

With no argument the script also reads the tip with getSlot, a cheap cached read at 1 cell, and one getBlock call for the block. Limits are per account, so other tools on the same keys draw on the same budget.

06

Refreshing after an upgrade

An IDL moves on its own schedule. The IDL authority replaces the document with anchor idl upgrade, and a program upgrade leaves it untouched, so the file can lag the code or run ahead of it. Rerun the sweep after an upgrade of a program you depend on: the script overwrites idl/<program>.json with what the account holds now.

Commit the folder to git and a diff between two sweeps shows which instructions were added or removed. To know when to rerun, the Program upgrade watcher prints a line when a program's deploy slot changes. To turn a saved file into decoded instructions, see the Anchor instruction decoder.

07

Where it ends

  • Only programs whose team ran Anchor's on-chain IDL upload appear. A no means nothing sits at the derived address. It does not say the program is not Anchor.
  • The IDL is a document written by its authority. Nothing ties it to the bytecode that runs, so a stale or wrong file passes every check above. Compare it with a few real transactions before building on it.
  • The authority can replace the document at any time, so a saved file is a snapshot of one moment.
  • The no-argument list comes from the top-level instructions of one block. A program that is only called through another program's CPI, or that was quiet in that block, is missing, and the busiest entries are usually native programs that answer no.
  • A passing document has instruction names and a matching address. Whether its argument and account lists are right is not checked.
08

When it goes wrong

what goes wrongwhat to do
Every row says no, including for a program you know has an IDL.The team may publish its IDL elsewhere, or the account was closed. Read the derived address with getAccountInfo to see whether it exists. A null answer is final for this method.
A row says bad with a zlib error such as incorrect header check.The account at that address does not hold a compressed IDL, or the stored length cuts the data short. Skip the program and look at the raw account bytes if you need the cause.
A row says bad: address field differs.The document was uploaded from another deployment of the program. Do not use it, and ask the program's team for the right file.
With no argument the run prints skipped slots and exits with No programs to check.Each of the six slots tried was skipped or failed. Run again, or pass program ids on the command line.
getBlock answers -32015.The block holds a v1 transaction and the call left maxSupportedTransactionVersion out or set it to 0. The script sends 1, so keep that value if you change the call.
The call comes back with 429.Wait for the retry-after hint and run the sweep again. It is one call, so nothing is half done. On Free, one 100-program call uses almost the whole 1,024-cell burst, so a second call right behind it is likely to get 429 as well.
09

Questions

How do I find the IDL account of a Solana program?

Derive a program address from the program id with an empty seed list, then call createAddressWithSeed with that address as base, the program as owner and the seed anchor:idl. The result depends only on the program id, so it never changes.

Can I get an IDL for a program that did not publish one?

Not from this read. The sweep reports no and moves on. Anchor derives instruction discriminators from instruction names, so a decoder can try known names against them, but the file itself has to come from the program's authors.

Does it handle both IDL formats?

Yes. The name check accepts metadata.name or a top-level name, and the address check runs only when the file has an address field.

Why does the sweep use one call for all programs?

getMultipleAccounts answers up to 100 addresses at a time on every plan, so the whole list is read together at one commitment and the result is easy to rerun.