library / AI and blockchain / SI0060
On-chain IDL retrieval for models
Fetch a program's published Anchor IDL from chain, inflate it and cut it into one chunk per instruction, account and error. A public IDL adds no secret to client code, and it is the best grounding text for decoding that program.
Does a public IDL add risk?
Putting an Anchor IDL in client code shows nothing the chain does not already show. The IDL lists a program's instructions, the accounts each one takes and the types of its arguments. Anyone who sends that program a transaction has to know all of it, and the program's bytecode is public. When the authors published the IDL with anchor idl init, the same JSON also sits in an account that any RPC node returns.
So the security question moves. Hiding the IDL protects no one, because the checks that matter run inside the program: signer checks, owner checks and account constraints. An attacker without your IDL reads the bytecode or copies the shape of existing transactions. The risks that remain sit around the IDL.
- A stale copy. After a program upgrade, a bundled IDL can describe the old account order or old field layout, and a client built on it sends the wrong accounts or decodes the wrong fields.
- A replaced copy. The account carries an authority, and whoever holds it can overwrite the JSON. Read the authority before you treat the account as ground truth.
- Text the authors wrote. Doc comments and error messages are free text from the program's authors, and they travel into any prompt you build from them. A model reads them as instructions as easily as facts.
- Details you did not mean to ship. An IDL generated from a private branch can list instructions that are not deployed, with internal notes in the docs fields.
Where the IDL account lives
The IDL account has no fixed address. Anchor derives it in two steps. The first is the program's signer address, the program derived address for empty seeds. The second is createAddressWithSeed from that base, with the seed anchor:idl and the program itself as owner. Given a program id, anyone can compute the address and read it.
| Offset | Size | Content |
|---|---|---|
| 0 | 8 bytes | account discriminator |
| 8 | 32 bytes | authority that may replace the IDL |
| 40 | 4 bytes | length of the compressed data, unsigned, little endian |
| 44 | that length | zlib-compressed JSON |
Reading and inflating the account
One file, on @solana/kit and Node built-ins. Set CARBIUM_KEY first; the file exits with a message when it is missing. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh, and the key goes out in the x-api-key header.
// SI0060 · On-chain IDL retrieval for models// https://carbium.sh/library/si/on-chain-idl-retrieval-for-models// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Fetch a program's Anchor IDL from chain and cut it into chunks. Run: CARBIUM_KEY=... node main.ts [programId]import { address, createAddressWithSeed, createDefaultRpcTransport, createSolanaRpcFromTransport, getProgramDerivedAddress } from "@solana/kit";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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const KNOWN = [ "MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD", "dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH", "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc", "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo", "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4",];// IDL account: base = program signer PDA (no seeds), address = createWithSeed(base, "anchor:idl", program).// Layout: 8 discriminator, 32 authority, u32 length at 40, zlib JSON from 44.async function readIdl(program: string) { const programAddress = address(program); const [baseAddress] = await getProgramDerivedAddress({ programAddress, seeds: [] }); const idlAddress = await createAddressWithSeed({ baseAddress, programAddress, seed: "anchor:idl" }); const { value } = await rpc.getAccountInfo(idlAddress, { encoding: "base64" }).send(); if (!value) return null; const raw = Buffer.from(value.data[0], "base64"); const length = raw.readUInt32LE(40); return JSON.parse(inflateSync(raw.subarray(44, 44 + length)).toString("utf8"));}const flat = (accounts: any[]): any[] => accounts.flatMap((a) => (a.accounts ? flat(a.accounts) : [a]));// A tuple struct field has no name: print it as raw JSON.const typed = (fields: any[]) => fields.map((f) => (f.name ? `${f.name}: ${JSON.stringify(f.type)}` : JSON.stringify(f))).join(", ");// One chunk per instruction, account and error; handles the old (isMut) and new (writable) dialects.function chunks(idl: any, name: string): string[] { const out: string[] = []; for (const ix of idl.instructions ?? []) { const accounts = flat(ix.accounts ?? []).map( (a) => `${a.name}${a.writable || a.isMut ? " (writable)" : ""}${a.signer || a.isSigner ? " (signer)" : ""}`, ); const docs = ix.docs?.length ? ` ${ix.docs.join(" ")}` : ""; out.push(`${name} instruction ${ix.name}.${docs} Accounts: ${accounts.join(", ")}. Args: ${typed(ix.args ?? [])}.`); } const types = new Map<string, any>((idl.types ?? []).map((t: any) => [t.name, t.type])); for (const acc of idl.accounts ?? []) { const fields = (acc.type ?? types.get(acc.name))?.fields ?? []; out.push(`${name} account ${acc.name}. Fields: ${typed(fields)}.`); } for (const e of idl.errors ?? []) out.push(`${name} error ${e.code} ${e.name}: ${e.msg ?? ""}`); return out;}for (const program of process.argv[2] ? [process.argv[2]] : KNOWN) { try { const idl = await readIdl(program); if (!idl) { console.log(`${program}: no published IDL`); continue; } const name = idl.name ?? idl.metadata?.name ?? "unnamed"; const all = chunks(idl, name); console.log(`${program}: ${name}, ${(idl.instructions ?? []).length} instructions, ${all.length} chunks`); all.slice(0, 3).forEach((c, i) => console.log(`chunk ${i + 1}: ${c.slice(0, 300)}`)); break; } catch (e) { console.log(`${program}: failed, ${(e as Error).message}`); }}
run: node main.ts
readIdl derives the base address and the IDL address, then calls getAccountInfo with base64 encoding. The call leaves commitment out, so @solana/kit sends confirmed. A null value means no IDL account exists at that address: the authors never published one, or they closed it. Otherwise the file reads the length at offset 40, inflates bytes 44 onward with node:zlib and parses the JSON.
With no argument the file walks a short list of well-known Anchor programs and stops at the first one that has an IDL. Each program without one prints no published IDL and the walk continues. Pass a program address as the first argument to read that program only. An account read costs 10 cells, so the default walk, which tries at most five programs one after another, costs at most 50.
The output is the program name, the instruction count, the chunk count and the first three chunks, each cut to 300 characters. The chunks are plain text. The file makes no embedding call, so the vectors and the store are yours.
Chunking by instruction, account and error
An IDL answers questions of three shapes: what does this instruction need, what does this account hold, what does this error mean. Each shape gets its own chunk, so a query such as the accounts a swap takes lands on one instruction and returns its whole account list. Each chunk starts with the program name and the kind of thing it describes, which lets it stand alone once it is out of the file.
Two JSON dialects exist. Older IDLs write isMut and isSigner and put an account's fields inline. Anchor 0.30 and later write writable and signer and move the field layouts into a types list. The chunker reads both, flattens nested account groups, and looks an account's layout up by name when it is not inline.
- Instruction chunk: name, doc lines when there are any, the accounts with their writable and signer flags, and the arguments with their types.
- Account chunk: name and fields, so a retrieval for a layout finds the field order.
- Error chunk: code, name and message, one line each, which suits short queries about a failed transaction.
Splitting the JSON every few hundred characters would cut an account list in half and strip the instruction name from its own arguments. One unit per chunk keeps each retrieved passage self-contained. For turning a retrieved instruction into decoded transaction data, see Anchor instruction decoder.
What a public IDL exposes
| The IDL tells you | The IDL leaves out |
|---|---|
| instruction names and their account lists | which checks the program runs on those accounts |
| argument types | the ranges the program accepts |
| account layouts | the contents of any account, which you read separately |
| error codes and messages | the conditions that raise each error |
| doc comments | the program source |
That split is why the IDL grounds a model well. It gives the model the names and shapes it needs to read a transaction or an account, and it makes no claim about behaviour. A model that answers from it can say what an instruction takes. Whether the call is safe to send is a question for the program and for Live account RAG, where the live account data comes from the chain.
Where it ends
- Many programs have no IDL on chain. Native programs never had one, and Anchor programs only have one if the authors ran the publish step. The walk prints a clear line for each and moves on.
- A program can publish its IDL somewhere else, such as a file in its repository. The derivation here finds nothing for those, and so does any other reader of this account.
- The account holds whatever the authority last uploaded. After an upgrade the JSON can lag the deployed bytecode, and this file does not compare the two.
- The file stops at text chunks. Embedding them, storing the vectors and ranking results are separate jobs.
- The chunker covers the fields most IDLs share. Rare constructs, such as tuple struct fields, come out as raw JSON in the chunk text.
- Doc strings and error messages stay untrusted text. Put retrieved chunks in the prompt as quoted data and never as instructions.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| inflateSync throws incorrect header check. | The offsets are wrong. The length is a 4-byte little-endian integer at offset 40 and the compressed data starts at 44. Starting at 8 or 40 feeds the authority or the length into the inflater. |
| getAccountInfo returns a null value for a program you know is Anchor. | The program has no IDL at the derived address, or the authors published it somewhere else. Print the line and move to the next program. A check of the seed spelling anchor:idl rules out a typo. |
| Chunks read undefined for names or show empty account lists. | The IDL uses the other dialect. Read writable and isMut for the same flag, signer and isSigner for the other, and take account layouts from types when the account has no inline type. |
| A retrieved doc string tells the model to ignore its earlier instructions. | Doc comments and messages are free text from the program's authors. Place chunks in the prompt as quoted data, and keep tool permissions narrow enough that a hostile passage can do nothing. |
Questions
Is it safe to bundle a program's IDL in a browser app?
Yes, because the IDL describes an interface that is already public in the program's bytecode and in an account any node returns. The checks that protect funds run inside the program, so hiding the IDL protects nothing. The remaining risk is a stale or replaced copy, so refresh a bundled IDL after each upgrade.
Can someone change the IDL on chain?
The authority stored at offset 8 can replace it. Read that address and compare it with the program's known maintainers before you trust a changed IDL. A bundled copy has the opposite problem: it never changes, so it goes stale after an upgrade.
Do I need the IDL to decode a program's accounts?
You need the layout, and the IDL is the easiest place to get it. Without one you work from the program's source or from hand-written decoders. Anchor instruction decoder shows an instruction decoder that uses a layout.
Why not split the IDL JSON every few hundred characters?
A fixed-size split cuts an account list in half and separates an instruction from its arguments, so a retrieved passage answers only part of the question. One chunk per instruction, account and error stays whole.