---
id: I0074
title: "MySQL closed-account tombstones"
url: https://carbium.sh/library/integrate/mysql-closed-account-tombstones
collection: Integrations
category: Relational databases
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# MySQL closed-account tombstones

A Node script finds a closeAccount instruction on the Token program, confirms with a null getAccountInfo read that the account is gone, and prints the MySQL statement that tombstones the mirror row, or the one that clears it if the address comes back.

## Why the row survives

A mirror table fills from account reads and account updates, and each one carries a final state to store: an owner, a mint, an amount, a slot. A closed token account carries none. The runtime removes the account, so a read of its address returns null in `value`, and a sync job that writes only what it can decode has nothing to write.

The old row stays where it is. The last upsert for that address left its owner and amount in place, so every query on the table counts it as live. A wallet screen lists an empty token account that no longer exists, and a holder count includes an account closed last week.

Deleting the row fixes the count and throws away the fact that the account existed. A mirror that feeds reports or reconciliation wants that fact. A tombstone leaves the row in place and adds the slot and the transaction of the close. Because the write comes from an absence, something besides the account read has to tell you the close happened.

## The tombstone columns

One table holds live and closed accounts together.

| Column | Holds |
|---|---|
| `address` | `varchar(44)`, primary key, the token account |
| `owner` | The wallet that owned it |
| `mint` | The token's mint |
| `amount` | Base units at the last live read |
| `slot` | The slot of the last live read |
| `closed_slot` | `bigint`, NULL while the account lives |
| `closed_signature` | `varchar(88)`, NULL while the account lives |

`closed_slot` is the slot of the transaction that carried the close, and `closed_signature` lets anyone open that transaction later. Queries for live accounts add `WHERE closed_slot IS NULL`, and audit queries read every row. The `slot` column matters to one write, the tombstone `UPDATE`, which compares against it so that a read newer than the close is left alone.

## Finding the close

A close shows up in a transaction as a `closeAccount` instruction of the Token program. With `jsonParsed` encoding the instruction arrives decoded, and `parsed.info.account` names the account that was closed. A program that cleans up for a user, such as a swap that unwraps SOL, runs it as an inner instruction, so the script reads the top-level list and every inner list. A failed transaction closes no account, so it skips any signature whose `err` is set.

The instruction says a close ran in that transaction. A later transaction, even in the same slot, can create the address again, so the instruction alone does not say the account is gone now. A [`getAccountInfo`](https://carbium.sh/docs/rpc) read at confirmed settles it: null in `value` means nothing lives at the address at the slot the response reports in `context`. Instruction and null read together give a tombstone you can defend, a close at one slot and an absence at that slot or a later one.

`getSignaturesForAddress` costs 50 cells, `getTransaction` 50 and `getAccountInfo` 10. The script reads at most 20 transactions, 1,000 cells, which fits inside the 1,024 cells a rate class [absorbs as a burst](https://carbium.sh/docs/limits). `getTransaction` carries `maxSupportedTransactionVersion: 1`, because mainnet carries v1 transactions and a call without it answers -32015 for one. A signature the address index lists can still come back null from `getTransaction`, since its pages reach [below the validator's ledger floor](https://carbium.sh/docs/migrate). The script skips a null and goes on to the next signature.

## The script

Use Node 24, which strips the types on load, and `npm install @solana/kit@8.6.0`. The script needs `CARBIUM_KEY` and takes no arguments. It lists the newest 20 signatures that touched the Token program, reads them one at a time at confirmed until one holds a `closeAccount`, then reads the closed account at confirmed. It only reads. It has no MySQL client and runs no SQL: it prints the statement, and you pass the same text through your driver with placeholders in place of the literal values.

`main.ts` (run: `node main.ts`)

```ts
// I0074 · MySQL closed-account tombstones
// https://carbium.sh/library/integrate/mysql-closed-account-tombstones
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const TOKEN = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
type Ix = { programId?: string; parsed?: { type?: string; info?: { account?: string } } };
type Tx = { slot: bigint; transaction: { message: { instructions: Ix[] } }; meta: { innerInstructions?: { instructions: Ix[] }[] } | null };

// a closeAccount can sit at the top level or inside a program's inner instructions
const closedIn = (tx: Tx) =>
  [...tx.transaction.message.instructions, ...(tx.meta?.innerInstructions ?? []).flatMap((i) => i.instructions)]
    .find((ix) => ix.programId === TOKEN && ix.parsed?.type === "closeAccount")?.parsed?.info?.account;

let target = "";
let sig = "";
let closeSlot = BigInt(0);
try {
  const sigs = await rpc.getSignaturesForAddress(TOKEN, { limit: 20, commitment: "confirmed" }).send();
  for (const s of sigs) {
    if (s.err) continue; // a failed transaction closes nothing
    try {
      const tx = (await rpc
        .getTransaction(s.signature, { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 })
        .send()) as unknown as Tx | null;
      if (!tx) {
        console.log(`no body for ${s.signature}`);
        continue;
      }
      const account = closedIn(tx);
      if (account) {
        [target, sig, closeSlot] = [account, s.signature, tx.slot];
        break;
      }
    } catch (e) {
      console.log(`getTransaction failed ${s.signature}: ${msg(e)}`);
    }
  }
} catch (e) {
  console.log(`getSignaturesForAddress failed: ${msg(e)}`);
}
if (!target) {
  console.log("no closeAccount in the newest 20 Token program transactions; run again");
  process.exit(0);
}
console.log(`closeAccount on ${target} in ${sig} at slot ${closeSlot}`);

try {
  const info = await rpc.getAccountInfo(address(target), { commitment: "confirmed", encoding: "base64" }).send();
  console.log(`getAccountInfo at slot ${info.context.slot}: ${info.value === null ? "null" : "alive"}`);
  if (info.value === null) {
    console.log(`UPDATE token_account SET closed_slot = ${closeSlot}, closed_signature = '${sig}' WHERE address = '${target}' AND slot < ${closeSlot} AND (closed_slot IS NULL OR closed_slot < ${closeSlot});`);
  } else {
    console.log(`UPDATE token_account SET closed_slot = NULL, closed_signature = NULL WHERE address = '${target}' AND closed_slot < ${info.context.slot};`);
  }
} catch (e) {
  console.log(`getAccountInfo failed: ${msg(e)}`);
}
```

The first line names the closed account, the signature and the slot of the close. The second gives the slot of the null read. The `UPDATE` after them is the tombstone. When the read finds the account alive instead, the script prints the statement that clears a tombstone.

## Addresses that come back

A close does not retire the address. An associated token account is derived from the wallet, the token program and the mint, so when that wallet receives that token again the same address is created. A mirror that tombstoned it now holds a closed row for a live account.

Slots order the two events. Arrival time says nothing, because a sync job and a close reader run apart and either can be late.

- The tombstone `UPDATE` requires `slot < S` for a close at slot S, and an empty or older `closed_slot`. A row refreshed by a read after the close is left alone.
- The clear `UPDATE` requires `closed_slot < R`, where R is the slot of a read that found the account alive. A read older than the close cannot clear it.
- The ordinary upsert for live accounts clears the tombstone when its own slot is newer than `closed_slot`: `INSERT INTO token_account (address, owner, mint, amount, slot) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE closed_signature = IF(VALUES(slot) > closed_slot, NULL, closed_signature), closed_slot = IF(VALUES(slot) > closed_slot, NULL, closed_slot), owner = VALUES(owner), mint = VALUES(mint), amount = VALUES(amount), slot = VALUES(slot)`. Clear `closed_signature` before `closed_slot`: MySQL evaluates the assignments left to right, so a later assignment that reads `closed_slot` sees the NULL just written and keeps a signature on a row that no longer has a close slot.

## Where it ends

- `getSignaturesForAddress` reaches back 30 days at most. A close older than that never shows in the signature list, and its row stays live. A sweep over the mirror finds those: `getMultipleAccounts` takes up to 100 addresses a call below Pro, and each null is a closed or never-created account. The sweep has no signature, so `closed_signature` stays NULL and `closed_slot` holds the slot of the read, which is a later bound than the real close.
- The script finds one close from the newest 20 transactions on the Token program. It shows the technique on live data and does not walk every close. A production writer reads each transaction for the owners it mirrors as it lands, from a logs subscription, and applies the same two comparisons.
- It matches the classic Token program. An account closed by Token-2022 carries a different program id, so add that id to the check.
- A null read also answers for an address that never held an account, so tombstone only an address your table already holds. A held row may be tombstoned from a null read alone, with `closed_slot` at the read slot and `closed_signature` NULL.
- A validator snapshot's accounts database can keep a closed account as a zero-lamport entry until clean removes it, so a loader drops entries with 0 lamports before the null-read pass. A snapshot written by another tool also has no tombstone columns and no record of closes after it was taken. Load its addresses into the table, then run the null read over them before anything counts them as live.
- The statements print with literal values, which is safe for base58 text and signatures. Code that runs them uses placeholders.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The script prints that no closeAccount appeared in the newest 20 transactions. | Closes are common on the Token program but not guaranteed in every 20. Run it again, since the list moves within seconds. A larger limit costs 50 cells for each extra `getTransaction`, so check the cell budget of your plan first. |
| A `getTransaction` call fails with -32015. | The call left out `maxSupportedTransactionVersion` or set it to 0, and the signature belongs to a v1 transaction. Pass 1 in the config, as the script does. |
| A signature is listed but `getTransaction` answers null. | The address index lists signatures from below the validator's ledger floor, so an older one can have no body to read. Skip it. The newest signatures answer. |
| Lines starting `getTransaction failed` show 429 on a second run straight after the first. | A full run spends 1,000 cells of the transaction-lookup class, and the class refills at its plan's rate. Free refills one call about every 4 seconds. Wait for the refill, or use a plan whose rate covers the repeat. |
| The call answers 401. | Carbium does not recognise the key. Attach the whole key in the `x-api-key` header. |
| The tombstone `UPDATE` reports 0 rows changed. | Either the address is not in the mirror, a read newer than the close already refreshed its `slot`, or a tombstone at the same or a later slot is already there. Select the row and compare its `slot` and `closed_slot` with the printed values. |

## Questions

### Why tombstone a closed account instead of deleting its row?

The row records that the account existed, who owned it and what it held at the last live read. A delete loses that, and a reopened address then has no history. For the detection side alone, see [Closed account detection](https://carbium.sh/library/howsolana/closed-account-detection).

### Can a null read alone write the tombstone?

Only for an address your table already holds. A null `value` also describes an address that never held an account, and it carries no slot or signature of the close. A close instruction supplies both.

### How do I catch closes as they happen?

`logsSubscribe` by mention [streams transaction logs](https://carbium.sh/docs/websocket) for an address you name, and a subscription of that kind opens at 25 credits, then costs 20 credits per MiB sent. Subscribe for the owners you mirror and run the instruction check and null read on each transaction that logs a close. For the live half of a mirror, see [Postgres token balance watcher](https://carbium.sh/library/integrate/postgres-token-balance-watcher).

### Does the same pattern work in Postgres?

Yes. The columns and the slot comparisons carry over unchanged, and only the upsert syntax differs.

## Related

- [Closed account detection](https://carbium.sh/library/howsolana/closed-account-detection) (How to use Solana, HS0038)
- [Postgres token balance watcher](https://carbium.sh/library/integrate/postgres-token-balance-watcher) (Integrations, I0022)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/migrate](https://carbium.sh/docs/migrate)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
