services
Get a key

library / How to use Solana / Webhooks / HS0124

Account balance change webhook

One TypeScript file watches an account over Carbium's WebSocket, reads its balance after each transaction that mentions it, and POSTs the before, after and delta to your URL when the number moved. It only reads the chain and never signs.

By Carbium · Webhooks · HS0124 · updated 2026-11-23

01

The job

An on-chain program runs only inside a transaction. Nothing on the chain wakes a program because some other account's lamports changed, and a program has no way to subscribe to anything. So the notification has to come from outside: a process that watches the account and calls your server when the balance moves.

The watcher in this entry does that for the SOL balance of one address. It opens a logsSubscribe with mentions set to the account on Carbium's WebSocket. A program that credits or debits an account has to list that account in the transaction, so a balance change from a program shows up as a transaction that mentions it. For each one the watcher reads the balance, compares it with the last value it holds, and sends a POST when the two differ.

If your own program needs to react, the POST goes to a service of yours that builds and signs a follow-up transaction. This file does none of that. It holds no keypair and sends no transaction.

02

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types on load. Pass the account to watch as the first argument. With WEBHOOK_URL set, each change is POSTed there as JSON. Without it the file prints the same JSON, so one run shows the whole path. For a first look, pass an address that moves often, because an idle wallet prints only its starting balance.

main.ts
// HS0124 · Account balance change webhook// https://carbium.sh/library/howsolana/account-balance-change-webhook// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;const target = process.argv[2];if (!key || !target) {  console.error("Set CARBIUM_KEY and pass the account to watch: node main.ts <address> (optional WEBHOOK_URL)");  process.exit(1);}const hook = process.env.WEBHOOK_URL;const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }));const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");wsUrl.searchParams.set("api-key", key);let balance: bigint | null = null;async function check(slot?: number, sig: string | null = null) {  const { value: after, context } = await rpc.getBalance(address(target as string), { commitment: "confirmed", minContextSlot: slot === undefined ? undefined : BigInt(slot) }).send();  const before = balance;  balance = after;  if (before === null) return console.log(`watching ${target}, balance ${after} lamports at slot ${context.slot}`);  if (before === after) return;  const body = JSON.stringify({ address: target, signature: sig, slot: Number(context.slot), before: String(before), after: String(after), delta: String(after - before) });  console.log(body);  if (!hook) return;  const r = await fetch(hook, { method: "POST", headers: { "content-type": "application/json" }, body });  if (!r.ok) console.error(`hook answered ${r.status}`);}// One read at a time, so each delta compares against the read before it.let queue: Promise<void> = Promise.resolve();const run = (slot?: number, sig?: string) => {  queue = queue.then(() => check(slot, sig)).catch((e) => console.error(`check failed: ${e.message}`));};function connect() {  const ws = new WebSocket(wsUrl);  ws.addEventListener("open", () => {    ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [target] }, { commitment: "confirmed" }] }));    run(); // first read, or the catch-up read after a reconnect  });  ws.addEventListener("message", (m) => {    const msg = JSON.parse(String(m.data));    if (msg.error) return console.error(`refused: ${msg.error.message}`);    if (msg.method !== "logsNotification") return;    const { context, value } = msg.params.result;    if (!value.err) run(context.slot, value.signature); // a failed transaction moves no lamports but its fee  });  ws.addEventListener("close", () => {    console.error("socket closed, reconnecting");    setTimeout(connect, 2000);  });}connect();

run: node main.ts <address>

The queue keeps the reads in order. A notification can arrive while the previous read is still in flight, and two overlapping reads would compare against the wrong earlier value. Each read passes the notification's slot as minContextSlot, so the node must have reached that slot before it answers and the balance can never predate the transaction that triggered it. A call to a node that is still behind fails with a message, and the watcher prints check failed and waits for the next transaction.

A transaction that failed on chain has err set and moves no lamports beyond its fee, so the file skips it. If the watched account paid that fee, the next read folds it into its delta. After a reconnect the file reads the balance once without a signature, which catches anything that happened while the socket was down.

03

What your server receives

FieldValue
addressThe account being watched.
signatureThe transaction that triggered the read, or null for the check after a reconnect.
slotThe slot the balance was read at.
beforeThe previous balance in lamports, as a string.
afterThe new balance in lamports, as a string.
deltaafter minus before in lamports. Negative when the account paid out.

Amounts are strings because a lamport count can pass the largest integer a JSON number holds exactly. Parse them with BigInt. One SOL is 1,000,000,000 lamports, so divide only when you display the value.

$The signature names the transaction that triggered the read, and the delta can cover more than that one. The read returns the balance at the node's confirmed slot, which can be past the notification's slot, so when two transactions land close together the first event carries both changes and the second finds no change and sends nothing.
04

On Carbium

The file sets the key on the WebSocket URL through searchParams and sends it in the x-api-key header with each getBalance, and never prints it. The subscription and the read both run at confirmed commitment, set in the code.

A logsSubscribe with mentions opens at 25 credits, then costs 20 credits per MiB sent. A refused subscription costs nothing. Free carries 5 sockets, and the WebSocket caps connections and subscriptions per account by plan. An account's keys share one budget, so a second watcher on another key draws from the same one.

Each notification triggers one getBalance, and each of those counts toward your rate limits. A read refused with 429 carries a retry-after hint, and the file reports it as check failed.

Watch accounts that matter to you. A heavily used account sends a notification for every transaction that names it, and the 20 credits per MiB add up. To cover many addresses with one connection, see address transaction webhooks, which also signs each POST.

05

Where it ends

This watches SOL lamports. On Carbium it is the live signal for a plain SOL wallet, because accountSubscribe sends nothing for one. A token balance sits in a token account, so pass that account's address, swap the read for getTokenAccountBalance and compare BigInt(value.amount).

The state lives in memory. The first read after a restart becomes the new baseline, so a change made while the process was down is not reported. Store the last balance and slot if you need to span restarts.

Delivery is one attempt. If your server is down or answers an error, the watcher prints the status and moves on, and that change is lost. Add retries or write to a table first, as the signed relay linked above does.

A read that fails is not retried, so its change waits for the next transaction on the account. If a change must never wait, add a periodic read of the same account that runs the same comparison.

06

When it goes wrong

what goes wrongwhat to do
refused: followed by a message right after the socket opens.The subscription was turned down, for example because the account is at its socket or subscription cap for its plan. Free carries 5 sockets. A refused subscription costs no credits. Close an idle socket or move to a plan with a higher cap.
socket closed, reconnecting repeating every 2 seconds.Check that CARBIUM_KEY holds the whole key and that the account is under its socket cap. A turned-down handshake never opens the socket, so the loop retries forever. Add a growing pause or a retry limit before you run the file unattended.
check failed with HTTP 429.The balance reads came faster than your plan's rate for that method. Wait the retry-after hint and the next transaction triggers a fresh read. The file does not retry a failed read, so on a low plan a busy account folds several changes into one event, and the last change before a quiet spell waits for the next transaction.
check failed with a message about the minimum context slot.The node answered before it reached the notification's slot. The next notification reads again from the then-current balance, so the delta covers both. Nothing is lost when later transactions arrive; the last one in a quiet period is.
hook answered 500 or a fetch error, and the change never reaches your server.The watcher sends each POST once. Bring the receiver back and compare the balance by hand. For a receiver that is often down, write each event to a table first and deliver from there.
07

Questions

Can a program on chain subscribe to another account's balance?

No. A program runs only while a transaction executes it, and nothing triggers it on a state change. Watch the account from outside and have your server submit a transaction when it should act.

Does this catch changes made by another program?

Yes. Any program that moves lamports in or out of the account has to name it in the transaction, so the transaction appears in the mentions feed. The watcher then reads the real balance.

Can I watch a token balance the same way?

Yes. Pass the token account's address and replace getBalance with getTokenAccountBalance. The mentions subscription works the same, and the token amount is a string in base units.

Why compare balances instead of parsing the logs?

Logs show which programs ran and whatever they chose to print, which seldom includes a balance. Reading the balance gives the exact number and covers every way an account can change.