library / Blockchain ideas / BI0018
Rent reclaim scanner
A wallet address in, a list of empty token accounts out, with the rent each one holds and the total a close would return. Read-only, one file on @solana/kit, and it finds a live wallet itself when you pass none.
Who uses it
Anyone who has received a token airdrop or tried a few new tokens ends up with token accounts that hold nothing. Each one still locks about 0.0015 to 0.002 SOL of rent until its owner closes it. The scanner lists those accounts for one wallet and adds up what closing them would return.
A wallet app can show the figure on a settings screen with a button beside it. A treasury team can run it across its own addresses before a tidy-up. A hackathon team can build the close step on top, because the scan already produces the account list that a close instruction needs.
What it reports
A wallet can own several token accounts for one mint, so the report lists each account on its own row. Each row comes from one getTokenAccountsByOwner response with jsonParsed encoding.
A reclaimable row prints its account, program and lamports. The other empty accounts only add to a count of skipped ones.
| Field | Where it comes from | What it tells you |
|---|---|---|
| Token account | pubkey of each row | The address a close instruction targets |
| Program | The programId filter of the call | The original Token program or Token-2022 |
| Balance | tokenAmount.amount in the parsed data | A string of base units; "0" means the account is a candidate |
| State | state in the parsed data | initialized or frozen; a frozen account cannot be closed |
| Close authority | closeAuthority, present only when set | An address besides the owner that must sign the close |
| Rent | lamports on the account | What goes to the destination when the account closes |
The report reads rent from each account's own lamports field, whatever the account's size. An account keeps the lamports that were required when it was created. Older classic token accounts of 165 bytes hold 2,039,280 lamports (0.00203928 SOL), newer ones hold less, and 170-byte Token-2022 accounts created today hold 1,513,840. getMinimumBalanceForRentExemption returns today's minimum for a given size, so an older row can sit above it.
The build
The scanner is one file that needs @solana/kit and what Node 24 ships. It signs and sends nothing.
- Take the wallet from the first argument. With none, read the newest signatures of a busy program with getSignaturesForAddress, fetch each transaction with getTransaction and keep the fee payers. Those are wallets that were active a moment ago. Discovery scans at most three of the wallets it finds.
- For each wallet, call getTokenAccountsByOwner twice, once with the Token program id and once with the Token-2022 id, so both kinds of account appear.
- Mark an account as reclaimable when its amount is "0", its state is initialized and no close authority is set.
- Print each reclaimable account with its lamports, then the count and the total in SOL, plus how many empty accounts the owner cannot close alone.
BUSY_PROGRAM defaults to Jupiter v6, which has transactions every second. Point it at any program your users touch, or skip discovery by passing the address you care about.
// BI0018 · Rent reclaim scanner// https://carbium.sh/library/blockchainideas/rent-reclaim-scanner// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (!apiKey) { 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": apiKey }, }),);const TOKEN_PROGRAMS: [string, string][] = [ ["Token", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"], ["Token-2022", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"],];// A busy program (Jupiter v6) whose newest fee payers are wallets that were active a moment ago.const BUSY_PROGRAM = process.env.BUSY_PROGRAM ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";type Row = { pubkey: string; account: { lamports: bigint; data: { parsed: { info: { state: string; closeAuthority?: string; tokenAmount: { amount: string } } } } };};const reason = (e: unknown): string => (e instanceof Error ? e.message : String(e));async function recentPayers(): Promise<string[]> { const payers = new Set<string>(); const page = await rpc.getSignaturesForAddress(address(BUSY_PROGRAM), { limit: 5, commitment: "confirmed" }).send(); for (const { signature } of page) { try { const tx = await rpc .getTransaction(signature, { commitment: "confirmed", encoding: "json", maxSupportedTransactionVersion: 1 }) .send(); if (tx) payers.add(String(tx.transaction.message.accountKeys[0])); // null: older than the ledger floor } catch (e) { console.error("getTransaction failed:", reason(e)); } } return [...payers];}async function report(wallet: string): Promise<void> { const tally = { count: 0, lamports: BigInt(0), blocked: 0 }; console.log(`wallet ${wallet}`); for (const [label, programId] of TOKEN_PROGRAMS) { try { const res = await rpc .getTokenAccountsByOwner(address(wallet), { programId: address(programId) }, { commitment: "confirmed", encoding: "jsonParsed" }) .send(); for (const row of res.value as unknown as Row[]) { const info = row.account.data.parsed.info; if (info.tokenAmount.amount !== "0") continue; if (info.state === "initialized" && !info.closeAuthority) { tally.count += 1; tally.lamports += row.account.lamports; console.log(` ${label} ${row.pubkey} ${row.account.lamports} lamports`); } else { tally.blocked += 1; } } } catch (e) { console.error(` ${label} read failed: ${reason(e)}`); } } const sol = Number(tally.lamports) / 1e9; console.log(` ${tally.count} empty accounts hold ${sol} SOL; ${tally.blocked} more cannot be closed by the owner alone`);}try { const wallets = process.argv[2] ? [process.argv[2]] : await recentPayers(); if (wallets.length === 0) console.error("no wallet found; pass one as the first argument"); for (const wallet of wallets.slice(0, 3)) await report(wallet);} catch (e) { console.error("scan failed:", reason(e)); process.exit(1);}
run: CARBIUM_KEY=<YOUR_KEY> node main.ts [wallet-address]
getTransaction passes maxSupportedTransactionVersion: 1 because mainnet carries v1 transactions, and a call with the value absent or 0 answers -32015 for one (the error and its fix).
A signature page from getSignaturesForAddress can reach below the validator's ledger floor, so an older signature may list and then return null from getTransaction. The code skips a null. Each read sits in its own try, so one failing read prints its message and the others still finish.
What it costs
A scan of one wallet is two getTokenAccountsByOwner calls. Discovery adds one getSignaturesForAddress call and five getTransaction calls, each of the six at 50 cells, 300 cells in all. A rate class absorbs bursts up to 1,024 cells, so the six discovery calls fit in one burst on every plan. Discovery then scans at most three of the wallets it found, which adds up to six getTokenAccountsByOwner calls to the six discovery calls.
| Plan | Credits | getSignaturesForAddress | getTransaction |
|---|---|---|---|
| Free ($0) | 500K once, at sign-up | 0.24 req/s | 0.24 req/s |
| Dev ($20) | 10M per month | 1.2 req/s | 1.2 req/s |
| Business ($250) | 50M per month | 100 req/s | 5 req/s |
| Pro ($500) | 200M per month | 500 req/s | 25 req/s |
A wallet you pass in skips discovery and needs only the two token reads. Scanning a list of wallets is a loop with a pause between wallets sized to the per-method req/s of your plan.
What to add next
- A close step: for each listed account, build a CloseAccount instruction naming the account, a destination for the lamports and the owner as signer, group several into one transaction and let the wallet sign.
- A live trigger: open a logsSubscribe with the wallet as the mention (25 credits to open, then 20 credits per MiB sent) and rescan after each transaction that touches it, so the figure follows the wallet.
- Names beside the addresses: join the mint to a metadata read, for instance the Token-2022 metadata lookup, so a row says which token it was.
- A report per wallet list: write each total to a small SQLite table with node:sqlite and show the change from the last run.
Where it ends
- The scanner only reads. Closing an account needs the owner's signature, or the close authority's, and that happens in the user's own wallet.
- Only zero-balance accounts are listed. An account that still holds tokens must be emptied by a transfer or a burn first, and a burn destroys those tokens. The report leaves that decision to the person.
- Frozen accounts and accounts with a close authority are counted as skipped. Token-2022 extensions can block a close for other reasons, such as transfer fees still withheld in the account, and the report does not check them.
- The lamports go to whatever destination the close instruction names, so the owner picks where the rent lands.
- A closed account address can come back: the next transfer of that mint to the wallet creates a token account again, and whoever creates it, usually the sender, pays the rent again.
- Other accounts hold rent too, such as buffers and program-owned data. This scanner reads token accounts only.
- With no argument the wallets come from the newest transactions of one program, so a run may land on a wallet with nothing to reclaim. The output then says 0 accounts, and passing your own address gives the real answer.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Discovery prints getTransaction failures or finds no wallet. | A printed failure is a read error, so read the message, wait a little and run again, or pass a wallet address. A signature that lists but returns null prints nothing and adds no wallet, because signature pages reach below the validator's ledger floor. The code asks for the newest five signatures, and getTransaction returns those. |
| getTransaction answers -32015. | The call left out maxSupportedTransactionVersion, or set it to 0, and the transaction is v1. Pass 1, as the code does. |
| The report shows no empty accounts for a wallet you know has some. | The wallet's empties may sit under the other token program. The code makes both calls, so check that neither printed a read failure. Also check that the account is not frozen or under a close authority, which counts it as skipped. |
| A close fails on an account the scanner listed. | A close authority may have been set after the scan, or a Token-2022 extension holds a withheld amount. Rescan, then read the instruction error from a simulation before the wallet signs. |
| The total differs from the figure a wallet app shows. | Apps may count only associated token accounts, or round the rent. Compare the two lists by account address, then compare each row's lamports. |
| The script exits and asks for a key. | Set CARBIUM_KEY in the environment before the run. An unknown key gets a 401 at the door, so paste the whole key. |
Questions
Does closing an empty token account lose any tokens?
No. A token account that holds tokens other than wrapped SOL can only close at a zero balance, and the scanner lists only zero-balance accounts. The only thing that moves is the rent, which goes to the destination in the instruction.
How much rent does one empty account return?
The figure depends on the account's size and on when it was created, and runs about 0.0015 to 0.002 SOL. The scanner reads each account's own lamports field and prints that value.
Does discovery need a paid plan?
No. Its six calls total 300 cells, which fits in one burst on every plan. A long list of wallets goes faster on a plan with a higher rate.
Can the scanner close the accounts for me?
Not as written, since it holds no key. It produces the account list. Add a close instruction per account and sign it in the owner's wallet.