services
Get a key

library / Use cases / UC0032

Token account cleanup for wallets

A wallet product that closes token accounts needs to know what blocks a close and what SOL comes back. You get the reads, a script that totals the rent before signing, and how a close lands.

By Carbium · Wallet products · UC0032 · updated 2026-11-22

01

Rent sits in empty accounts

Every token account is an account on chain, and an account must hold a minimum balance to stay alive, called rent exemption. A standard token account is 165 bytes, and the current figure for that size comes from getMinimumBalanceForRentExemption. An older account keeps the lamports it was funded with. The payer of the create put the rent in: the wallet itself when it swaps into a token, often the sender when a first transfer creates the account. A close sends that rent to the closer's chosen destination either way.

When the balance of a token falls to 0 the account stays, with its rent still inside. A wallet that has swapped and collected unsolicited tokens for a year can own hundreds of these. Closing an account deletes it and sends every lamport it holds to a destination the closer names. The job for a wallet product is to find the empty accounts and show the sum before anyone is asked to sign.

02

The read behind the total

getTokenAccountsByOwner with a programId filter returns each token account of a wallet with its own lamports and, in jsonParsed encoding, the mint, the state and the token amount. A wallet's accounts live under two token programs, the original Token program and Token-2022, so the script sends one read per program. The calls go to the Carbium RPC endpoint with the key in the x-api-key header.

Every call passes commitment: "confirmed". The numbers are a snapshot: a deposit that lands after the read makes a listed account non-empty, and its close then fails.

A job that scans many wallets can post a batch of up to 100 calls in one request. The kit client sends one call per request, so post the batch yourself to the same URL with the same header.

03

A script in one file

Run it with wallet addresses, or with none. With none it takes the first signer of the newest transactions of a busy swap program and keeps the first two distinct signers, which gives live wallets to read. That costs one getSignaturesForAddress and eight getTransaction calls at 50 cells each, 450 cells in all, inside the 1,024-cell burst. It sets maxSupportedTransactionVersion: 1, since mainnet carries v1 transactions and a call without it answers -32015 for one. A signature from the address index can also come back as null from getTransaction, so the script skips those.

For each wallet it prints the token account count, the closable count with the SOL they hold, the held-back count, the frozen count and the count holding a balance, then the first 10 closable accounts. Held back means an empty account whose close authority is a key other than the owner, or a Token-2022 account with withheld transfer fees. Those stay out of the sum, because the owner's close would fail. The script prints the rent of a plain 165-byte account first, for comparison. It reads CARBIUM_KEY and exits with a message when it is unset.

main.ts
// UC0032 · Token account cleanup for wallets// https://carbium.sh/library/usecase/token-account-cleanup-for-wallets// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: finds the empty token accounts of a wallet and totals the rent a close would return.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 commitment = "confirmed";// Token accounts live under one of two token programs.const PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];// A busy swap program: its newest transactions give live wallets when none is passed in.const BUSY_PROGRAM = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";const sol = (l: bigint) => `${l / 1_000_000_000n}.${(l % 1_000_000_000n).toString().padStart(9, "0")}`;type Ext = { extension: string; state?: { withheldAmount?: number | string } };type Info = { mint: string; state: string; tokenAmount: { amount: string }; closeAuthority?: string | null; extensions?: Ext[] };type Key = { pubkey: string; signer: boolean };async function recentSigners(): Promise<string[]> {  const sigs = await rpc.getSignaturesForAddress(address(BUSY_PROGRAM), { limit: 8, commitment }).send();  const txs = await Promise.allSettled(sigs.map((s) =>    rpc.getTransaction(s.signature, { commitment, encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()));  const found = new Set<string>();  for (const t of txs) {    if (t.status === "rejected") { console.error(`getTransaction failed: ${String(t.reason)}`); continue; }    const tx = t.value?.transaction as unknown as { message?: { accountKeys?: Key[] } } | undefined;    const first = tx?.message?.accountKeys?.find((k) => k.signer);    if (first) found.add(first.pubkey);  }  return [...found].slice(0, 2);}async function scan(owner: string): Promise<void> {  const reads = await Promise.allSettled(PROGRAMS.map(async (id) => {    const res = await rpc      .getTokenAccountsByOwner(address(owner), { programId: address(id) }, { commitment, encoding: "jsonParsed" })      .send();    return res.value.map((v) => ({      pubkey: String(v.pubkey),      lamports: BigInt(v.account.lamports),      info: (v.account.data as unknown as { parsed: { info: Info } }).parsed.info,    }));  }));  const accounts = reads.flatMap((r) => {    if (r.status === "fulfilled") return r.value;    console.error(`${owner}: one token program read failed: ${String(r.reason)}`);    return [];  });  // Held back: another key is the close authority, or a Token-2022 account has withheld fees. The owner's close fails.  const heldBack = (a: (typeof accounts)[number]) =>    (!!a.info.closeAuthority && a.info.closeAuthority !== owner) ||    (a.info.extensions ?? []).some((e) => e.extension === "transferFeeAmount" && BigInt(e.state?.withheldAmount ?? 0) > 0n);  // Closable: a zero token amount in any state except uninitialized, frozen included, and not held back. Its whole lamport balance comes back.  const empty = accounts.filter((a) => a.info.tokenAmount.amount === "0" && a.info.state !== "uninitialized");  const closable = empty.filter((a) => !heldBack(a));  const total = closable.reduce((sum, a) => sum + a.lamports, 0n);  const frozen = accounts.filter((a) => a.info.state === "frozen").length;  const funded = accounts.filter((a) => a.info.tokenAmount.amount !== "0").length;  console.log(`${owner}: ${accounts.length} token accounts, ${closable.length} closable for ${sol(total)} SOL, ${empty.length - closable.length} held back, ${frozen} frozen, ${funded} holding a balance`);  for (const a of closable.slice(0, 10)) console.log(`  ${a.pubkey}  mint ${a.info.mint}  ${a.lamports} lamports`);}const rent = await rpc.getMinimumBalanceForRentExemption(165n, { commitment }).send().catch(() => null);console.log(`Rent of a plain 165-byte token account: ${rent === null ? "unavailable" : rent} lamports`);const owners = process.argv.length > 2 ? process.argv.slice(2) : await recentSigners().catch((e) => {  console.error(`wallet discovery failed: ${String(e)}`);  return [];});if (owners.length === 0) { console.error("No wallet found. Pass one as an argument."); process.exit(1); }for (const owner of owners) await scan(owner).catch((e) => console.error(`${owner}: scan failed: ${String(e)}`));

run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [wallet ...]

Lamports are summed as BigInt and formatted as SOL by integer division, so a large wallet's total carries no float error. The script signs and sends nothing. Wallet token holdings lists the mints a wallet holds.

04

What a close needs

The token program accepts its CloseAccount instruction only when the account meets a few conditions. The instruction takes three accounts: the token account, the destination that receives the lamports, and the close authority or owner as signer. The scan reads the state, the amount, the close authority and the withheld fees, which settle most cases.

Account stateCloses nowBefore the close
Initialized, amount 0YesNothing. The close authority signs when one is set, and the owner signs otherwise. An owner cannot close an account whose close authority is another key.
Frozen by the mint's freeze authority, amount 0YesNothing. CloseAccount has no frozen-state check, so a freeze does not stop it.
Amount above 0NoBurn the balance or send it away first.
Frozen, amount above 0NoThe burn or transfer that would empty it is refused, so only the freeze authority's thaw frees it. Leave it out of the total.
Token-2022 with withheld transfer feesNoRun HarvestWithheldTokensToMint to move the withheld fees to the mint, then close.
Wrapped SOL with a balanceYesThe wrapped lamports go to the destination with the rent.

The script counts wrapped SOL under balances, so add it to the total when your product unwraps it. The signer of a close is the account's close authority when one is set and its owner otherwise. The destination is any account the signer names, so a wallet product builds the transaction with the destination set to the user's own wallet, and the wallet shows it before signing.

A balance above 0 takes two instructions in one transaction, a burn and then the close, both signed by the owner. Decide the dust rule as a product choice: list each funded account with its mint and amount, and have the user tick the ones to burn before the transaction is built.

05

From the list to a landed close

A legacy or v0 transaction is limited to 1,232 bytes, so a large cleanup splits into several transactions of close instructions. Your service builds each one unsigned with the user's wallet as fee payer, signer and destination, and the wallet signs. A send through the RPC endpoint costs 20 cells without preflight and 70 with it, and Transaction status check covers confirming that it landed.

After it lands, scan again. The closed accounts are gone and the total falls to what you left out on purpose. Cache each scan per wallet for a short time, so a wallet screen that many users open does not repeat the two reads on every view.

06

Where it ends

  • Reads only: the script signs nothing, and a close needs the close authority's or the owner's signature in a wallet.
  • Current state only: it does not say who paid a rent or when an account was opened. getSignaturesForAddress reaches back 30 days at most from Carbium's own address index, and an empty page past that is the index's age limit, so the creation of an older account is out of reach.
  • No reverse view: getTokenLargestAccounts and getProgramAccountsV2 are not served and answer -32601, which is final, so the scan starts from a wallet.
  • Token-2022 confidential transfers: the script does not read them, and an account with a confidential balance can still refuse a close. Read that extension's data before you promise a total to a user.
  • Gross amount: the transaction fee, 5,000 lamports per signature at the base rate, plus any priority fee, comes out of the same wallet.
07

When it goes wrong

what goes wrongwhat to do
The total shows 0 SOL for a wallet that has empty accounts.Read both token programs. Accounts of Token-2022 mints sit only under the second one.
A close transaction fails as a whole.One account in it received a deposit after the scan, has a close authority held by another key, or holds withheld Token-2022 fees, and one failed instruction fails the transaction. Scan again, drop that account and rebuild.
A Token-2022 account refuses to close although its amount is 0.Withheld transfer fees sit in the account. Run HarvestWithheldTokensToMint to move them to the mint, then close it.
The total differs from a count of accounts multiplied by one rent figure.Sum the lamports field of each account. A fresh 165-byte account holds the figure getMinimumBalanceForRentExemption returns now, while an older account keeps what it was funded with and a larger account holds more.
getTransaction answers -32015 for a recent signature.Pass maxSupportedTransactionVersion: 1 with an encoding, because mainnet carries v1 transactions. Treat a null answer as a skipped signature.
08

Questions

Does closing a token account destroy the tokens?

A wrapped SOL account closes with its lamports sent to the destination, and any other account needs a balance of 0, so the close itself destroys no tokens. An account with a balance needs a burn or a transfer first, and a burn does destroy those tokens.

Who receives the SOL?

The destination the signer names in the close instruction. A wallet product sets it to the user's own wallet, and it receives the rent plus any extra SOL the account held.

Can the account come back after a close?

Yes. Anyone who sends that token to the wallet can create the account again and pays its rent in that transfer. The rent you reclaimed is not owed back.

Can I get the rent figure without scanning a wallet?

getMinimumBalanceForRentExemption with 165 returns it for a plain token account, and the script prints it. A wallet's real total needs the scan, since accounts differ in size and in the SOL they hold.