library / How to use Solana / HS0067
Instruction log filter
One TypeScript file subscribes to a program's logs, finds the lines that name an instruction inside that program's own frame, and prints signature, slot and err for each match. It stops after a set time and prints totals. It only reads.
What the server filters and what it leaves to you
logsSubscribe on Carbium streams transaction logs, either all of them or those that mention one address. The mention filter works on accounts: a transaction passes when the address is among its account keys. Nothing in the request can name an instruction. Mention the Token-2022 program and you receive every transaction that invokes it, whether it moves tokens, mints, closes an account or sets a delegate.
Each notification carries a signature, an err field and an array of log lines. Deciding from those lines whether a transaction ran the instruction you care about is your job, and the server has already sent you the transactions you throw away.
| Question | Who answers it |
|---|---|
| Does the transaction involve this program? | The server, through mentions |
| Which instruction ran? | Your code, from the log lines |
| Did the transaction succeed? | The err field, null on success |
| What amounts moved? | Neither: fetch the transaction |
The match, and why the frame matters
The runtime writes a program's own output as Program log: ... lines, and the SPL token programs print Program log: Instruction: <Name> as they start an instruction. That line has no program id on it. Its owner is whichever program is innermost at that point in the log. An invoke line (Program <id> invoke [depth]) opens a frame, and a success or failed: line for that id closes it.
A plain search for the text Instruction: TransferChecked goes wrong for two reasons. The original SPL Token program prints the same line, so a transaction that also invokes Token-2022 can carry a TransferChecked line that Token-2022 never wrote. And a router that calls Token-2022 through a cross-program call puts the line at depth 2 or deeper, so a check on the first frame misses it.
The file keeps a stack of program ids as it walks the lines. It pushes on invoke, pops on success or failed, and counts the Instruction: line only when the program on top of the stack is the one you watch. The comparison is an exact line match, so TransferChecked never matches TransferCheckedWithFee.
The code
Export CARBIUM_KEY and run the file with Node 24. The first argument is the instruction name and defaults to TransferChecked. The second is how many seconds to watch and defaults to 20.
// HS0067 · Instruction log filter// https://carbium.sh/library/howsolana/instruction-log-filter// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITconst key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1);}const PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"; // Token-2022const wanted = process.argv[2] ?? "TransferChecked";const seconds = Number(process.argv[3] ?? 20);const url = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");url.searchParams.set("api-key", key);// True when `wanted` is logged while PROGRAM is the innermost running program.function ran(logs: string[]): boolean { const frames: string[] = []; for (const line of logs) { const open = /^Program (\w+) invoke \[\d+\]$/.exec(line); if (open) frames.push(open[1]); else if (/^Program \w+ (success|failed)/.test(line)) frames.pop(); else if (line === `Program log: Instruction: ${wanted}` && frames.at(-1) === PROGRAM) return true; } return false;}let seen = 0;let matched = 0;let bytes = 0;const ws = new WebSocket(url);ws.addEventListener("open", () => { ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [PROGRAM] }, { commitment: "confirmed" }] })); setTimeout(() => ws.close(), seconds * 1000);});ws.addEventListener("message", (ev) => { const text = String(ev.data); bytes += text.length; const msg = JSON.parse(text); if (msg.id === 1) { if (msg.error) { console.error(`subscription refused: ${msg.error.message}`); ws.close(); } else console.log(`watching ${wanted} for ${seconds} s`); } else if (msg.method === "logsNotification") { const { context, value } = msg.params.result; seen++; if (!ran(value.logs ?? [])) return; matched++; console.log(`${value.signature} slot=${context.slot} err=${JSON.stringify(value.err)}`); }});ws.addEventListener("error", () => console.error("socket error"));ws.addEventListener("close", () => { console.log(`seen ${seen}, matched ${matched}, about ${(bytes / 1024).toFixed(0)} KiB received`); process.exit(0);});
run: node main.ts [InstructionName] [seconds]
The subscription asks for confirmed commitment. Every match prints the signature, the slot and the raw err value. When the timer closes the socket, the file prints how many transactions it saw, how many matched, and about how many KiB arrived. That last figure is the text length of the messages, close to the bytes sent for log lines, and the meter charges 20 credits for each MiB of it.
Failed transactions and the err field
A transaction that fails still produces logs, and the logs run up to the point of failure. The Instruction: line for your instruction can appear in a transaction whose later instruction failed, and the runtime then reverts the whole transaction. The line says the program began that instruction. It does not say the transfer happened.
That is why the file prints err beside every match. A null err means the transaction succeeded. Anything else is an error object, such as an instruction error with an index. If you want only completed work, skip every match whose err is not null.
A failed transaction closes its last frame with Program <id> failed: <reason>. The file closes the frame on that line as it does on success.
What logs cannot tell you
- Programs that log no instruction names. The System program and many custom programs print nothing of the kind, and some print their own wording. Anchor programs print Instruction: <Name> by default, but a program built another way may not. Run the file against a program and look at what it prints before trusting a silent result.
- Truncated logs. The runtime caps how much a transaction may log, and a long one ends with a Log truncated line. Instructions that run after the cap leave no line, so a transaction can contain your instruction and still not match.
- Amounts and accounts. The line carries a name only. The amount, mint, source and destination are in the instruction data and account list, which logs omit.
- Two instructions of one name in a transaction. The file reports the transaction once, since it returns at the first match.
For amounts, fetch the transaction by signature with getTransaction, which costs 50 cells. Pass maxSupportedTransactionVersion: 1 with an encoding, or a v1 transaction answers -32015. Inner instruction tree shows how to read nested calls from the result.
What the filter costs
Opening a logsSubscribe with mentions costs 25 credits, and a subscription to all logs costs 200. After that the meter runs at 20 credits per MiB sent. Because the instruction filter runs in your process, you pay for every transaction the server sends, matching or not. Token-2022 traffic is steady, so a long watch adds up in MiB, and the KiB figure the file prints at the end tells you the cost of a run.
A refused subscription costs nothing. Subscription and connection counts are capped per account by plan, and Free carries 5 sockets. Credits are spent on WebSocket work and on RPC calls alike, and an account's keys share one budget.
Where it ends
The file does not reconnect. A dropped socket ends the run, and anything sent while it was down is gone. Multi-wallet log watcher shows a reconnect with backoff and a backfill from getSignaturesForAddress, which can only list signatures and their err flags, so a backfilled signature needs getTransaction before the instruction filter can run on it.
One subscription mentions one program. To watch two programs, open two subscriptions and keep one stack check per program. The match depends entirely on what a program logs, so it is a screen for candidates. When a missed or false match is expensive, confirm each candidate by decoding the transaction itself.
A mention subscription can send a busy program's whole traffic. If the stream gets heavy for your plan, narrow the address: mention a mint or an account only your instruction touches, and keep the frame check for exactness.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The file prints the watching line and then only totals with matched 0. | The name is compared as an exact, case-sensitive line. Check the spelling against a log you have seen, and remember that TransferCheckedWithFee is a different instruction from TransferChecked. Run once with the default name to confirm the stream and the match logic work. |
| Matches appear for transactions that did not move anything. | Those transactions failed after your instruction began. Print or test err and skip every match where it is not null. |
| A program you know is active never matches. | It may log no instruction names, or its transaction logs were truncated before the line. Fetch one of its transactions with getTransaction and read the logs there to see what it prints. |
| The first message is subscription refused. | Subscription and connection counts are capped per account by plan, and Free carries 5 sockets. Close other watchers on the account or move up a plan. A refused subscription costs no credits. |
| The file prints socket error and then seen 0, matched 0, with no watching line. | The door answered 401 because the key was not recognised, and Node's WebSocket does not show you that status. Attach the whole key in CARBIUM_KEY, with no trailing characters cut off. |
| getTransaction on a matched signature answers -32015. | The transaction is v1. Pass maxSupportedTransactionVersion: 1 and an encoding on the call. |
Questions
Can the server filter by instruction name for me?
No. The mentions filter takes an address, so the server narrows by account and leaves the instruction to your code. You pay for each transaction it sends before your filter drops it.
Does a program called only through another program still match?
Yes. A program invoked in a cross-program call must be in the transaction's account keys, so the mention matches. The frame stack then finds its Instruction: line at depth 2 or deeper.
Why not search the logs for the instruction text?
Any program can print the same words, and the line carries no program id. Tracking invoke and success lines ties the text to the program that printed it.
Does this work for programs other than Token-2022?
It works for any program that prints Instruction: <Name> in its own frame, which includes Anchor programs by default. Change the program id in the file and the name in the first argument.