---
id: I0031
title: "Anchor events to NATS"
url: https://carbium.sh/library/integrate/anchor-events-to-nats
collection: Integrations
category: Queues and streams
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Anchor events to NATS

A Node relay that subscribes to an Anchor program's logs on Carbium's WebSocket, reads each event's discriminator and publishes the event as JSON to a NATS subject. It needs only Node 24 and runs without a NATS server, printing what it would publish.

## What the relay does

The relay is one Node file with no dependency beyond Node 24. It opens a WebSocket to Carbium, subscribes to the logs of transactions that mention one Anchor program, picks out the events that program emitted and publishes each as a message on a NATS subject. A consumer anywhere on your NATS network subscribes to `anchor.<program>.<event>` and receives every event as JSON.

Carbium has two doors for live data. The [WebSocket](https://carbium.sh/docs#websocket) carries `logsSubscribe`, which the relay uses. The [gRPC stream](https://carbium.sh/docs#stream) sits at `https://services.carbium.sh:9443`, takes the key in an `x-token` header and opens on Dev, Business and Pro; Free plans have no stream. The relay stays on the WebSocket, so the same file runs on any plan.

| Part | Job |
|---|---|
| Carbium socket | `logsSubscribe` with a `mentions` filter at confirmed commitment: one frame per transaction that lists the program. |
| Filter in code | Drops failed transactions and keeps a `Program data:` line only while the watched program is the one running. |
| Publisher | Writes `PUB` frames to a NATS server over a plain TCP socket, or prints them when `NATS_URL` is unset. |

## The Anchor side: events in the logs

An Anchor program's `emit!` writes the event through the `sol_log_data` syscall, so it shows in the transaction logs as `Program data: <base64>`. The first 8 bytes are the event discriminator, the first 8 bytes of the SHA-256 of `event:` plus the event name. The rest is the Borsh-encoded fields.

A log holds lines from every program in the call tree, and a `Program data:` line does not say who wrote it. The relay follows the stack through the `Program <id> invoke [n]` lines and the matching `success` or `failed` lines, and keeps a data line only when the watched program is on top. A swap routed through another program that calls into yours gives you your events and none of the caller's.

A transaction that failed rolls its state back, and its logs can still hold event lines from before the failure. The relay skips every notification whose `err` is set.

Set `EVENT_NAMES` to the event names from the program's IDL, for example `Deposit,Withdraw`, and the relay computes each discriminator and puts the name in the subject. Names are case sensitive. An event you did not list keeps its discriminator in hex, so nothing is dropped while you collect names.

## The NATS side: one subject per event

Core NATS speaks a short text protocol. The client sends `CONNECT` with a JSON options object, then `PUB <subject> <byte count>` followed by the payload, each ending in CRLF, and answers `PING` with `PONG`. The relay writes those frames on a `node:net` socket, which keeps the file free of a client library. If you already run one in production, replace the `publish` function and nothing else changes.

The subject is `anchor.<program>.<event>`. NATS splits subjects at dots, so `anchor.>` matches every event from every relayed program and `anchor.<program>.Deposit` matches one. The payload carries the slot, the signature, the event's position in the transaction, the program, the event name, the discriminator and the field bytes as base64.

Core NATS hands a message to the subscribers connected at that moment and keeps nothing. To store events, create a JetStream stream on `anchor.>` on the server. The relay publishes the same frames either way.

## The relay

Run it with Node 24, which strips the types on load, so there is no install step. `CARBIUM_KEY` is required and the program id is the first argument; with none given it watches the Whirlpools program. `CARBIUM_WS_URL`, `NATS_URL` (for example `nats://127.0.0.1:4222`) and `EVENT_NAMES` are optional.

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

```ts
// I0031 · Anchor events to NATS
// https://carbium.sh/library/integrate/anchor-events-to-nats
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createHash } from "node:crypto";
import { connect } from "node:net";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const program = process.argv[2] ?? "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";

// An Anchor event starts with sha256("event:<Name>")[0..8]; map the names you know.
const names = new Map<string, string>();
for (const n of (process.env.EVENT_NAMES ?? "").split(",").filter(Boolean)) {
  names.set(createHash("sha256").update(`event:${n}`).digest().subarray(0, 8).toString("hex"), n);
}

// NATS core is a text protocol: CONNECT, PUB, and PONG for every PING.
const natsUrl = process.env.NATS_URL ? new URL(process.env.NATS_URL) : null;
const nats = natsUrl ? connect({ host: natsUrl.hostname, port: Number(natsUrl.port || 4222) }) : null;
// The socket queues writes in order, so CONNECT reaches the server before any PUB.
nats?.write('CONNECT {"verbose":false,"name":"anchor-events"}\r\n');
nats?.on("data", (d) => {
  if (d.includes("PING\r\n")) nats?.write("PONG\r\n");
});
nats?.on("error", (e) => console.error("nats error:", e.message));
nats?.on("close", () => {
  console.error("nats closed");
  process.exit(1);
});

function publish(subject: string, body: object) {
  const json = JSON.stringify(body);
  if (nats) nats.write(`PUB ${subject} ${Buffer.byteLength(json)}\r\n${json}\r\n`);
  else console.log(subject, json);
}

const ws = new WebSocket(`${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}?api-key=${key}`);
ws.addEventListener("open", () => {
  const params = [{ mentions: [program] }, { commitment: "confirmed" }];
  ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params }));
  console.log(`listening for events from ${program}`);
});
ws.addEventListener("error", () => console.error("socket error"));
ws.addEventListener("close", () => {
  console.error("socket closed");
  process.exit(1);
});
ws.addEventListener("message", (m) => {
  const msg = JSON.parse(String(m.data));
  if (msg.error) {
    console.error("subscribe failed:", msg.error.message);
    process.exit(1);
  }
  if (msg.method !== "logsNotification") return;
  const { context, value } = msg.params.result;
  if (value.err) return; // a failed transaction rolled its events back
  const stack: string[] = []; // which program is running, from the invoke / success lines
  let index = 0;
  for (const line of value.logs as string[]) {
    const call = /^Program (\w+) invoke \[/.exec(line);
    if (call) stack.push(call[1]);
    else if (/^Program \w+ (success|failed)/.test(line)) stack.pop();
    else if (line.startsWith("Program data: ") && stack.at(-1) === program) {
      const raw = Buffer.from(line.slice(14).split(" ")[0], "base64");
      if (raw.length < 8) continue;
      const discriminator = raw.subarray(0, 8).toString("hex");
      const event = names.get(discriminator) ?? discriminator;
      const data = raw.subarray(8).toString("base64");
      publish(`anchor.${program}.${event}`, { slot: context.slot, signature: value.signature, index: index++, program, event, discriminator, data });
    }
  }
});
```

The socket carries the [key](https://carbium.sh/docs#auth) as `?api-key=` on the URL, and the code never prints that URL.

## Run it and read the stream

With `NATS_URL` unset, `node main.ts <program id>` prints a line per event, subject first and the JSON after it. That shows the filter and the discriminator work before a server is involved. With the variable set, run `nats sub 'anchor.>'` from the NATS command line tool on any machine that reaches the server to watch the same messages arrive.

The process exits with code 1 when the Carbium socket closes, when NATS closes or when the subscribe call is refused. Run it under a supervisor such as a systemd unit with a restart delay, and the exit becomes a reconnect. A quiet program prints only the first line until it emits an event.

## What it costs against your limits

A subscription on logs with a `mentions` filter [opens at 25 credits](https://carbium.sh/docs#limits), then costs 20 credits per MiB sent. The filter matches transactions that mention the program, and the relay discards the lines it does not want after they arrive, so a busy program sends you every transaction it touches, events or not. Watch the credit balance for the first hour on a new program before you trust the rate.

Your plan caps sockets and subscriptions per account, and Free carries 5 sockets. The relay holds one socket and one subscription per program, so a second program means a second process.

## Where it ends

- It reads logs only. An event written with `emit_cpi!` travels as data on a self-call instruction and writes no log line, so this relay never sees it.
- It does not decode fields. The payload holds the raw bytes after the discriminator, and your consumer applies the IDL layout. The [Anchor instruction decoder](https://carbium.sh/library/howsolana/anchor-instruction-decoder) shows the same idea for instructions.
- Events arrive at confirmed commitment. Each message carries the signature and an index, so a consumer can drop repeats by that pair.
- A socket that drops loses what was emitted until the restart. Backfill from `getSignaturesForAddress` on the program, which reaches back 30 days at most, and read each transaction with `getTransaction`.
- The runtime stops recording a transaction's logs past a size limit and adds `Log truncated`. Events after that line are not in the logs.
- The NATS connection has no TLS and no credentials. Point it at a server on a private network, or put a proxy in front.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The socket closes right after start and the log shows `socket closed` with no events. | Check that `CARBIUM_KEY` holds the whole key. An unknown key is refused at the door with 401, and the socket never subscribes. Also check that `CARBIUM_WS_URL`, if set, is the WebSocket address. |
| The relay prints `listening` and nothing else for minutes on a busy program. | The program may not write events through `emit!`, or it may use `emit_cpi!`, which leaves no log line. Read a recent transaction with `getTransaction`, using `maxSupportedTransactionVersion: 1`, and look for `Program data:` in `logMessages`. Confirm the program id too. |
| Subjects end in 16 hex characters where the event name belongs. | `EVENT_NAMES` has no entry that hashes to that discriminator. Copy the names from the IDL with the same capitals, comma separated and without spaces. |
| The log shows `nats closed` and the process exits. | The server refused the connection, asked for credentials or TLS, or `NATS_URL` has the wrong host or port. The relay speaks plain TCP with no login. Test with the NATS command line tool from the same machine. |
| Consumers see the same event twice after a restart. | Backfill and live delivery can overlap. Drop repeats on the pair of `signature` and `index`, which is unique per event. |
| Credits fall faster than expected. | The subscription sends every transaction that mentions the program, at 20 credits per MiB. The cost follows the program's whole transaction volume, so budget by that volume. |

## Questions

### Does Carbium support Geyser for events?

The gRPC stream at port 9443 opens on Dev, Business and Pro. This relay uses `logsSubscribe` on the WebSocket instead, which works on Free and carries the log lines Anchor events live in.

### Do I need the program's IDL?

Not to relay. The discriminator needs only the event names, and `EVENT_NAMES` takes them. You need the IDL in the consumer to read the fields.

### Can I run it with no NATS server?

Yes. Leave `NATS_URL` unset and the relay prints each subject and payload to the terminal, which is how to check a program before you wire a server.

### Why subscribe at confirmed commitment?

Confirmed is the explicit choice in the code. The signature in each message lets a consumer check finality later with `getSignatureStatuses`.

### Can one relay watch several programs?

Each subscription takes one address in its filter. Run one process per program, and keep the count under your plan's socket cap.

## Related

- [On-chain event webhooks](https://carbium.sh/library/blockchainideas/on-chain-event-webhooks) (Blockchain ideas, BI0013)
- [Python program subscriptions](https://carbium.sh/library/integrate/python-program-subscriptions) (Integrations, I0005)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#stream](https://carbium.sh/docs#stream)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
