library / AI and blockchain / SI0065
Unrecognized outgoing transfer alert
A read-only Node script that reads a wallet's recent transactions, finds the ones the wallet signed and lost lamports in, and labels each destination known or first-seen. Each alert comes with a JSON evidence line a model can read.
What a signature proves
Very little about the person. A Solana signature proves that someone held the private key behind the signing address when the transaction was built. That key comes from a seed phrase, and a seed phrase copied once is a seed phrase two people hold. The chain records no device, no location and no intent, so no read of a transaction can say whether the owner or a thief signed it.
A narrower question has an answer: does this transaction look like the wallet's own past? A drained wallet usually shows a destination the wallet never paid before, often for most of the balance. Those are properties of the history, and the script scores the destination and the size of the send.
Treat its output as a lead for a person or an agent to follow. A first-seen destination is also what a new payee, a fresh exchange deposit address or a rotated hot wallet looks like.
Building the known-destination set
The known set holds every address that gained lamports in a transaction the wallet signed and lost lamports in. The script keeps it in a SQLite file, known.db, in the directory you run from, so a second run remembers the first. It reads the wallet's five newest signatures with `getSignaturesForAddress`, fetches those five transactions with getTransaction, and walks them oldest first. Each transaction is judged against the set as it stood before it, and then its recipients join the set.
Five transactions make a thin baseline. On a fresh file the oldest transaction's recipients are first-seen by definition. For a real watch, fill the file once from a longer walk before you start alerting: page back with before and read each page. The address index behind that call keeps up to 30 days, and an empty page past that is the index's age limit. The wallet may have older transactions that the index never serves, so a payee last paid 31 days ago will look new.
Pages from that index reach below the validator's ledger floor, so getTransaction can answer null for a signature the page listed. The script prints null for it and moves on. A null leaves a gap in the baseline and says nothing about the transfer.
Scoring one outgoing transfer
For each transaction the script reads three things: the signer flag on the wallet's account key, the wallet's lamports before and after, and every other account whose lamports rose. The outflow is the wallet's decrease minus the fee when the wallet pays it, so a fee-only transaction has no outflow. A failed transaction prints skip and is never scored. The read asks for jsonParsed with maxSupportedTransactionVersion: 1, because with that value absent or 0 a v1 transaction answers -32015 instead of data. Every call asks for confirmed.
| Flag | Fires when | Why it matters |
|---|---|---|
| first-seen-destination | A gaining account is not in the known set | The one signal that separates a new payee from routine payments |
| half-or-more-of-balance | The outflow is at least half the balance before | Someone emptying a wallet takes what is there |
| drained | The balance after is 0 | A full drain ends most thefts and also a deliberate sweep to a new wallet |
// SI0065 · Unrecognized outgoing transfer alert// https://carbium.sh/library/si/unrecognized-outgoing-transfer-alert// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Unrecognized outgoing transfer alert, read only. Run: CARBIUM_KEY=... node main.ts [wallet address]import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Signature } 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 apiKey: string = key;const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey }, }),);type Num = number | bigint;type Tx = { meta: { err: unknown; fee: Num; preBalances: Num[]; postBalances: Num[] } | null; slot: Num; transaction: { message: { accountKeys: { pubkey: string; signer: boolean }[] } };};// confirmed, v1 allowed; the answer is null when the node no longer holds the transactionconst load = async (signature: Signature) => (await rpc .getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "confirmed" }) .send()) as unknown as Tx | null;const db = new DatabaseSync("known.db");db.exec("create table if not exists known (address text primary key, first_signature text)");const isKnown = db.prepare("select 1 from known where address = ?");const learn = db.prepare("insert or ignore into known values (?, ?)");// With no argument: the fee payer of the newest landed transaction on a busy swap program.async function discover(): Promise<string> { const program = address(process.env.PROGRAM ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"); const page = await rpc.getSignaturesForAddress(program, { limit: 5, commitment: "confirmed" }).send(); const landed = page.find((s) => s.err === null); const tx = landed ? await load(landed.signature) : null; const payer = tx?.transaction.message.accountKeys[0]?.pubkey; if (!payer) throw new Error("no readable transaction on the program"); return payer;}const wallet = address(process.argv[2] ?? (await discover()));console.log(`wallet ${wallet}`);function score(signature: string, tx: Tx): void { const { meta, transaction } = tx; const keys = transaction.message.accountKeys; const i = keys.findIndex((k) => k.pubkey === wallet); if (!meta || meta.err !== null || i < 0) return void console.log(`skip ${signature} (failed or wallet not listed)`); const pre = Number(meta.preBalances[i]); const post = Number(meta.postBalances[i]); const out = pre - post - (i === 0 ? Number(meta.fee) : 0); if (!keys[i].signer || out <= 0) return void console.log(`quiet ${signature} (${keys[i].signer ? "signed" : "not signed"}, no outflow)`); const to = keys .map((k, j) => ({ address: k.pubkey, gained: Number(meta.postBalances[j]) - Number(meta.preBalances[j]) })) .filter((r) => r.gained > 0 && r.address !== wallet) .map((r) => ({ ...r, firstSeen: !isKnown.get(r.address) })); const flags: string[] = []; if (to.some((r) => r.firstSeen)) flags.push("first-seen-destination"); if (pre > 0 && out / pre >= 0.5) flags.push("half-or-more-of-balance"); if (post === 0) flags.push("drained"); console.log(`${flags.length ? "ALERT" : "known"} ${signature} out ${out} lamports`); if (flags.length) { console.log(JSON.stringify({ wallet, signature, slot: Number(tx.slot), outLamports: out, balanceBefore: pre, balanceAfter: post, flags, recipients: to })); } for (const r of to) learn.run(r.address, signature);}const page = await rpc.getSignaturesForAddress(wallet, { limit: 5, commitment: "confirmed" }).send();if (!page.length) console.log("no signatures in the address index");const reads = await Promise.allSettled(page.map((s) => load(s.signature)));for (let n = page.length - 1; n >= 0; n--) { const signature = page[n].signature; const read = reads[n]; if (read.status === "rejected") console.error(`read failed ${signature}: ${(read.reason as Error).message}`); else if (!read.value) console.log(`null ${signature} (the node no longer holds it)`); else score(signature, read.value);}
run: node main.ts [wallet address]
Pass a wallet address to watch your own, or pass nothing: the script then takes the fee payer of the newest landed transaction on a busy swap program, which PROGRAM overrides. CARBIUM_RPC_URL overrides the default https://services.carbium.sh, and the key travels in the x-api-key header. The output is one line per transaction. ALERT means a flag fired, known means every recipient was in the set and the amount was moderate, quiet means the wallet did not sign or lost nothing, and skip means the transaction failed or did not list the wallet.
Feeding the alert to a model
An alert line suits a person. A model that explains or triages the alert needs the fields without prose, so each alert also prints one JSON line with the wallet, signature, slot, outflow, balance before and after, the flags, and the recipients with their gain and a first-seen boolean. Hand that line to the model as a tool result and tell it to cite only fields that appear in it.
If you run the signer yourself, Agent wallet watcher shows the stronger check: a table of signatures your own signer recorded. That table separates your transfers from everyone else's, which a history-only score cannot do.
What a run costs
With an address, a run makes one getSignaturesForAddress call and five getTransaction calls. Each costs 50 cells, so the run costs 300. With no argument it adds one more of each and costs 400. A rate class absorbs bursts up to 1,024 cells, so a single run fits whole. Longer baselines need paging, and then the calls should be spaced to your plan's req/s for those methods.
Where it ends
- It proves nothing about who held the key. A drain flag on a first-seen destination is a pattern, and the owner may have moved the funds on purpose.
- Use of a seed phrase leaves no mark. Whoever holds it signs from the same address with the same scheme, so nothing in the transaction differs. Only destination and size can.
- History stops at 30 days. A destination older than that looks first-seen, and a null transaction leaves a hole in the baseline.
- A lamport gain names the account that received it. When that account is owned by a program, as a pool vault or a token account is, it is not the wallet behind it. An SPL send moves token balances, and the receiving token account is one of possibly several the same wallet holds for that mint, so this script misses SPL sends. Mapping them back to wallets needs the owner fields in postTokenBalances.
- A swap pays a pool vault or a temporary token account, and every new pool is first-seen. The no-argument demo wallet is a swap fee payer, so it alerts on routine swaps: its SOL leg splits across a few such accounts.
- The alert arrives after the transfer. It cannot stop one.
- The script learns every destination it scores, alerted or not, so a second transfer to a thief's address prints known. Review each alert before the next run, or delete the address from known.db.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every destination prints as first-seen. | known.db is new or the run started in another directory, since the path is relative. Fill the file from a longer history walk first, then start alerting. |
| getTransaction answers -32015. | The call left out maxSupportedTransactionVersion or set it to 0, and the transaction is v1. Pass 1, as the script does. |
| Several lines print null. | The address index lists signatures below the validator's ledger floor, so the node no longer holds those transactions. Treat each as a gap in the baseline and score the rest. |
| A normal exchange deposit raises an alert. | It is first-seen, so the alert is correct. Confirm it with the owner, then insert the address into known.db so it stops alerting. |
| Token transfers never alert. | The script reads lamport balances only. Map postTokenBalances owners to wallets and score those transfers the same way. |
| The no-argument run alerts on a routine swap or picks a wallet with no outflow. | The newest fee payer on a swap program pays pool vaults and temporary token accounts, which are first-seen for each new pool, or it may only receive. Pass an address, or set PROGRAM to another busy program. |
Questions
Can I tell whether the owner or a thief with the seed phrase signed?
No. The signature proves the key signed, and a copied seed phrase gives the thief the same key. You can only score how far a transfer departs from the wallet's own history.
Does a first-seen destination mean the wallet was compromised?
No. New payees and fresh deposit addresses look the same. Combined with a large send or a full drain it deserves a human look, and the script reports it as a flag.
Why only five transactions?
Five keeps a run at 300 cells, inside the 1,024-cell burst. A longer baseline means paging and spacing the calls.
Does it catch a transfer inside a program call?
It sees lamports leave the wallet whatever instruction moved them, because it compares balances before and after. It cannot say which instruction did it.
Can a model decide whether to freeze or alert someone?
It can summarize the evidence line and suggest a check. The decision stays with a person, since the line proves no intent.