services
Get a key

library / How to use Solana / HS0038

Closed account detection

A programSubscribe stream can miss an account at the moment it closes. The file tracks the accounts the stream shows, sweeps them with getMultipleAccounts, and prints each one that is gone or has left your program.

By Carbium · WebSocket · HS0038 · updated 2026-11-22

01

What a close looks like

Closing an account moves its lamports out and zeroes its data. In the usual pattern the account is also handed back to the System Program, and an account left with zero lamports is dropped by the runtime. Nothing on chain says closed. The account is absent from the next read.

programSubscribe filters by the owner program. The last update for a closed account carries its state after the close, with lamports at 0 and the System Program as owner, so it no longer belongs to the program you subscribed to. Whether a node delivers that update anyway is not something to build on, so the file counts a 0-lamport notification as an early catch and relies on the sweep.

!A program subscription lists accounts that exist. A close shows up as silence for one account, and a subscription cannot report silence by itself. The reliable signal is a read that comes back null.
02

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips TypeScript types on load. Two optional arguments set the program id and the number of seconds to run. The default program is the pump.fun bonding curve program, whose accounts change every few seconds. Pass your own program id to watch the accounts you care about.

main.ts
// HS0038 · Closed account detection// https://carbium.sh/library/howsolana/closed-account-detection// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { setTimeout as sleep } from "node:timers/promises";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 rpcUrl = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const wsUrl = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": key } }),);const program = process.argv[2] ?? "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";const seconds = Number(process.argv[3] ?? 20);const MAX_TRACKED = 50; // 50 pubkeys cost 500 cells a sweepconst tracked = new Set<string>();const gone = new Set<string>();let notifications = 0;function markClosed(pubkey: string, how: string) {  tracked.delete(pubkey);  if (!gone.has(pubkey)) console.log(`closed ${pubkey} (${how})`);  gone.add(pubkey);}// One read of the whole set: null means the account is gone.async function sweep() {  const keys = [...tracked];  if (keys.length === 0) return;  try {    const { value } = await rpc      .getMultipleAccounts(keys.map((k) => address(k)), { encoding: "base64", dataSlice: { offset: 0, length: 0 } })      .send();    value.forEach((account, i) => {      if (account === null) markClosed(keys[i], "sweep: account is gone");      else if (account.owner !== program) markClosed(keys[i], `sweep: owner is now ${account.owner}`);    });    console.log(`sweep: ${keys.length} checked, ${gone.size} closed so far`);  } catch (e) {    console.error(`sweep failed: ${e}`);  }}const ws = new WebSocket(`${wsUrl}?api-key=${key}`);ws.addEventListener("error", () => console.error("WebSocket error"));ws.addEventListener("open", () => {  ws.send(JSON.stringify({    jsonrpc: "2.0",    id: 1,    method: "programSubscribe",    params: [program, { commitment: "confirmed", encoding: "base64", dataSlice: { offset: 0, length: 0 } }],  }));});ws.addEventListener("message", (event) => {  const msg = JSON.parse(String(event.data));  if (msg.error) return console.error(`subscribe failed: ${JSON.stringify(msg.error)}`);  if (msg.id === 1) return console.log(`subscribed, id ${msg.result}`);  if (msg.method !== "programNotification") return;  const { pubkey, account } = msg.params.result.value;  notifications++;  if (account.lamports === 0) markClosed(pubkey, "notified with 0 lamports");  else if (!gone.has(pubkey) && tracked.size < MAX_TRACKED) tracked.add(pubkey);});const timer = setInterval(sweep, 10_000);await sleep(seconds * 1000);clearInterval(timer);ws.close();await sweep();console.log(`done: ${notifications} notifications, ${tracked.size} still tracked, ${gone.size} closed`);

run: node main.ts [program] [seconds]

The file opens programSubscribe at confirmed with dataSlice set to zero bytes, so each notification carries the pubkey, lamports and owner and no account data. Every pubkey it sees goes into a set of at most 50. A notification with 0 lamports is reported as closed at once.

Every 10 seconds, and once more at the end, getMultipleAccounts reads the whole set. A null answer means the account is gone. An owner other than your program means the account left it. Both are printed and dropped from the set. Each sweep sits in a try, so a failed call prints and the next sweep runs.

03

Reading the output

A run prints one subscribed line, a sweep line per sweep, a closed line for each close, and a final done line with the notification count, the accounts still tracked and the closes found. On a busy program, a 20-second window usually finds zero closes, because accounts rarely close in any given window. A run that shows notifications above zero and sweeps that returned without error has exercised the subscribe and sweep paths. The three close paths (null, new owner, 0 lamports) only run when an account actually closes.

The text in parentheses on a closed line says which path caught it. A line saying notified with 0 lamports means your node does send the final update, and the sweep acts as a safety net. Lines that only say sweep mean the sweep is doing all the work.

To watch a real close, point the file at a program whose accounts live for one order or one session, and pass a larger second argument so the run lasts through a few of them.

04

Ways to catch a close

MethodWhat it catchesWhat it costs on Carbium
programSubscribe plus a sweep (this file)Any account the stream showed, found at the next sweep that reads null or a new owner200 credits to open, 20 credits per MiB sent, and 10 cells per tracked pubkey per sweep
accountSubscribe on one accountThe account you named, with its last state25 credits to open, refunded at close when it never notified
getMultipleAccounts on a list you holdEach listed account that answers null10 cells per pubkey, 100 pubkeys a call below Pro
logsSubscribe by mention, then getTransactionThe transaction that did the close, with its logs25 credits to open, then 50 cells per transaction read

Pick by what you already hold. If your database lists the accounts, skip the subscription and read that list on a timer. If you know only the program, subscribe to find accounts and sweep what you found. If you need to know who closed an account and in which transaction, read that transaction with getTransaction and maxSupportedTransactionVersion: 1, which also covers v1 transactions.

accountSubscribe sends state on change for streamed accounts and sends nothing for a plain SOL wallet, so it fits program-owned accounts you can name.

05

On Carbium

The socket is wss://services.carbium.sh. A plan caps connections and subscriptions per account, and Free carries 5 sockets. A subscription costs credits to open by filter weight, and a program subscription sits in the heaviest class at 200, then 20 credits per MiB sent. A refused subscription costs nothing. The zero-byte dataSlice keeps the MiB count low, and on a very busy program you can add dataSize or memcmp filters to the subscribe params. Limits are per account, and its keys share one budget.

getMultipleAccounts is an account read at 10 cells per pubkey: 100 pubkeys cost 1000 cells, 1001 over a 4 KiB body. The 1,024-cell burst caps a call at 100 pubkeys below Pro, and Pro takes up to 300. The file tracks 50, so one sweep costs 500 cells and fits the burst on every plan. Account reads refill at 0.5 req/s on Free, which is 5 cells a second, so a sweep every 10 seconds empties the burst after about two sweeps and then gets 429. On Free, use a much longer interval or fewer tracked pubkeys to keep it up.

For reading a commitment level on the sweep, see Solana commitment levels. For streaming chain data at larger volume, see Chain data streaming.

06

Where it ends

A sweep finds a close at its next run, and the gap can be as long as the interval. A shorter interval shrinks the gap and spends more cells.

The file tracks only accounts it saw during the run. An account that closes before any update reached the socket is never in the set. For a full picture, seed the set from your own store of the program's accounts and let the subscription add new ones.

A null answer says the account is gone and nothing about why. An address can be funded and created again later, and the file drops it after the first report, so a revived account needs a fresh start of the run.

The socket does not reconnect. Closes that land while it is down send nothing, so after any reconnect, sweep first and resubscribe second. Reads sit at confirmed, which @solana/kit fills in when a call omits commitment.

07

When it goes wrong

what goes wrongwhat to do
The run ends with 0 notifications.The program id may be wrong or quiet. Try a busier program, and check for a WebSocket error line. An unknown key gets 401 at the door, so attach the whole key.
A sweep prints failed with a 429.The cells did not refill in time. Wait for the retry-after hint, lower the tracked count or lengthen the interval, which Free needs most. The next sweep runs on its own.
An account reported closed shows up again later.The address was funded and created again. Start the file again, or remove it from the gone set when a later notification shows lamports above 0.
The socket drops mid-run and closes in the gap are never reported.Open a new socket, run a sweep over your saved list before anything else, then resubscribe to pick up new accounts.
Credits climb fast on a busy program.Add dataSize or memcmp filters to the subscribe params so only the accounts you care about arrive.
The file stops with Set CARBIUM_KEY to your Carbium API key.Export CARBIUM_KEY in the shell that runs node main.ts. The file reads it from the environment and never prints it.
08

Questions

Does programSubscribe send a notification when an account is closed?

Not reliably. The last update carries the account with 0 lamports and the System Program as owner, which no longer matches your program. Sweep the accounts you track with getMultipleAccounts instead of waiting for it.

Can accountSubscribe on one account show the close?

For an account you name, the update usually shows lamports at 0, so confirm with a getAccountInfo read that comes back null. It costs one subscription per account, so past a few dozen accounts it is simpler to read the list with getMultipleAccounts.

How do I find out which transaction closed an account?

List the account's signatures with getSignaturesForAddress, then call getTransaction with maxSupportedTransactionVersion 1 and compare pre and post balances. On Carbium the address index reaches back up to 30 days, and an older signature can answer null, so handle that.

Why does the file track 50 accounts?

A sweep costs 10 cells per pubkey, so 50 keeps it at 500 cells, inside the 1,024-cell burst on every plan. On Pro you can raise the cap toward 300.