---
id: HS0114
title: "Program subscription filters"
url: https://carbium.sh/library/howsolana/program-subscription-filters
collection: How to use Solana
category: WebSocket
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Program subscription filters

One TypeScript file opens a programSubscribe on the Token program for each mint you pass, each with a size filter and a mint filter, and prints the token account changes it receives, with amounts in base units.

## How the filters combine

`programSubscribe` takes a program id and an optional list of filters. The two that matter here are `dataSize`, which keeps accounts of exactly that many bytes, and `memcmp`, which keeps accounts whose data holds the given bytes at a given offset. Every filter in the list has to match, so a list is an AND. There is no OR inside one subscription.

That settles the question of multiple accounts. You can stack several conditions on one subscription, for example a size and a mint, and you get the accounts that satisfy all of them. You cannot hand one subscription two mints and receive either. Each value you want to match on its own needs its own subscription.

- One subscription per value: a `memcmp` filter per mint, per owner or per whatever sits at the offset. This is what the file below does.
- One `accountSubscribe` per address when you know the exact accounts. It is the narrowest feed and carries no program filter at all.
- One broad `programSubscribe` and a `Set` in your code that drops everything not on your list. It sends every account the program touches, so it only suits a program with little traffic.
- `logsSubscribe` with a mention, one address per subscription, when you want the logs of transactions that name an account and can do without its state.

## The code

The file needs no install. Export `CARBIUM_KEY` and run it with Node 24. Pass one or more mint addresses as arguments. With none, it watches USDC and wrapped SOL. It subscribes to the Token program once per mint, with two filters on each: `dataSize: 165`, the size of a classic token account, and a `memcmp` at offset 0, where a token account stores its mint.

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

```ts
// HS0114 · Program subscription filters
// https://carbium.sh/library/howsolana/program-subscription-filters
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const url = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
url.searchParams.set("api-key", key);

const TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const WSOL = "So11111111111111111111111111111111111111112";
const args = process.argv.slice(2);
const mints = args.length > 0 ? args : [USDC, WSOL];

const bySub = new Map<number, string>(); // subscription id -> mint
const counts = new Map<string, number>();
const ws = new WebSocket(url);

ws.addEventListener("open", () => {
  // Filters in one list are ANDed, so each mint gets its own subscription.
  mints.forEach((mint, i) => {
    ws.send(JSON.stringify({
      jsonrpc: "2.0",
      id: i + 1,
      method: "programSubscribe",
      params: [TOKEN_PROGRAM, {
        encoding: "base64",
        commitment: "confirmed",
        filters: [{ dataSize: 165 }, { memcmp: { offset: 0, bytes: mint } }],
      }],
    }));
  });
});

ws.addEventListener("message", (ev) => {
  const msg = JSON.parse(String(ev.data));
  if (msg.id !== undefined) {
    const mint = mints[msg.id - 1];
    if (msg.error) console.error(`subscribe refused for ${mint}: ${msg.error.message}`);
    else {
      bySub.set(msg.result, mint);
      console.log(`subscribed ${mint} as ${msg.result}`);
    }
    return;
  }
  if (msg.method !== "programNotification") return;
  const mint = bySub.get(msg.params.subscription) ?? "unknown";
  const { context, value } = msg.params.result;
  const data = Buffer.from(value.account.data[0], "base64");
  counts.set(mint, (counts.get(mint) ?? 0) + 1);
  console.log(`slot ${context.slot} ${mint.slice(0, 6)} ${value.pubkey} amount ${data.readBigUInt64LE(64)} base units`);
});

ws.addEventListener("error", () => console.error("socket error"));

setTimeout(() => {
  for (const mint of mints) console.log(`${mint}: ${counts.get(mint) ?? 0} notifications`);
  ws.close();
  process.exit(0);
}, 25_000);
```

Replies to the subscribe calls carry the request id, so the file maps each returned subscription id back to its mint. Every later notification names its subscription, which is how a line gets its label. The commitment is `confirmed` and the encoding is `base64`, so the account data arrives as bytes you slice yourself. The run ends after 25 seconds with a count per mint.

## Reading the output

After the subscribe lines you see one line per changed token account: the slot, the mint label, the token account address and its amount. The amount is a `u64` at byte offset 64 of the account data, printed in base units. Divide by ten to the power of the mint's decimals before you show it to anyone. USDC has 6 decimals, wrapped SOL has 9.

At confirmed commitment a changed account arrives once per slot, with its state at the end of that slot, so the same address on two lines means two slots. A wallet can own several token accounts for one mint, so two addresses can belong to one wallet and still be two separate accounts.

> Each line carries the account's full amount at that slot, never a change. If you write the amounts to a store, key the row by account address and keep the one from the newest slot.

## Choosing an approach

| Approach | Matches | Cost to know |
|---|---|---|
| Several programSubscribe, one filter each | Any mix of values at the same offset | One subscription per value, each in the heaviest class |
| One accountSubscribe per address | Exact accounts you list | One subscription per address |
| One broad programSubscribe, filter in code | Anything you can test in code | Every account the program writes crosses the wire |
| logsSubscribe with a mention | Transactions that name an address | One address per subscription, logs without account state |

The deciding number is how many values you have and how busy the program is. A short list of mints on the Token program fits the first row. A list of thousands of addresses does not fit any row well, and the broad subscription becomes a firehose that you pay for by the megabyte.

## On Carbium

The WebSocket endpoint is `wss://services.carbium.sh`, and the file puts the key in the URL as [`?api-key=`](https://carbium.sh/docs/auth). A program subscription sits in the heaviest of the three opening classes, 200 credits, against 25 for an account subscription and 5 for a slot subscription. After that, [20 credits per MiB sent](https://carbium.sh/docs/limits) apply. A subscription that is refused costs nothing.

Opening ten mints therefore costs 2,000 credits up front. The file shares one socket across all of them, and a plan caps connections and subscriptions per account, with Free carrying 5 sockets. Limits belong to the account, so every key on it draws from the same budget.

Account state on [`accountSubscribe`](https://carbium.sh/docs/websocket) arrives for streamed accounts. A plain SOL wallet sends nothing there. To follow one, subscribe with `logsSubscribe` mentions and read the balance with `getBalance` when a log arrives.

For the reconnect loop that a long-running version of this file needs, see [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect). For the same job over a list of deposit addresses, see [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor).

## Where it ends

The file matches on equality at a fixed offset. It cannot match a range, or a value that sits at different offsets in different layouts. A mint issued under Token-2022 keeps its token accounts in the Token-2022 program, so a subscription on the Token program never sees them. For such a mint, subscribe to the Token-2022 program id and drop `dataSize`, since an account with extensions runs past 165 bytes; the mint still sits at offset 0.

A new subscription starts at the current slot and replays nothing. Whatever changed while the socket was down is gone from the stream. Read the accounts again with `getMultipleAccounts` after a reconnect, which costs 10 cells per pubkey, and cap each call at 100 addresses unless your plan is Pro, where a call takes up to 300.

The file also stops after 25 seconds. A real watcher needs the silence watchdog and the backoff from the keepalive entry, and a decision about what to do with a burst: a busy mint can produce hundreds of lines a second, and each notification counts toward the MiB meter.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A second filter in the list seems to be ignored and the feed is wider than expected. | Every filter that reaches the server has to match, so a filter can only narrow the feed. A wider feed means one was lost on the way: check that `filters` sits inside the config object, the second item of `params`, and that each entry carries a `dataSize` or `memcmp` key spelled as in the file. |
| The subscription is accepted and nothing ever arrives. | The program, the size or the offset does not match any live account. A Token-2022 mint's accounts live under the Token-2022 program and are often longer than 165 bytes. Read one of its token accounts with `getAccountInfo`, check its owner program and data length, and confirm the mint is given in base58. |
| The reply to a subscribe call is an error and the file prints `subscribe refused`. | A refused subscription is not charged. Read the message in the reply and check the plan's socket and subscription caps for the account, since every key on it shares them. |
| Notifications from one mint show up under another mint's label. | Map the subscription id from the reply to the mint, and read the `subscription` field of each notification. Matching by arrival order breaks as soon as two replies come back in a different order. |
| The connection is refused with a 401, the file prints `socket error` and ends with zero notifications. | An unknown key gets 401 at the door. Check that `CARBIUM_KEY` holds the whole key. |

## Questions

### Can one programSubscribe take two mints at once?

No. The filters in one subscription are ANDed, and two `memcmp` filters at the same offset can never both match. Open one subscription per mint.

### Is dataSize required alongside memcmp?

No, but it narrows the feed. Without it, a `memcmp` at offset 0 would also match other account types in the program that happen to start with the same bytes.

### When is accountSubscribe a better fit?

When you know the exact addresses. It carries less than a program subscription and costs 25 credits to open on Carbium, against 200. It does not help for accounts whose addresses you do not know yet.

### How do I watch accounts that are created after I subscribe?

Use the program subscription. A filtered `programSubscribe` reports a new account the first time it matches, so you never need its address in advance.

## Related

- [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect) (How to use Solana, HS0036)
- [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor) (Blockchain ideas, BI0006)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
