library / Integrations / Relational databases / I0163
SQLite discriminator lookup
A Node script reads an Anchor IDL, stores each instruction's 8-byte discriminator in a SQLite table, then matches the instruction data of a program's newest transactions on Carbium against it.
What the program does
The program reads an Anchor IDL file, works out an 8-byte discriminator for each instruction it names, and loads those into a SQLite table. It then reads the newest signatures of one program through RPC, decodes the data of each top-level instruction, and looks its first 8 bytes up in that table. Each match is written to a second table with its signature, slot, instruction name and argument bytes.
The lookup is the part to keep. Raw transaction data holds no instruction name, but the discriminator is fixed by the program's IDL, so one indexed read answers which instruction ran. Everything else in the file is plumbing around that read.
How the discriminator is built
Anchor writes an 8-byte prefix at the start of an instruction's data. For an instruction without a custom discriminator, the prefix is the first 8 bytes of the SHA-256 hash of global: followed by the instruction name in snake_case. The IDL keeps the name in camelCase, so the code turns exactOutRoute into exact_out_route before it hashes.
| Step | Input | Output |
|---|---|---|
| Convert the name | exactOutRoute from the IDL | exact_out_route |
| Hash | global:exact_out_route | 32 bytes of SHA-256 |
| Keep the prefix | the 32 bytes | the first 8 bytes, as hex text |
| Read the data | the base58 data string from getTransaction | the first 8 bytes, as hex text |
Both sides end as the same lowercase hex text, so the match is a string comparison and the query does no hashing. Anchor's build writes the IDL under target/idl/. Check the instruction names against the program's source before you trust the table, because a misspelled name hashes to a prefix nothing sends.
Keeping the table in SQLite
The file uses node:sqlite, built into Node 24, so there is no database driver to install. The ix table keys each discriminator as TEXT PRIMARY KEY. If two instructions in one IDL hash to the same 8 bytes, the insert stops with a UNIQUE constraint error, which is the correct result, because a lookup that returns two names is ambiguous.
Both tables are dropped and created at each start, so a rerun does not stack rows. The database file idl-index.db is written to the working directory, so run the file from a directory you own.
Reading the newest transactions
The first argument is the program address. The code asks for the newest 8 signatures at confirmed, then calls getTransaction for each one with json encoding and maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and without that option the call answers -32015 for them, which is covered in transaction version errors.
In the json encoding, each instruction's data is a base58 string, and the code decodes it with the base58 codec from @solana/kit. A version 0 transaction that uses address lookup tables lists its loaded addresses in meta, so the code appends them to the static keys before it resolves programIdIndex. Instructions called from inside another program are not in the top-level list, so the code does not read them.
The call cost is small. getSignaturesForAddress costs 50 cells and runs at 0.24 req/s on Free, and getTransaction costs 50 cells each. Eight of each come to 450 cells, under the 1,024-cell burst that a rate class absorbs. A larger limit costs the same per call, so raise it on a plan with more cells per second, read the limits first.
The program
The file takes a program address as its first argument and an optional IDL path as its second. Without a path it uses the four instruction names of the IDL built into the file. It exits with a message when CARBIUM_KEY is unset, and it sends the key in the x-api-key header to the Carbium RPC endpoint.
// I0163 · SQLite discriminator lookup// https://carbium.sh/library/integrate/sqlite-discriminator-lookup// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getBase58Encoder,} from '@solana/kit';import { createHash } from 'node:crypto';import { readFileSync } from 'node:fs';import { DatabaseSync } from 'node:sqlite';const key = process.env.CARBIUM_KEY;if (!key) { console.error('Set CARBIUM_KEY to your Carbium key.'); process.exit(1);}const [programArg, idlPath] = process.argv.slice(2);if (!programArg) { console.error('Usage: node main.ts <program address> [idl.json]'); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? 'https://services.carbium.sh', headers: { 'x-api-key': key }, }),);type Idl = { instructions: { name: string }[] };type Tx = { slot: number; transaction: { message: { accountKeys: string[]; instructions: { programIdIndex: number; data: string }[] } }; meta: { loadedAddresses?: { writable: string[]; readonly: string[] } } | null;};// Instruction names of the program's IDL, used when no IDL path is given.const builtIn: Idl = { instructions: [{ name: 'route' }, { name: 'exactOutRoute' }, { name: 'sharedAccountsRoute' }, { name: 'sharedAccountsExactOutRoute' }],};// Anchor: the first 8 bytes of sha256('global:' + snake_case name).const snake = (name: string) => name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);const discriminator = (name: string) => createHash('sha256').update(`global:${snake(name)}`).digest().subarray(0, 8).toString('hex');const idl = idlPath ? (JSON.parse(readFileSync(idlPath, 'utf8')) as Idl) : builtIn;const db = new DatabaseSync('idl-index.db');db.exec('DROP TABLE IF EXISTS ix; DROP TABLE IF EXISTS hits;');db.exec('CREATE TABLE ix (disc TEXT PRIMARY KEY, name TEXT NOT NULL);');db.exec('CREATE TABLE hits (signature TEXT, slot TEXT, name TEXT, args_hex TEXT);');const put = db.prepare('INSERT INTO ix (disc, name) VALUES (?, ?)');for (const ins of idl.instructions) put.run(discriminator(ins.name), ins.name);const find = db.prepare('SELECT name FROM ix WHERE disc = ?');const save = db.prepare('INSERT INTO hits VALUES (?, ?, ?, ?)');const opts = { encoding: 'json', maxSupportedTransactionVersion: 1, commitment: 'confirmed' } as const;const sigs = await rpc.getSignaturesForAddress(address(programArg), { limit: 8, commitment: 'confirmed' }).send();const results = await Promise.allSettled(sigs.map((s) => rpc.getTransaction(s.signature, opts).send()));let nulls = 0;let fails = 0;results.forEach((res, i) => { if (res.status === 'rejected') { fails++; console.error(`failed ${sigs[i]?.signature}: ${String(res.reason)}`); return; } const tx = res.value as unknown as Tx | null; if (!tx) { nulls++; return; } // older than the ledger floor: listed, not served const keys = [...tx.transaction.message.accountKeys, ...(tx.meta?.loadedAddresses?.writable ?? []), ...(tx.meta?.loadedAddresses?.readonly ?? [])]; for (const ix of tx.transaction.message.instructions) { if (keys[ix.programIdIndex] !== programArg) continue; const bytes = Buffer.from(getBase58Encoder().encode(ix.data)); const row = find.get(bytes.subarray(0, 8).toString('hex')) as unknown as { name: string } | undefined; if (row) save.run(sigs[i]!.signature, String(tx.slot), row.name, bytes.subarray(8).toString('hex')); }});console.log(`signatures ${sigs.length}, null ${nulls}, failed ${fails}`);const counts = db.prepare('SELECT name, COUNT(*) AS n FROM hits GROUP BY name ORDER BY n DESC').all() as unknown as { name: string; n: number }[];console.log(`matched instructions: ${counts.reduce((t, r) => t + r.n, 0)}`);for (const r of counts) console.log(` ${r.name}: ${r.n}`);const sample = db.prepare('SELECT signature, name FROM hits LIMIT 3').all() as unknown as { signature: string; name: string }[];for (const s of sample) console.log(` e.g. ${s.signature.slice(0, 12)}... ${s.name}`);db.close();
run: node main.ts JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4
Run it and query the hits
Set CARBIUM_KEY, then run the command in the code block. The first lines report how many signatures were read, how many came back null, and how many instruction hits were written, followed by a count per instruction name. A count of zero for every name means the newest signatures held nothing from that IDL.
Each hit row holds the signature, slot, instruction name and argument bytes as hex. To group them yourself, open the file with any SQLite client and run SELECT name, COUNT(*) FROM hits GROUP BY name;. Decoding the argument bytes needs the argument types from the same IDL, and this file stops at the discriminator.
Where it ends
- It matches top-level instructions only, and it reads the newest 8 signatures, so the counts cover recent calls only.
- An Anchor program with a custom discriminator on an instruction will not match the computed hash. Use the bytes that IDL lists for that instruction.
- getSignaturesForAddress reaches back 30 days at most. An older signature can appear in a page and answer null from getTransaction, which the code counts and skips.
- Argument bytes are stored as hex, and this file does not decode them.
- The discriminator rule is Anchor's. Native programs and the SPL Token program use other instruction layouts, so the same lookup returns nothing for them.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every count is zero although the program is busy. | The IDL may not belong to this program, or the newest 8 signatures hold other instructions. Check the program address, then raise the limit on a plan with more cells per second. An instruction with a custom discriminator also gives zero, so compare the bytes the IDL lists with the computed hash. |
| The run ends with a UNIQUE constraint failed error on ix.disc. | Two instruction names in the IDL hash to the same 8 bytes. Use the IDL for that exact program version, or match on the discriminator bytes the IDL lists, since the table cannot hold two names under one key. |
| The log shows failed lines with error -32015. | The request lost maxSupportedTransactionVersion: 1. Keep it in the options object, which the code builds once and reuses for every getTransaction call. |
| The run exits with the CARBIUM_KEY message. | Export CARBIUM_KEY in the shell that starts node. Set it to the whole key, which the call sends in the x-api-key header. |
| Several getTransaction lines show null for signatures from weeks ago. | The address index covers 30 days. A null for an older signature is normal, and the code skips it. Read newer signatures, or accept the gap in the counts. |
Questions
Why 8 bytes and not the whole instruction name?
Anchor hashes the name with SHA-256 and keeps the first 8 bytes as the prefix, so each name gets a fixed prefix that is short enough to index. The rest of the instruction data holds the arguments.
Does the lookup see instructions called through another program?
No. The code reads the top-level instruction list only. A program called from inside a transaction appears in the inner instructions, which this file does not read.
Can I read the discriminator from the IDL instead of hashing?
Yes, when the IDL lists the bytes for an instruction, use them. The code computes the hash so one rule covers every IDL that lists names.
How far back does the match reach?
As far as the address index returns, within 30 days. Raise the limit to read more signatures per run, though older ones may answer null.