library / AI and blockchain / SI0036
Wallet spam token filter
Reads a wallet's token accounts and mints through Carbium RPC, scores each token with a small logistic model and returns the likely spam with the reasons, so an agent can hide it and say why.
What spam looks like on chain
Anyone can create a token mint, create a token account for your wallet and send tokens into it, paying the rent themselves. The wallet owner signs nothing, so a wallet app lists the new token like any other holding. Most of it is harmless clutter. Some carries a name that promises a reward and a link that asks for a signature, and that is where real loss happens.
The chain gives a filter a few cheap, honest signals. A mint records who can still create more supply, who can freeze holders and how much exists. A token account records how much sits in it. A wallet's holdings come from one call per token program, and the mints come from a second call. None of it needs a name, an image or a website.
That limit is deliberate. Names and links are text a stranger wrote, and a model that reads them can be steered by that stranger. Chain numbers give an injected instruction nowhere to sit, so an agent can read them without taking orders from the token's author.
Five signals and one score
The scanner turns each token into five yes or no signals and adds a weight for every signal that fires.
| Signal | Read from | Weight |
|---|---|---|
| Known mint (USDC, wrapped SOL, USDT) | a fixed set in the file | -4 |
| Mint authority still set | mintAuthority on the mint | +1.2 |
| Freeze authority still set | freezeAuthority on the mint | +1.0 |
| Dust balance, one whole token or less | token account balances, summed per mint | +0.8 |
| Supply above a trillion whole tokens | supply and decimals on the mint | +0.7 |
| Bias | none | -1 |
The score z is the bias plus the weight of each signal that fires, and the spam probability is 1 / (1 + e^-z). A token flags at 0.5 or above. An unknown mint that keeps both authorities and sits in the wallet as one token gives z = 2.0 and a probability of 0.88. USDC with a large balance gives z = -2.8 and 0.06. A token with both authorities revoked and 500 units gives z = -1 and 0.27.
These weights are hand-set priors. They encode one judgment: a mint whose issuer can still print more and freeze your account, delivered as a single token, is more likely clutter than a holding you chose. They do not come from a fitted dataset.
Reading holdings and mints
getTokenAccountsByOwner takes one program id per call, so the file asks the Token program and Token-2022 separately and settles both. If one fails, it prints the failure and scores what the other returned. Each answer is requested with jsonParsed encoding at confirmed commitment, which hands back the mint and uiAmountString without any byte decoding.
A wallet can own more than one token account for the same mint, so balances are summed per mint before scoring. Without that, one token shows up twice and the dust signal fires on pieces of a larger holding.
The mints come from getMultipleAccounts, also in jsonParsed, which exposes mintAuthority, freezeAuthority, supply and decimals. A revoked authority comes back as null. The method charges 10 cells per pubkey, so a call with 100 mints costs 1000 cells, and below Pro the 1,024-cell burst caps a call at 100 pubkeys. A Pro key may send up to 300 in one call, and that is the only reason to raise the chunk size. The file stops at 300 mints with a balance, which is three calls.
With no argument, the file finds a wallet to scan. It lists the newest signatures that touched the USDC mint address, fetches each transaction and takes the fee payer, the first account key, until one payer holds token accounts. getSignaturesForAddress reads from an address index that keeps up to 30 days, which covers the newest six easily. That index reaches below the validator's ledger floor, so getTransaction can answer null for a signature it lists, and the loop skips a null. The transaction call passes maxSupportedTransactionVersion: 1, because mainnet carries v1 transactions and an absent or 0 value answers -32015 for one. Each of those two calls costs 50 cells.
The scanner
One file, with @solana/kit as its only dependency. Node 24 runs the TypeScript directly. Set CARBIUM_KEY first; the file exits with a message when it is unset, and CARBIUM_RPC_URL overrides the default https://services.carbium.sh.
// SI0036 · Wallet spam token filter// https://carbium.sh/library/si/wallet-spam-token-filter// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Wallet spam token filter. 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 rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const KNOWN = new Set([USDC, "So11111111111111111111111111111111111111112", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"]);// Hand-set priors; fit them on tokens you have labelled.const W: Record<string, number> = { bias: -1, known: -4, mintAuthority: 1.2, freezeAuthority: 1, dust: 0.8, hugeSupply: 0.7 };const MAX_MINTS = 300;type Row = { mint: string; balance: number };async function holdings(owner: string): Promise<Row[]> { const settled = await Promise.allSettled( PROGRAMS.map((p) => rpc.getTokenAccountsByOwner(address(owner), { programId: address(p) }, { encoding: "jsonParsed", commitment: "confirmed" }).send(), ), ); const totals = new Map<string, number>(); for (const r of settled) { if (r.status === "rejected") { console.log("token accounts failed:", String(r.reason)); continue; } for (const a of r.value.value as any[]) { const info = a.account.data.parsed.info; totals.set(info.mint, (totals.get(info.mint) ?? 0) + Number(info.tokenAmount.uiAmountString)); } } return [...totals].map(([mint, balance]) => ({ mint, balance }));}async function mintInfo(mints: string[]): Promise<Map<string, any>> { const out = new Map<string, any>(); for (let i = 0; i < mints.length; i += 100) { const chunk = mints.slice(i, i + 100); try { const res = await rpc.getMultipleAccounts(chunk.map((m) => address(m)), { encoding: "jsonParsed", commitment: "confirmed" }).send(); (res.value as any[]).forEach((acc, j) => out.set(chunk[j] as string, acc?.data?.parsed?.info)); } catch (e) { console.log("mint read failed:", String(e)); } } return out;}function score(mint: string, balance: number, info: any) { const f: Record<string, number> = { known: KNOWN.has(mint) ? 1 : 0, mintAuthority: info?.mintAuthority ? 1 : 0, freezeAuthority: info?.freezeAuthority ? 1 : 0, dust: balance <= 1 ? 1 : 0, hugeSupply: info && Number(info.supply) / 10 ** info.decimals > 1e12 ? 1 : 0, }; const z = Object.entries(f).reduce((s, [k, v]) => s + (W[k] ?? 0) * v, W.bias ?? 0); return { p: 1 / (1 + Math.exp(-z)), flags: Object.keys(f).filter((k) => f[k]) };}async function findWallet(): Promise<{ owner: string; rows: Row[] } | undefined> { const sigs = await rpc.getSignaturesForAddress(address(USDC), { limit: 6, commitment: "confirmed" }).send(); for (const s of sigs) { try { const tx: any = await rpc.getTransaction(s.signature, { maxSupportedTransactionVersion: 1, encoding: "json", commitment: "confirmed" }).send(); const m = tx?.transaction?.message; const payer = (m?.accountKeys ?? m?.staticAccountKeys)?.[0]; if (typeof payer !== "string") continue; const rows = await holdings(payer); if (rows.length > 0) return { owner: payer, rows }; } catch (e) { console.log("candidate failed:", String(e)); } }}const arg = process.argv[2];const found = arg ? { owner: arg, rows: await holdings(arg) } : await findWallet();if (!found) { console.error("No wallet with token accounts found; pass one as the first argument."); process.exit(1);}const held = found.rows.filter((r) => r.balance > 0);const rows = held.slice(0, MAX_MINTS);const mints = await mintInfo(rows.map((r) => r.mint));const scored = rows.map((r) => ({ ...r, ...score(r.mint, r.balance, mints.get(r.mint)) })).sort((a, b) => b.p - a.p);console.log(`wallet ${found.owner}: ${found.rows.length} mints, ${held.length} with a balance, ${rows.length} scanned`);for (const s of scored.slice(0, 15)) { console.log(`${s.mint.slice(0, 8)} p=${s.p.toFixed(2)} ${s.p >= 0.5 ? "SPAM" : "ok "} balance ${s.balance} ${s.flags.join(",")}`);}console.log(`flagged ${scored.filter((s) => s.p >= 0.5).length} of ${scored.length}`);
run: node main.ts
Run it with a wallet address as the first argument, or with none. The output starts with one line naming the wallet and the count of its mints, then lists up to 15 tokens sorted by score, each with its probability, a SPAM or ok label, its balance and the signals that fired. The last line gives the number flagged. A mint whose account cannot be read scores on the signals that remain, and a line names each call that failed.
Fitting the weights and using the score
To replace the priors, label a few hundred tokens from wallets you have reviewed as spam or kept. Compute the same five signals for each and fit a logistic regression with any tool you like. The fitted coefficients replace the numbers in W, and score stays as it is. Check the result against tokens you hold on purpose: a false positive on a real holding costs more than a missed piece of clutter.
- Expose score as a read-only tool. The model passes a wallet, gets the list with probabilities and fired signals, and writes the explanation from those signals.
- Hide flagged tokens in your interface. Leave burning tokens or closing accounts to the owner; nothing here signs or sends.
- Cache mint authorities by address and re-read supply on every scan. Authorities change only when the issuer revokes or reassigns them, but a mint that still has its mint authority can grow its supply and flip the supply signal between scans.
Authority screening for one mint is the subject of Token authority screening, and LP token classification is LP token classifier.
Where it ends
- Names, symbols, images and links sit in metadata, and this file reads none of them. A token named like a reward notice scores on chain signals only. If you add a metadata read, treat that text as untrusted input and keep it away from the model's instructions. Token-2022 metadata lookup reads Token-2022 metadata.
- A spam token with both authorities revoked scores below the 0.5 line: with a dust balance alone it reaches 0.45, and a revoked-authority mint sent in amounts above one token scores 0.27.
- Real tokens keep their authorities too. Only three mints sit on the known list, so an unlisted stablecoin or governance token with both authorities and a small balance flags. Extend the set from your own list.
- An NFT is usually a mint with 0 decimals and a supply of 1, so its balance of one fires the dust signal. A Metaplex NFT also keeps its mint and freeze authority (held by its edition account), so it fires both authority signals plus dust and flags at 0.88. The file does not tell NFTs apart; filter them first when the wallet holds any.
- Holder concentration is not read. getTokenLargestAccounts is not served and answers -32601, so ranking holders needs another route.
- Token-2022 extensions such as transfer hooks and a permanent delegate are not parsed, so a token that can block transfers or claw back balances looks like any other.
- A scan is one read at confirmed commitment. A transfer that arrives a moment later shows up in the next scan, and a wallet with more than 300 mints with a balance is cut at 300.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getMultipleAccounts with more than 100 mints is refused on a key below Pro. | Send chunks of 100. The 1,024-cell burst caps a call at 100 pubkeys below Pro, and only a Pro key may send up to 300. |
| getTransaction answers -32015 while looking for a wallet to scan. | Pass maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and an absent or 0 value is refused for one. |
| getTransaction answers null for a signature that getSignaturesForAddress just listed. | Skip the null and try the next signature. The address index reaches below the validator's ledger floor, so an older signature can be listed and still unreadable. Scan from the newest signatures. |
| One token program query fails and the wallet seems to hold half its tokens. | Settle each program call on its own and print the failure. Run the scan again before hiding or reporting anything. |
| The same token appears twice with two small balances and flags as dust. | Sum the balances per mint before scoring. A wallet can own several token accounts for one mint. |
| A real token with both authorities set flags as spam. | Add its mint to the known set or lower the authority weights after fitting on your own labels, then check the held tokens again. |
Questions
Can the scanner read a token's name?
No. It reads mint and token account fields only, so a name or link never reaches your model. Add a metadata read if you need names, and treat that text as untrusted input.
Why a small logistic model for this?
The inputs are five yes or no signals, so a weighted sum is enough, it runs in microseconds and every flag explains the score. A language model can write the explanation from the fired signals.
How many calls does one scan make?
Two token account calls, one per token program, plus one getMultipleAccounts call per 100 mints at 10 cells per pubkey, so 1000 cells for 100 mints. A run with no argument also makes one getSignaturesForAddress call, up to six getTransaction calls at 50 cells each and a holdings read for each candidate payer. Scan wallets one at a time and cache mint authorities.
Where do better weights come from?
From your own labels. Mark a few hundred tokens as spam or kept, compute the same five signals and fit a logistic regression. The coefficients replace the numbers in W.
Can the file hide or burn a token for me?
No. It only reads. Hiding is your interface's job, and burning or closing an account is a signed transaction that belongs to the wallet owner.