---
id: I0115
title: "WhatsApp low-balance alerts"
url: https://carbium.sh/library/integrate/whatsapp-low-balance-alerts
collection: Integrations
category: Chat and notifications
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# WhatsApp low-balance alerts

A small Node watcher reads up to 100 wallet balances in one Carbium call every minute and sends a WhatsApp template message when a wallet drops under your limit and again when it recovers. Without WhatsApp credentials it prints the message instead.

## What the watcher does

The watcher is one Node process with one dependency, `@solana/kit`. You give it up to 100 wallet addresses on the command line and a limit in SOL. Every 60 seconds it reads all the balances in a single call and compares each one with the limit. It writes to WhatsApp only when a wallet changes side: one message when a balance falls under the limit, and one when it climbs back to the limit or above.

| State | When | WhatsApp message |
|---|---|---|
| ok | The balance is at or above the limit. | One, when the wallet returns from low. |
| low | The balance is under the limit, or the account does not exist. | One, when the wallet enters this state. |

The set of low wallets lives in memory. A restart forgets it, so a wallet that is still low when the process starts alerts again on the first poll. That also makes the first run an easy test: start it with a limit above every balance and each wallet sends one message.

## The Solana side: one call for every balance

The read is `getMultipleAccounts`. It takes the whole address list and returns one entry per address, in the order you sent them, all from the same slot. The response carries that slot, and the alert text quotes it, so a message can be matched to the chain later. The call reads at `confirmed` commitment, and the code names it.

The watcher asks for a data slice of length 0. A wallet is a system account with no data, but an address pasted into the list may be a program or a large account, and the slice keeps each entry down to its lamports and owner either way. An account that holds no lamports does not exist on chain, and the call returns `null` for it. The watcher reads that as a balance of 0, so an emptied wallet alerts as low.

Lamports come back as a `bigint`. The comparison stays in lamports, and only the message text converts to SOL, with four decimals. The limit becomes lamports once, at start.

## The WhatsApp side: one template, one POST

The sender is the WhatsApp Cloud API from Meta. In the Meta developer dashboard, add a WhatsApp number to your business app. The dashboard shows a phone number ID beside the number, and that ID goes in `WHATSAPP_PHONE_ID`. Create an access token for the app. The temporary token in the dashboard expires after 24 hours, so for a watcher that stays up, create a system user and a permanent token for it.

An alert usually goes to someone who has not written to your number in the last 24 hours, and outside that window WhatsApp accepts only a template message. Create a template with the category Utility and one variable, for example the body `Wallet monitor: {{1}} Top it up soon.` Meta rejects a body that starts or ends with a variable, which is why fixed words sit on both sides. Wait until the dashboard shows it as approved, then put its name in `WHATSAPP_TEMPLATE`.

The watcher then POSTs to `/<phone number ID>/messages` on the Graph API with the token as a bearer token. The body names the template, a language code (`en_US` unless `WHATSAPP_LANG` says otherwise) and one text parameter that holds the whole alert. Parameter text may not contain a newline, a tab or more than four spaces in a row, so each alert is one line. The recipient goes in `WHATSAPP_TO` as digits with the country code.

The test number that comes with a new app sends to at most five recipient numbers that you list in the dashboard. A send to any other number fails with error 131030.

The state changes only after the API answers with a 2xx status. If the token is wrong or Meta is down, the next poll tries the same alert again.

## The watcher

Install the dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. `CARBIUM_KEY` is required, and the file exits with a message without it. `WHATSAPP_TOKEN`, `WHATSAPP_PHONE_ID`, `WHATSAPP_TO` and `WHATSAPP_TEMPLATE` work as a set: when any of them is missing, the watcher prints each alert after the words `dry run, would send:` and sends nothing. `LOW_SOL` (default 0.1), `CARBIUM_RPC_URL`, `WHATSAPP_API_URL` and `WHATSAPP_LANG` are optional.

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

```ts
// I0115 · WhatsApp low-balance alerts
// https://carbium.sh/library/integrate/whatsapp-low-balance-alerts
// 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 wallets = process.argv.slice(2).map((a) => address(a));
const lowSol = Number(process.env.LOW_SOL ?? 0.1);
if (wallets.length < 1 || wallets.length > 100 || !Number.isFinite(lowSol) || lowSol < 0) {
  console.error("Usage: node main.ts <wallet> [<wallet> ...] (1 to 100 wallets; LOW_SOL is a number of SOL)");
  process.exit(1);
}
const lowLamports = BigInt(Math.round(lowSol * 1e9));
const POLL_MS = 60_000;
const deadline = () => AbortSignal.timeout(10_000);

const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const { WHATSAPP_TOKEN: token, WHATSAPP_PHONE_ID: phoneId, WHATSAPP_TO: to, WHATSAPP_TEMPLATE: template } = process.env;
const graph = process.env.WHATSAPP_API_URL ?? "https://graph.facebook.com/v23.0";
const lang = process.env.WHATSAPP_LANG ?? "en_US";

// One template message whose single body variable carries the whole alert line.
async function send(text: string): Promise<void> {
  if (!token || !phoneId || !to || !template) {
    console.log("dry run, would send:", text);
    return;
  }
  const res = await fetch(`${graph}/${phoneId}/messages`, {
    method: "POST",
    headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
    signal: deadline(),
    body: JSON.stringify({
      messaging_product: "whatsapp",
      to,
      type: "template",
      template: { name: template, language: { code: lang }, components: [{ type: "body", parameters: [{ type: "text", text }] }] },
    }),
  });
  if (!res.ok) throw new Error(`WhatsApp answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
  console.log("sent:", text);
}

const low = new Set<string>(); // wallets that already got a low-balance message
const sol = (lamports: bigint) => (Number(lamports) / 1e9).toFixed(4);

async function poll(): Promise<void> {
  const { context, value } = await rpc
    .getMultipleAccounts(wallets, { commitment: "confirmed", encoding: "base64", dataSlice: { offset: 0, length: 0 } })
    .send({ abortSignal: deadline() });
  for (let i = 0; i < wallets.length; i++) {
    const wallet = wallets[i];
    const lamports = value[i]?.lamports ?? 0n; // a missing account holds nothing
    const isLow = lamports < lowLamports;
    if (isLow === low.has(wallet)) continue;
    const text = isLow
      ? `${wallet} holds ${sol(lamports)} SOL, under the ${lowSol} SOL limit (slot ${context.slot}).`
      : `${wallet} is back to ${sol(lamports)} SOL, at or over the ${lowSol} SOL limit (slot ${context.slot}).`;
    try {
      await send(text);
      if (isLow) low.add(wallet);
      else low.delete(wallet); // state moves only after the send succeeded, so a failure is retried
    } catch (err) {
      console.error("alert failed:", err instanceof Error ? err.message : err);
    }
  }
  console.log(`slot ${context.slot}: ${wallets.length} wallets read, ${low.size} low`);
}

for (;;) {
  await poll().catch((err: unknown) => console.error("poll failed:", err instanceof Error ? err.message : err));
  await new Promise((r) => setTimeout(r, POLL_MS));
}
```

## Run it in three steps

Start with `node main.ts <wallet> <wallet>` and no WhatsApp variables, and set `LOW_SOL` above every balance. Each wallet prints one dry run line, and a status line follows every poll with the slot and the count of low wallets.

Then set the four WhatsApp variables, using a recipient number from the dashboard's list, and run it again. Each wallet sends one message, and the chat shows the template with the alert text in place of `{{1}}`, for example `Wallet monitor: 7xK...q2 holds 0.0412 SOL, under the 0.1 SOL limit (slot 412345678). Top it up soon.`

Last, set the limit you want and run the file under a supervisor such as a systemd unit, so it survives a crash and a reboot.

## What it costs against your limits

[`getMultipleAccounts` charges 10 cells per pubkey](https://carbium.sh/docs/rpc). Ten wallets cost 100 cells a poll, which is 100 cells a minute. A list of 100 wallets is the 1000-cell call, close to the 1,024 cells a rate class absorbs as a burst, so a list that size belongs on a slow poll like this one. Below Pro, that burst caps a call at 100 pubkeys, and the watcher caps its list at 100 so the same file runs on any plan.

[Limits are per account](https://carbium.sh/docs/limits), so all your keys share one budget. Account reads on Free run at 0.5 req/s. At 10 cells a read, that refills 5 cells a second, or 300 cells a minute, so on Free a poll every minute keeps up with 30 wallets. A longer list on Free needs a longer `POLL_MS`, or the polls after the first one get 429.

## Where it ends

- It reads SOL balances only. Token balances are not read, so a token account running low does not alert.
- One limit applies to every wallet in the list. Per-wallet limits mean a small map in place of `lowLamports`.
- A poll every 60 seconds sees the balance at that moment. A balance that dips and recovers between two polls goes unseen.
- A wallet that stays low gets one message. The watcher sends no reminder, and a restart is the only thing that repeats it.
- A 2xx answer means Meta accepted the message. Delivery to the phone is a separate step that the watcher does not track.
- A balance that hovers around the limit alerts on each crossing. The recovery point is the limit itself, with no margin.
- A watcher that dies sends nothing. Supervise the process, and let a second check tell you when it stops.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The log shows `alert failed: WhatsApp answered 401` and the error text mentions an expired token (code 190). | The temporary dashboard token lasted 24 hours. Create a system user in the business settings, give it the WhatsApp permissions, generate a permanent token and put it in `WHATSAPP_TOKEN`. The next poll sends the waiting alert. |
| The log shows `alert failed: WhatsApp answered 400` with error 131030. | The recipient is not on the test number's list. Add the number in the dashboard and confirm it with the code WhatsApp sends there, or finish business verification and use a production number. |
| The log shows error 132001 (template does not exist) or 132000 (parameter count mismatch). | `WHATSAPP_TEMPLATE` and the language code must match an approved template exactly, and the template body must hold one variable. Check the name and the language in the template list, and set `WHATSAPP_LANG` if the template is not in `en_US`. |
| The log shows `poll failed:` followed by an HTTP error (401) and no alert ever fires. | Carbium does not know the key. Check that `CARBIUM_KEY` holds the whole key, then see [how keys are sent](https://carbium.sh/docs/auth). While the poll fails, the watcher keeps its state and sends nothing. |
| The log shows `poll failed:` with an HTTP error (429) now and then. | Your account's budget is spent, either by app traffic on other keys or by a list of more than 30 wallets on Free. The watcher tries again at the next poll. Lower the other traffic or move to a plan with a higher rate if it keeps happening. |
| Messages arrive on every crossing while the balance sits near the limit. | Add a margin: leave the low state only when the balance reaches the limit plus 20 percent. That is one extra comparison in the poll loop. |

## Questions

### Can I send plain text and skip the template?

Only inside the 24 hours after the recipient last wrote to your number. An alert has no such conversation behind it, so Meta requires an approved template.

### Could a WebSocket subscription replace the polling?

Not for a plain SOL wallet. `accountSubscribe` sends nothing for one, and the [WebSocket](https://carbium.sh/docs/websocket) route is `logsSubscribe` with mentions plus a `getBalance` read. A subscription also opens at 5, 25 or 200 credits and then costs 20 credits per MiB sent, so one call a minute is the simpler job here.

### How do I watch more than 100 wallets?

Run a second process with the next list. Pro allows 300 pubkeys in one `getMultipleAccounts` call, and you can raise the cap in the code if you run on Pro.

### Where does this fit next to a chain halt or a fee sponsor budget?

The same pattern carries over: poll, compare, send on a change. [Chain halt SMS alerts](https://carbium.sh/library/integrate/chain-halt-sms-alerts) does it for slot progress, and [Fee sponsor budget monitor](https://carbium.sh/library/usecase/fee-sponsor-budget-monitor) is the budget case behind a low-balance alert.

## Related

- [Fee sponsor budget monitor](https://carbium.sh/library/usecase/fee-sponsor-budget-monitor) (Use cases, UC0031)
- [Chain halt SMS alerts](https://carbium.sh/library/integrate/chain-halt-sms-alerts) (Integrations, I0045)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
