library / AI and blockchain / SI0039
Flagged-address flow alerts
A watch list of flagged addresses in, a stream of plain lines out: lamport and token changes per address, the accounts on the other side of each transfer, and new activity as it confirms. Read-only, on one RPC key and one socket.
An address in a warning
A warning that names an address and says funds were stolen is a claim somebody else made. On chain you can read every balance change that touched the address and the other accounts in each of those transactions. That is enough for a useful alert: when an address on your list moves funds, you hear about it with the counterparties attached.
The job suits a screening service or an agent with a tool for it. You keep a list of addresses taken from warnings, from your own incident records or from a feed you trust. For each one the watcher prints what moved, in which direction and who sat on the other side. A person or a fixed rule then decides whether a counterparty joins the list. The watcher makes no judgement about guilt.
It holds only the Carbium key and public addresses. It signs nothing and sends nothing.
The flow file
One file. Node 24 runs the TypeScript directly and @solana/kit 8.6.0 makes the RPC calls. Set CARBIUM_KEY and pass the flagged addresses as arguments. With none, it watches the one address written into the file, so replace that with your own list. CARBIUM_RPC_URL and CARBIUM_WS_URL override the two endpoints, which default to https://services.carbium.sh and wss://services.carbium.sh.
// SI0039 · Flagged-address flow alerts// https://carbium.sh/library/si/flagged-address-flow-alerts// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Flagged-address flow alerts, read only. Run: CARBIUM_KEY=... node main.ts [address ...]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, 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 flagged = new Set(process.argv.length > 2 ? process.argv.slice(2) : ["3xPeeYKnsELXhhN7PDwJGahivYXii91Zf1BLk4DrrsV6"]);flagged.forEach((a) => address(a)); // a mistyped address stops the run hereconst rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey }, }),);const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");wsUrl.searchParams.set("api-key", apiKey);type Tok = { mint: string; owner?: string; uiTokenAmount: { amount: string } };type Meta = { err: unknown; preBalances: bigint[]; postBalances: bigint[]; preTokenBalances?: Tok[]; postTokenBalances?: Tok[] };type Tx = { meta: Meta | null; transaction: { message: { accountKeys: { pubkey: string }[] } } };const short = (a: string) => a.slice(0, 6);const signed = (d: bigint) => (d > 0n ? "+" : "") + d;const seen = new Set<string>();async function explain(sig: string, live = false): Promise<void> { if (seen.has(sig)) return; seen.add(sig); const config = { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 } as const; const get = async () => (await rpc.getTransaction(signature(sig), config).send()) as unknown as Tx | null; let tx = await get(); if (!tx?.meta && live) tx = await new Promise((r) => setTimeout(r, 1000)).then(get); // a live alert can beat the node if (!tx?.meta) { seen.delete(sig); console.log(`${sig} listed, body not served yet or older than the ledger`); return; } const { meta } = tx; const moves = tx.transaction.message.accountKeys .map((k, i) => ({ who: k.pubkey, delta: BigInt(meta.postBalances[i]) - BigInt(meta.preBalances[i]) })) .filter((m) => m.delta !== 0n); const tokens = new Map<string, bigint>(); for (const [list, sign] of [[meta.preTokenBalances ?? [], -1n], [meta.postTokenBalances ?? [], 1n]] as const) for (const t of list) if (t.owner) tokens.set(`${t.owner} ${t.mint}`, (tokens.get(`${t.owner} ${t.mint}`) ?? 0n) + sign * BigInt(t.uiTokenAmount.amount)); const hits = [ ...moves.filter((m) => flagged.has(m.who)).map((m) => `${short(m.who)} ${signed(m.delta)} lamports`), ...[...tokens] .filter(([k, d]) => d !== 0n && flagged.has(k.split(" ")[0])) .map(([k, d]) => `${short(k)} ${signed(d)} of mint ${short(k.split(" ")[1])}`), ]; const others = [ ...moves.filter((m) => !flagged.has(m.who)).slice(0, 4).map((m) => `${m.who} ${signed(m.delta)}`), ...[...tokens].filter(([k, d]) => d !== 0n && !flagged.has(k.split(" ")[0])).slice(0, 4).map(([k, d]) => `${k.split(" ")[0]} ${signed(d)} of mint ${short(k.split(" ")[1])}`), ]; const head = `${sig}${meta.err ? " (failed)" : ""}`; if (hits.length === 0) console.log(`${head}\n mentions a flagged address, no balance change on it`); else console.log(`${head}\n flagged: ${hits.join("; ")}\n others: ${others.join("; ") || "none"}`);}async function scan(addr: string): Promise<void> { try { const recent = await rpc.getSignaturesForAddress(address(addr), { limit: 5, commitment: "confirmed" }).send(); if (recent.length === 0) console.log(`${addr} no signatures in the 30-day index`); const reads = await Promise.allSettled([...recent].reverse().map((e) => explain(e.signature))); for (const r of reads) if (r.status === "rejected") console.error("read failed:", (r.reason as Error).message); } catch (e) { console.error("scan failed:", (e as Error).message); }}await Promise.all([...flagged].map(scan));const ws = new WebSocket(wsUrl);ws.addEventListener("open", () => [...flagged].forEach((a, i) => { const params = [{ mentions: [a] }, { commitment: "confirmed" }]; ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 1, method: "logsSubscribe", params })); }),);ws.addEventListener("message", (event) => { const msg = JSON.parse(String(event.data)); if (msg.error) return void console.error("subscription refused:", msg.error.message); const value = msg.params?.result?.value; if (value) explain(value.signature, true).catch((e: Error) => console.error("read failed:", e.message));});ws.addEventListener("close", () => { console.error("socket closed, exiting so a supervisor restarts the watcher"); process.exit(1);});
run: node main.ts [flagged address ...]
For each address the file reads the five newest signatures with getSignaturesForAddress and explains each one through getTransaction. The explanation compares every account's lamports before and after, then sums the token balances by owner and mint. The others line lists the other accounts whose lamports changed and the other owners whose token balance changed, so the wallet that received a token outflow shows up there. After the scan the file opens one socket and sends one logsSubscribe per address, because a mentions filter takes a single address. A confirmed transaction that mentions an address goes through the same explanation, and seen drops any signature that arrives twice. A live alert can reach the socket before the node serves the transaction body, so on a null answer the socket path pauses one second and asks once more before it gives up.
The token step reads the owner from the transaction's balance entries. When tokens move into a token account that already exists, the instructions name only the two token accounts and the authority that signed for the sender. The wallet that ends up holding the tokens appears nowhere in them, so the file takes the owner field from the token balances before and after.
Reading the lines
| Line | Meaning | What to do |
|---|---|---|
| flagged: 3xPeeY +1500000 lamports | The net change in a flagged account's lamports, after any fee the account paid. 1 SOL is 1,000,000,000 lamports. | Look at others for the sender. |
| flagged: 3xPeeY -2039280 lamports | A flagged account sent funds or paid a fee. | Treat the receiving accounts in others as candidates once the amount clears your threshold. |
| flagged: 3xPeeY +500 of mint EPjFWd | A token amount in raw units for that owner and mint. Decimals are not applied. | Read the mint's decimals before you compare amounts. |
| others: <address> +1500000 | Up to four other accounts whose lamports changed in the same transaction, in account order, flagged accounts left out, then up to four other owners whose token balance changed, as <owner> +500 of mint EPjFWd. | Add an address to the list only after you decide it belongs there. |
| mentions a flagged address, no balance change on it | The transaction lists the flagged address, often as a failed or rejected transfer or a token account move keyed to another owner, but neither its lamports nor any token balance it owns changed. | Nothing in the balances. Open the signature if you want to know why it listed the address. |
| (failed) after a signature | The transaction landed with an error. A failed transaction can still pay its fee. | Check whether the error was a refused transfer. |
| listed, body not served yet or older than the ledger | getTransaction answered null for a signature the index listed. | Nothing. A restart scans it again only while it is among the address's five newest. |
Failed transactions arrive too. A failed transaction prints a lamport line only when the flagged address paid the fee. Otherwise it prints mentions a flagged address, no balance change on it.
Cost and rate
getSignaturesForAddress costs 50 cells and getTransaction costs 50 cells. One address with the file's limit: 5, which you edit in scan, is six calls and 300 cells at start-up. After that each live notification is one getTransaction, 50 cells, or two calls when a null answer triggers the retry. The rate for getTransaction is 0.24 req/s on Free, 1.2 on Dev, 5 on Business and 25 on Pro, so on Free an address with a transaction more often than about every 4 s starts printing read failed:.
A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger: 20 getTransaction calls on Free, Dev and Business, 25 on Pro. The scans run in parallel and every flagged address draws on the same burst, so parallel scans past it get 429 with a retry-after hint.
Each logsSubscribe with a mentions filter opens at 25 credits, then costs 20 credits per MiB sent. A refused subscription costs nothing. Free carries 5 sockets and the file uses one, with one subscription per flagged address. Subscription counts are capped per account by plan, so a long list may need a higher tier. Limits are per account and an account's keys share one budget, which means other services on the same account draw on what the watcher needs.
From lines to alerts
The output is plain text, so a few lines of parsing turn it into whatever you alert on. A fixed rule works well here: raise an alert when a flagged address sends more than a threshold, and attach the others line.
If an agent reads the lines, let it summarise and let it propose, and keep the write to the list in code you control. A sender into a flagged address signed that transfer itself, so the transfer says little about the sender. The flagged wallet, on the other hand, can send dust to any address it likes and make an innocent one look like an outflow recipient. Treat outflow recipients as candidates only above an amount threshold, and have a person check each one before it goes on a list that triggers alerts. Agent wallet watcher shows the same read-only pattern for an agent's own wallet, and Wallet activity tracker tracks wallet activity without a flag list.
Where it ends
- The watcher reports after the fact, once a transaction confirms. It cannot stop a transfer.
- mentions and getSignaturesForAddress both match transactions that list the wallet. A token transfer into one of its existing token accounts may never list the wallet, so put the token account on the list next to the wallet. The wallet stays on the list so the owner match still works.
- Lamport changes include fees and rent. A swap through wrapped SOL shows up as a token amount for the wrapped mint.
- getSignaturesForAddress pages come from Carbium's own address index, which keeps up to 30 days. Older history is not served, and an empty page past that is the index's age limit, so the address may have older transactions.
- The file labels nothing. An exchange deposit address, a program-owned account and a fresh wallet all look like plain addresses in others.
- It follows one hop. Counterparties are printed and never watched until you add them.
- There is no reconnect. The file exits with status 1 when the socket closes, and a supervisor restarts it.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The opening scan prints no signatures in the 30-day index for an address you know was active. | The address index keeps up to 30 days, and an empty page past that is its age limit. Older activity is not served. Also check the address against its source for a typo. |
| A signature is listed but the line says body not served yet or older than the ledger. | getTransaction answered null. For an old signature the index reaches below the ledger floor. For a fresh one the node's view may not include it yet, so a live alert waits one second and asks once more before it prints this line. After that the file forgets the signature, and a restart scans it again only while it is among the address's five newest. |
| A read fails with -32015. | maxSupportedTransactionVersion is absent or 0 and the transaction is v1. Set it to 1 in the config, and keep as const on a config held in a variable. |
| read failed: lines print, during the opening scan or later on live alerts, and some carry 429. | Each address costs six calls and 300 cells at start-up, and each live notification costs one getTransaction of 50 cells, two with a null retry, against 0.24 req/s on Free. Scan fewer addresses at once, lower limit in scan, watch fewer busy addresses or move to a higher tier, and wait the retry-after hint before the restart. |
| A subscription is refused and the line prints subscription refused. | Subscription counts are capped per account by plan. A refused one costs nothing. Drop addresses from the list or move to a higher tier. The other subscriptions keep running. |
| The socket closes and nothing prints for hours. | The file exits with status 1 on close. Run it under a supervisor with a pause between restarts. The opening scan then reports up to five signatures per address from the gap. |
Questions
Does an address in a warning mean the funds were stolen?
The chain shows movement and says nothing about intent. Treat the list as input you vetted, and read the output as evidence for a person or a fixed rule.
Should I add every counterparty to the list?
No. A sender into a flagged address signed that transfer on its own, and the flagged wallet can dust any innocent address to make it look like a recipient. Only outflow recipients above an amount threshold are candidates, and a person confirms each one.
How far back does the opening scan reach?
Five signatures per address, the file's limit: 5, which you edit in scan. The address index keeps up to 30 days, so older history is not served.
Can an agent run this as a read-only tool?
Yes. Pass the lines back as a tool result and keep the write to the flag list outside the model. Agent wallet watcher shows a watcher shaped the same way.
Why does the file read token owners from the balance entries?
The instructions leave out the wallet that receives the tokens when the destination token account already exists. The balance entries carry the owner, which is what an address list matches.