library / AI and blockchain / SI0070
Program interaction audit
A past call keeps power over a wallet only through account fields it changed, such as a delegate or an authority. The script lists programs a wallet's newest transactions invoked, with call counts, known names and slot range, so you know which to inspect.
What persists after an interaction
A call to a program on Solana keeps power over a wallet only through account fields it changed. The transaction ran, changed the accounts it listed as writable and finished. A program that behaved badly in the past can act on a wallet today only if that transaction left something in the wallet's accounts that grants it power.
| Change | Instruction that makes it | Where it shows | What it allows |
|---|---|---|---|
| Delegate | Token Approve | delegate and delegatedAmount on the token account | The delegate moves tokens up to the allowance with its own signature |
| Changed authority | Token SetAuthority, Stake program Authorize, AuthorizeNonceAccount | owner or closeAuthority on a token account, the authority fields on a mint, the staker and withdrawer on a stake account, the authority on a nonce account | The new holder acts with no signature from the old owner |
| Reassigned owner | System Program Assign | owner on the wallet account itself | The program that now owns the account can move its SOL |
Swaps, mints, transfers, memos and claims leave history only. They tell you who a wallet dealt with and grant nothing. The audit therefore has two halves: a list of every program the wallet's transactions invoked, which is history, and a read of the fields above, which is live exposure. The list decides where the reads look.
Listing the programs a wallet invoked
Every instruction in a transaction names a program, and the programs that one calls in turn appear in the transaction's metadata as inner instructions. A swap with three top-level instructions can reach a dozen programs this way, so reading only the top level misses everything the first program called on. The inner instruction tree entry shows how those nested calls are laid out. This audit flattens them and counts.
The script takes a wallet address. With no argument it picks one: the fee payer of a successful transaction among the newest signatures of the Compute Budget program, which almost every transaction carries. It then calls getSignaturesForAddress on the wallet for the newest eight and runs getTransaction on all eight at once with jsonParsed encoding and maxSupportedTransactionVersion: 1, so a v1 transaction does not answer -32015. Each call is settled alone: one that fails prints its error while the rest still count, and a null answer is counted and skipped. Both methods cost 50 cells a call. Calls leave commitment out, so @solana/kit 8.6.0 fills in confirmed.
// SI0070 · Program interaction audit// https://carbium.sh/library/si/program-interaction-audit// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Audit which programs a wallet's newest transactions invoked. Run: CARBIUM_KEY=... node main.ts [wallet]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";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: Record<string, string> = { "11111111111111111111111111111111": "System Program", TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA: "Token program", TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb: "Token-2022", ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL: "Associated Token Account", ComputeBudget111111111111111111111111111111: "Compute Budget", MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr: "Memo v2", AddressLookupTab1e1111111111111111111111111: "Address Lookup Table",};type Ix = { programId: string };type Tx = { slot: bigint; transaction: { message: { accountKeys: { pubkey: string }[]; instructions: Ix[] } }; meta: { err: unknown; innerInstructions?: { instructions: Ix[] }[] | null } | null;};const why = (error: unknown) => (error instanceof Error ? error.message : String(error));// No argument: take the fee payer of a recent successful Compute Budget transaction.async function findWallet(): Promise<string | undefined> { try { const sigs = await rpc.getSignaturesForAddress(address("ComputeBudget111111111111111111111111111111"), { limit: 10 }).send(); for (const { signature, err } of sigs) { if (err) continue; try { const res = await rpc.getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send(); const tx = res as unknown as Tx | null; if (tx) return tx.transaction.message.accountKeys[0].pubkey; } catch (error) { console.log(`getTransaction ${signature} failed: ${why(error)}`); } } } catch (error) { console.log(`getSignaturesForAddress failed: ${why(error)}`); } return undefined;}const wallet = process.argv[2] ?? (await findWallet());if (!wallet) { console.error("no wallet found; pass one as an argument"); process.exit(1);}console.log(`wallet ${wallet}`);const sigs = await rpc.getSignaturesForAddress(address(wallet), { limit: 8 }).send().catch((error: unknown) => { console.error(`getSignaturesForAddress failed: ${why(error)}`); return process.exit(1);});const results = await Promise.allSettled( sigs.map(({ signature }) => rpc.getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()),);const seen = new Map<string, { calls: number; top: number; inner: number; first: bigint; last: bigint }>();let read = 0, missing = 0, failed = 0;results.forEach((res, i) => { if (res.status === "rejected") { console.log(`getTransaction ${sigs[i].signature} failed: ${why(res.reason)}`); return; } const tx = res.value as unknown as Tx | null; if (!tx) { missing++; return; } read++; if (tx.meta?.err) failed++; const calls = [ ...tx.transaction.message.instructions.map((ix) => [ix.programId, true] as const), ...(tx.meta?.innerInstructions ?? []).flatMap((group) => group.instructions.map((ix) => [ix.programId, false] as const)), ]; for (const [id, isTop] of calls) { const row = seen.get(id) ?? { calls: 0, top: 0, inner: 0, first: tx.slot, last: tx.slot }; row.calls++; if (isTop) row.top++; else row.inner++; if (tx.slot < row.first) row.first = tx.slot; if (tx.slot > row.last) row.last = tx.slot; seen.set(id, row); }});console.log(`${read} transactions read, ${missing} null, ${failed} failed on chain`);for (const [id, row] of [...seen].sort((a, b) => b[1].calls - a[1].calls)) { console.log(`${id} calls ${row.calls} top ${row.top} inner ${row.inner} first slot ${row.first} last slot ${row.last} ${KNOWN[id] ?? "unknown"}`);}
run: node main.ts
Run node main.ts <wallet> with CARBIUM_KEY set, or with no wallet to audit a fresh one. After the wallet line, one line counts transactions read, null answers and transactions that failed on chain. Then comes one line per program id, busiest first: the calls, how many were top-level and how many inner, the first and last slot it appeared in, and a name or unknown. A failed transaction still counts its calls, because it did invoke those programs, and it left nothing behind except the fee.
Sorting known from unknown
The script carries a short table of ids it can name: the System Program, the Token program, Token-2022, the Associated Token Account program, Compute Budget, Memo and the Address Lookup Table program. Those are the plumbing of nearly every wallet's history. Anything else prints unknown, which says only that the script has no name for the id.
| Line in the output | Reading | Next read |
|---|---|---|
| Known name, high count | Ordinary plumbing | None |
| Unknown id, many calls across many transactions | A program the wallet's apps use habitually, such as a swap router or a game | Look the id up in a public explorer and check who maintains it |
| Unknown id, inner calls only | Another program reached it, so the top-level program made the choice | Read that transaction's top-level program and instruction |
| Unknown id near the date of a bad interaction | The first program to examine | getTransaction on that signature, then the follow-up checks |
An unknown program is not a malicious one. Most ids a wallet meets are small applications the script has no name for, and an id that did harm looks the same in this list as one that did not. Calling a program malicious takes evidence from the transaction: an Approve, a SetAuthority or an Assign on the wallet's accounts that the owner never intended. The counts and slots only tell you which transactions to open.
Follow-up checks on live exposure
- Open the transactions behind each unknown id with getTransaction and read the instruction types. An Approve, SetAuthority or Assign on the wallet's own accounts is the finding. A transfer or a swap is history.
- Run the delegate exposure scan on the wallet. It lists every delegate and allowance on the Token and Token-2022 accounts and reports an account whose close authority is another address.
- Call getAccountInfo on the wallet. Its owner should be the System Program, 11111111111111111111111111111111. Any other owner means an Assign happened and that program holds the wallet.
- For each token the wallet minted, read the mint account and check that the mint and freeze authorities are the addresses you expect.
- Revoke what you find. The owner signs a Revoke for a delegate, from a wallet app a person runs and never from the agent whose history you audited.
None of this inspects a key. A program call cannot read a private key, so a seed phrase typed into a page or a key file handed to a hostile tool is a separate exposure. If that happened, treat the wallet as lost: move the assets to a fresh wallet first and revoke afterwards.
Where it ends
- The history reaches back 30 days at most. getSignaturesForAddress reads an address index that keeps up to 30 days, and an empty page past that is the index's age limit, so the wallet may have older transactions. A bad interaction from last year does not show in the list, though a delegate it left behind still shows in the follow-up reads.
- The script reads the newest eight transactions. A wallet with heavy traffic has pushed older interactions out of that window. Raise limit and page with before, as signature history pagination shows, at 50 cells for each extra transaction.
- getTransaction can answer null for a signature the index lists, because the index reaches below the validator's ledger floor. The script counts these, and the transactions behind them stay unread.
- The list comes from transactions that mention the wallet, including ones another party sent to it. A dust transfer from a stranger puts that stranger's programs in the list with no action by the owner.
- A transaction signed in advance against a durable nonce is not on chain until someone submits it, so no read shows it. Advancing the nonce voids it when the wallet holds the nonce authority; otherwise move the assets to a fresh wallet.
- A clean result is no promise that the wallet is safe. It says the reads found nothing in the window. A leaked key, or a drain that already took everything, leaves nothing to find.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTransaction answers -32015 for some signatures. | Pass maxSupportedTransactionVersion: 1 with an encoding. Mainnet carries v1 transactions, and an absent or 0 value gets the error for them. |
| getTransaction returns null for a signature the address listing returned. | The index reaches below the validator's ledger floor, so an older signature can list and read as null. Count the null, skip it and audit the newest signatures. |
| The report calls an unknown program malicious. | Label it unknown, open the transactions behind it and look for Approve, SetAuthority or Assign on the wallet's accounts before saying more. |
| An old wallet shows no programs at all. | An empty page past 30 days is the index's age limit, so the wallet may have older transactions. Older history needs another source. |
| A program reached only through another program is missing from the list. | Read meta.innerInstructions as well as the top-level instructions, as the script does, and count both. |
Questions
Does calling a malicious program leave it control of my wallet?
Not by itself. Control persists only through a delegate, a changed authority or a reassigned owner, and those are fields you can read. A program that never received one of them has nothing left to act on.
How far back does the audit see?
Thirty days at most, the span of the address index behind getSignaturesForAddress. Anything older needs a separate source.
Does the script sign or change anything?
No. It makes read calls and prints. Revoking a delegate is a separate step that the owner signs.
Why count inner instructions?
A program that a transaction calls through another program shows up only there. A hostile program placed behind a familiar router would never appear among the top-level instructions.
Which calls does the no-argument run make?
One getSignaturesForAddress on the Compute Budget program and getTransaction until it finds a successful fee payer. Then one getSignaturesForAddress on that wallet and eight getTransaction calls.