services
Get a key

library / Integrations / I0005

Python program subscriptions

A Node script opens one programSubscribe on Carbium's WebSocket, filters to one mint's token accounts, prints each account update and the bytes received, then closes. It shows the exact messages your Python code, using solana-py, sends and reads.

By Carbium · Solana wallets and libraries · I0005 · updated 2026-11-22

01

What the script does

The script opens one WebSocket to Carbium, sends a single programSubscribe request and prints what comes back. It takes a program id and, optionally, a mint address. With a mint, it asks only for the SPL token accounts of that mint. It stops after 10 updates or 20 seconds, prints the count of updates and bytes received, and exits with 0 if at least one update arrived.

A program subscription reports an account owned by the program each time that account changes. A Python client sends the same exchange.

DirectionMessageWhat it means
OutprogramSubscribe with the program id and a config objectEvery change to an account the program owns, shaped by the filters.
InA reply with the same id and a number as resultThe subscription id. Keep it to tell subscriptions apart on one socket.
InA programNotification with context.slot and a value holding pubkey and accountOne changed account at that slot.
InAn error in place of a resultThe subscription was refused, and a refused subscription is free.
02

The Python side: program_subscribe in solana-py

In solana-py the same request is program_subscribe, called on the socket that solana.rpc.websocket_api.connect gives you. You pass the program as a Pubkey, and you give the commitment, the encoding and the filters as keyword arguments, because the method takes data_slice between the encoding and the filters and a positional fourth argument lands there. The first recv() returns the subscription confirmation, and later ones return notifications with the slot and the account. Argument names and order shift a little between releases, so read the signature of the version you installed.

Point connect at the WebSocket endpoint, wss://services.carbium.sh, with the key as ?api-key=<YOUR_KEY> on the URL. Read the whole URL from an environment variable and keep it out of your logs, since the query string holds the key.

Filters decide how much you receive. An integer in the list is a size check, so 165 keeps accounts of exactly 165 bytes, the size of a plain SPL token account. A byte match is a MemcmpOpts filter from solana.rpc.types, written MemcmpOpts(offset=0, bytes=str(mint)), because its bytes field takes a base58 string. A token account stores its mint in its first 32 bytes, so a match at offset 0 against a mint address keeps the accounts of that mint. The script sends the same two filters as dataSize and memcmp.

The Python side is one call sequence, in this order, with program and mint as Pubkey values and url read from your environment.

  1. Import connect from solana.rpc.websocket_api and MemcmpOpts from solana.rpc.types.
  2. Open the socket with async with connect(url) as ws:.
  3. Subscribe with await ws.program_subscribe(program, commitment="confirmed", encoding="base64", filters=[165, MemcmpOpts(offset=0, bytes=str(mint))]).
  4. Read the confirmation with first = await ws.recv(). It comes back as a list, and first[0].result is the subscription id.
  5. Loop over the notifications with async for batch in ws:, then for msg in batch:. Each msg.result carries context.slot and a value with the pubkey and the account. Break out of the loop when you have enough updates.
  6. Leave the async with block. Closing the socket ends the subscription.
03

The Solana side: commitment, encoding and the first message

The script asks for confirmed, so each update arrives once its slot has a supermajority of votes. A request that leaves commitment out gets the server's default, which is finalized.

The script asks for base64 account data. A 165 byte account becomes 220 characters, and Python decodes it with base64.b64decode. What the bytes mean depends on the program, and the script prints only their length.

Notifications arrive with no request id and the method name programNotification, which is how the script tells the two apart.

04

The script

Install the one dependency with npm install @solana/[email protected], and set "type": "module" in package.json. Node 24 strips the types on load. The script uses @solana/kit only to check the addresses you pass, and the socket is Node's global WebSocket. CARBIUM_KEY is required. CARBIUM_WS_URL, MAX_EVENTS and WAIT_S are optional.

main.ts
// I0005 · Python program subscriptions// https://carbium.sh/library/integrate/python-program-subscriptions// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { isAddress } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY.");  process.exit(1);}const [programId, mint] = process.argv.slice(2);if (!programId || !isAddress(programId) || (mint !== undefined && !isAddress(mint))) {  console.error("Usage: node main.ts <program id> [mint to filter token accounts by]");  process.exit(1);}const maxUpdates = Number(process.env.MAX_EVENTS ?? 10);const waitMs = Number(process.env.WAIT_S ?? 20) * 1000;const url = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");url.searchParams.set("api-key", key);// A size check plus a byte match on the mint (offset 0) picks one mint's SPL token accounts.const filters = mint ? [{ dataSize: 165 }, { memcmp: { offset: 0, bytes: mint } }] : [];const ws = new WebSocket(url.href);let updates = 0;let bytes = 0;function finish(code: number): never {  ws.close();  console.log(`${updates} updates, ${bytes} bytes received`);  process.exit(code);}setTimeout(() => finish(updates > 0 ? 0 : 1), waitMs);ws.addEventListener("open", () => {  ws.send(    JSON.stringify({      jsonrpc: "2.0",      id: 1,      method: "programSubscribe",      params: [programId, { commitment: "confirmed", encoding: "base64", filters }],    }),  );});ws.addEventListener("error", () => {  console.error("socket error: check CARBIUM_KEY and CARBIUM_WS_URL");  finish(1);});ws.addEventListener("close", () => finish(updates > 0 ? 0 : 1));ws.addEventListener("message", (event) => {  const text = String(event.data);  bytes += Buffer.byteLength(text);  const msg = JSON.parse(text);  if (msg.error) {    console.error("refused:", msg.error.code, msg.error.message);    finish(1);  } else if (msg.id === 1) {    console.log("subscription id", msg.result);  } else if (msg.method === "programNotification") {    const { context, value } = msg.params.result;    const size = Buffer.from(value.account.data[0], "base64").length;    console.log(`slot ${context.slot} ${value.pubkey} ${value.account.lamports} lamports, ${size} data bytes`);    if (++updates >= maxUpdates) finish(0);  }});

run: node main.ts TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v

Run it with the Token program id and the USDC mint as arguments: node main.ts TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v. It prints the subscription id, then one line per changed token account, then the totals.

05

What a subscription costs

A program subscription sits in the heaviest of three opening classes. It opens at 200 credits, where an account or logs mentions subscription opens at 25 and a slot or signature one at 5. After that it costs 20 credits per MiB sent.

The per MiB charge follows the bytes Carbium sends you, so the filter is your cost control. An unfiltered subscription sends every change to every account of the program, and you pay for all of it. To get the credits your stream used, convert the byte total the script prints into MiB and multiply by 20. The Free plan has 500K credits once at sign-up, and Dev, Business and Pro have 10M, 50M and 200M a month.

Connection and subscription counts are capped per account by tier, and Free carries 5 sockets. Limits are per account, so all your keys share them. A Python service should open one socket and put several subscriptions on it, each with its own id and its own 200 credits to open. If your alerts watch for limit trouble, see RPC rate-limit alerts.

06

Where it ends

  • The Python calls follow solana-py's interface, and their argument names move between releases, so check them against the version you install.
  • A subscription has no history. It starts when it opens, and after a dropped socket you reconnect, subscribe again and read the accounts you care about once. getMultipleAccounts takes up to 100 pubkeys a call below Pro and 300 on Pro, at 10 cells each, and SPL token balance covers reading one balance.
  • getProgramAccountsV2 is not served here, so it gives no starting snapshot of a program's accounts.
  • The filters shown are the standard programSubscribe form. If Carbium declines a filter, the script prints the refusal with its code and message.
  • The script prints sizes and does not decode account layouts, which belong to each program.
  • A plain SOL wallet stays silent on accountSubscribe. For wallets, use logsSubscribe mentions plus getBalance.
07

When it goes wrong

what goes wrongwhat to do
The script prints refused: with a code and a message, and exits with 1.Read the message. A misspelt method name answers -32601, method not found, and a retry changes nothing. Check the method is programSubscribe with a capital S and the params are the program id followed by one config object.
The script prints 0 updates and exits with 1 after 20 seconds.The filters match nothing that changed in that time. Check that you passed the mint address itself, that the offset is 0 and that the size is 165. Run once with no mint to see any update, and expect a bigger stream.
The script prints socket error and exits with 1 before any reply.Check that CARBIUM_KEY holds the key itself and that CARBIUM_WS_URL, if you set it, is the wss:// WebSocket endpoint. An account that already holds all the sockets its tier allows (Free carries 5) can also be turned away, so close the idle ones.
Your Python code treats the first recv() as an account update and fails on it.The first message is the subscription confirmation with the id. Read the id from it, then loop over the notifications.
Python raises a TypeError from program_subscribe when a filter's bytes holds a Pubkey.Building MemcmpOpts does no type check, so the error comes up when program_subscribe serializes the filter. Build the byte match with MemcmpOpts(offset=0, bytes=str(mint)) from solana.rpc.types, and pass it in the same list as the integer size check.
Credits fall faster than the number of updates suggests.Each notification carries the full account data, and the charge is per MiB sent. Add the size and mint filters, and watch the byte total the script prints.
08

Questions

Can one socket carry several program subscriptions?

Yes. Send one programSubscribe per program and match each notification to its subscription id. Each one opens at its own 200 credits.

How do I stop a subscription?

Close the socket, which ends its subscriptions. The script closes the socket when it is done.

Why not an account subscription on every token account?

Each account subscription opens at 25 credits and covers one address. One program subscription with a mint filter covers every account of that mint, including ones created after you subscribe.

Can the key travel somewhere other than the URL?

Carbium also takes the key as the WebSocket subprotocol api-key.<YOUR_KEY>. The script uses ?api-key= on the URL, so keep that URL out of logs.