---
id: HS0125
title: "Token burn event webhook"
url: https://carbium.sh/library/howsolana/token-burn-event-webhook
collection: How to use Solana
category: Webhooks
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Token burn event webhook

One TypeScript file listens to both token programs over WebSocket, spots burn instructions in the logs, reads each transaction, and prints the mint, the raw amount and the signature. It only reads and never holds a keypair.

## What a burn looks like

A burn is a token program instruction that destroys tokens in a token account and lowers the mint's supply by the same amount. The classic token program and Token-2022 both have two forms: `Burn`, which carries an amount, and `BurnChecked`, which also carries the mint's decimals. Each form writes a log line, `Program log: Instruction: Burn` or `Program log: Instruction: BurnChecked`, so a log stream is enough to notice a burn without decoding every transaction.

That makes the job two steps. A `logsSubscribe` on each token program tells you a transaction touched the program, and a match on the burn line narrows those to burns. The log line carries neither the mint nor the amount, so a second call reads the transaction and takes both from the parsed instruction. The file below does both steps and hands each burn to one function, `onBurn`. That function is the place to POST to your own endpoint, write a row or send a message.

The LP token of a liquidity pool is an ordinary mint. Burning LP tokens is the same instruction, so the same code catches it.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24. The one optional argument is the number of seconds to listen. With no argument it listens until you stop it.

`main.ts` (run: `node main.ts [seconds]`)

```ts
// HS0125 · Token burn event webhook
// https://carbium.sh/library/howsolana/token-burn-event-webhook
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { setTimeout as sleep } from "node:timers/promises";
import { createDefaultRpcTransport, createSolanaRpcFromTransport, signature } 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 wsUrl = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";
// Token program and Token-2022. Add a locker program id here to watch locks too.
const PROGRAMS = [
  "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",
];
const seconds = Number(process.argv[2] ?? 0);
type Ix = { parsed?: { type?: string; info?: Record<string, any> } };
type Bal = { accountIndex: number; mint: string };
type Tx = {
  meta: {
    preTokenBalances?: Bal[];
    postTokenBalances?: Bal[];
    innerInstructions?: { instructions: Ix[] }[];
  } | null;
  transaction: { message: { accountKeys: { pubkey: string }[]; instructions: Ix[] } };
};
// Replace the body to POST to your own endpoint or write a row.
function onBurn(b: { mint: string; amount: string; sig: string }) {
  console.log(`burn mint=${b.mint} amount=${b.amount} sig=${b.sig}`);
}
async function report(sig: string) {
  for (let i = 0; i < 4; i++) {
    const tx = (await rpc
      .getTransaction(signature(sig), { encoding: "jsonParsed", commitment: "confirmed", maxSupportedTransactionVersion: 1 })
      .send()) as unknown as Tx | null;
    if (!tx) { await sleep(500); continue; }
    const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey);
    const mints = new Map<string, string>();
    const balances = [...(tx.meta?.preTokenBalances ?? []), ...(tx.meta?.postTokenBalances ?? [])];
    for (const b of balances) mints.set(keys[b.accountIndex], b.mint);
    const inner = (tx.meta?.innerInstructions ?? []).flatMap((g) => g.instructions);
    for (const { parsed } of [...tx.transaction.message.instructions, ...inner]) {
      if (parsed?.type !== "burn" && parsed?.type !== "burnChecked") continue;
      const info = parsed.info ?? {};
      onBurn({ mint: info.mint ?? mints.get(info.account) ?? "unknown", amount: info.amount ?? info.tokenAmount?.amount, sig });
    }
    return;
  }
  console.log(`no transaction yet for ${sig}`);
}
const seen = new Set<string>();
let inflight = 0;
let burns = 0;
const ws = new WebSocket(`${wsUrl}?api-key=${key}`);
ws.onopen = () =>
  PROGRAMS.forEach((p, i) =>
    ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 1, method: "logsSubscribe", params: [{ mentions: [p] }, { commitment: "confirmed" }] })),
  );
ws.onmessage = (ev) => {
  const msg = JSON.parse(String(ev.data));
  if (msg.id) {
    console.log(msg.error ? `subscribe ${msg.id} failed: ${JSON.stringify(msg.error)}` : `subscribed to ${PROGRAMS[msg.id - 1]}`);
    return;
  }
  if (msg.method !== "logsNotification") return;
  const v = msg.params.result.value;
  if (v.err || seen.has(v.signature)) return;
  if (!v.logs.some((l: string) => l.includes("Instruction: Burn"))) return;
  seen.add(v.signature);
  burns++;
  if (inflight >= 5) {
    console.log(`burn sig=${v.signature} (lookup skipped, 5 in flight)`);
    return;
  }
  inflight++;
  report(v.signature)
    .catch((e) => console.log(`lookup failed for ${v.signature}: ${e instanceof Error ? e.message : e}`))
    .finally(() => inflight--);
};
ws.onerror = () => console.error("socket error");
ws.onclose = () => { console.log("socket closed"); process.exit(1); };
if (seconds > 0) {
  setTimeout(() => { console.log(`done: ${burns} burns in ${seconds}s`); process.exit(0); }, seconds * 1000);
}
```

The socket URL carries the key as `?api-key=`, and two subscriptions open on that one socket, one per token program, both at `confirmed`. A notification with an empty `err` and a burn line goes to `report`. It calls `getTransaction` with `jsonParsed` encoding and `maxSupportedTransactionVersion: 1`, and it names `commitment: "confirmed"` to match the subscriptions. Kit would fill in confirmed anyway when a call leaves it out, where the server on its own would use finalized. A null answer is retried a few times, since a node can announce a log a moment before it can serve the transaction. At most 5 lookups run at once. A burn past that limit prints its signature only.

Burns turn up in the top-level instructions and in inner instructions. A swap or a locker that burns for you calls the token program through a cross-program invocation, and that call sits in `innerInstructions`. The parsed `burn` and `burnChecked` both carry `info.mint`. As a fallback the file also builds an account-to-mint map from the transaction's pre and post token balances, reading both lists because an account burned empty and closed in the same transaction only appears in the pre list.

## Reading the output

Each burn prints one line: `burn mint=<mint> amount=<raw> sig=<signature>`.

| Field | Source | Meaning |
|---|---|---|
| mint | `info.mint`, else the token balance map | The token whose supply dropped. `unknown` when neither source names it. |
| amount | `info.amount`, or `tokenAmount.amount` for BurnChecked | The raw count in the mint's smallest unit, as a string. |
| sig | The log notification | The transaction to open in an explorer or fetch again. |

Keep `amount` as a string and convert with `BigInt`. A mint with 9 decimals and a large supply passes 2^53 in raw units, and a float rounds the last digits. To show a person the number, divide by 10 to the power of the mint's decimals, which `getTokenSupply` returns for the mint.

> A burn lowers supply. A transfer to a dead address leaves the supply as it was. If your rule is that tokens are gone, test for a burn instruction, since a transfer to a burn address can be undone by whoever holds that key.

## Watching LP locks

A lock moves LP tokens into a vault owned by a locker program, and the vault holds them until a date or for good. On chain it looks like a token transfer plus whatever instruction the locker defines. The supply stays the same, so the burn line never appears.

To watch locks, add the locker's program id to `PROGRAMS`. The `mentions` filter takes one address, so each program id gets its own subscription, and the file already loops over the list. Then swap the filter. Each locker writes its own log lines and instruction data, so replace the burn test with that program's line and decode its layout, or look for parsed token transfers whose destination is the locker's vault. The LP mint of the pool you care about is the other handle: the mint's address can go in `mentions` too.

The same trick narrows the burn stream. A `Burn` or `BurnChecked` lists the mint among its accounts, so one subscription with the mint's address in `mentions` sees only transactions that touch that token, and the burn line test keeps its burns. For a pool's LP mint, that is usually all you need, and it cuts the traffic by orders of magnitude. For a check of whether liquidity is already locked, see [Liquidity lock checker](https://carbium.sh/library/blockchainideas/liquidity-lock-checker).

## On Carbium

Open the socket at `wss://services.carbium.sh` with the key as `?api-key=` in the URL, as the [WebSocket](https://carbium.sh/docs/websocket) section describes. A `logsSubscribe` with `mentions` is the middle weight and costs 25 credits to open, then 20 credits per MiB sent. The token programs sit in most transactions, so the unfiltered pair streams a lot of text, and a mint-level subscription is the lighter habit. A refused subscription costs nothing. Free carries 5 sockets, and this file uses one.

`getTransaction` costs 50 cells per call, which is why the file caps lookups in flight. Each plan also caps its [calls per second](https://carbium.sh/docs/limits). With `maxSupportedTransactionVersion` absent or 0, a v1 transaction answers -32015 with no charge. The file passes 1 so it never sees that error.

## Where it ends

A log subscription has no replay. If the socket drops, burns during the gap are never delivered, and the file exits instead of reconnecting. Run it under a supervisor and add the reconnect logic from [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect). To fill a gap, call `getSignaturesForAddress` on the mint for the missed window. That index reaches back 30 days at most, and the transactions it lists can read as null on `getTransaction` for older ones.

Notifications at confirmed can belong to a fork that is later dropped, so a burn that triggers something you cannot undo, such as releasing funds, should be checked again at finalized before it acts. Finalized now trails processed by one slot at most, so that second read costs little wait.

The file reads only the parsed `burn` and `burnChecked` instructions of the two token programs. Confidential burns under Token-2022 and any custom program that reduces a balance in its own way are not decoded. The 5-lookup cap also means a busy minute prints some burns without a mint or an amount. Raise it only as far as your plan's `getTransaction` rate allows.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The run prints `socket error` and `socket closed` before any `subscribed` line. | The connection was refused. A 401 there means the key is unknown, so send the whole key in `?api-key=`. If a `subscribe 1 failed` line shows instead, read its error body: your plan caps subscriptions per account, so close idle ones first. |
| `getTransaction` answers -32015 for some burns. | The call left out `maxSupportedTransactionVersion`, or set it to 0, and the transaction is v1. Pass 1. |
| Lines of `no transaction yet for <signature>`. | The node announced the log before it could serve the transaction. Fetch it again a few seconds later, or raise the retry count or the 500 ms wait in `report`. |
| Burns print with `mint=unknown`. | The parsed instruction had no `info.mint` and the token account was not in the pre or post token balances. Read `info.account` and call `getAccountInfo` on it, or subscribe on the mint's address and take the mint from that. |
| Credits drain quickly while the file runs. | The token programs appear in most transactions, so the stream is large. Subscribe with the mint or the pool's LP mint in `mentions` instead. |
| The file exits with `socket closed` after a long run. | A socket can drop on any network fault, and the file exits on every close. Start it under a supervisor that restarts it, and back-fill the gap from signatures. |

## Questions

### Is a transfer to the burn address the same as a burn?

No. A burn instruction lowers the mint's supply. A transfer to a dead address moves tokens and leaves the supply unchanged, and the file reports only the instruction.

### Can I watch one token's burns instead of all of them?

Yes. Put the mint's address in `mentions`. A burn lists the mint among its accounts, so that subscription sees only that token, and the same burn filter applies.

### Do I need a separate webhook service to get these events?

Not for this job. The socket pushes the logs to your process, and `onBurn` is the place to forward each event to your own HTTP endpoint.

### How do I find burns from the last few days?

Call `getSignaturesForAddress` on the mint, which reaches back 30 days, then read each transaction the way `report` does. Handle null answers for older signatures.

## Related

- [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect) (How to use Solana, HS0036)
- [Liquidity lock checker](https://carbium.sh/library/blockchainideas/liquidity-lock-checker) (Blockchain ideas, BI0023)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
