---
id: HS0018
title: "Address transaction webhooks"
url: https://carbium.sh/library/howsolana/address-transaction-webhooks
collection: How to use Solana
category: Webhooks
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Address transaction webhooks

One TypeScript file subscribes to transactions that mention your addresses over Carbium's WebSocket, then POSTs each one as HMAC-signed JSON to your server. It retries failed deliveries and refills a gap after a reconnect. It only reads the chain and never signs.

## The job

A webhook is an HTTP POST that your server receives when something happens. On Solana the something is a transaction that touches one of your addresses: a deposit lands, or a program you run gets called. Your server should be told about it instead of polling for it.

Carbium serves the event feed on its WebSocket plane. `logsSubscribe` streams transaction logs, all of them or only the ones that mention an address. The relay opens that subscription for each address you pass and turns every notification into a POST with a signed body, sent to the URL you choose. It runs on a machine you control, and the receiver is any HTTPS endpoint.

The file holds no keypair, signs no transaction and sends none. The one secret in play is your Carbium key, and it comes from the environment.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips TypeScript types on load. Pass one or more addresses as arguments. With `WEBHOOK_URL` and `WEBHOOK_SECRET` set, each event goes to your server. Without them the file starts a small receiver on 127.0.0.1 and posts to itself, so one run shows the whole path. To see events at once, first point it at a busy public address such as the USDC mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`, then switch to your own.

`main.ts` (run: `node main.ts <address> [address...]`)

```ts
// HS0018 · Address transaction webhooks
// https://carbium.sh/library/howsolana/address-transaction-webhooks
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
import { setTimeout as sleep } from "node:timers/promises";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
const watched = process.argv.slice(2);
if (!key || !watched.length || (process.env.WEBHOOK_URL && !process.env.WEBHOOK_SECRET)) {
  console.error("Set CARBIUM_KEY and pass addresses: node main.ts <address>... (WEBHOOK_URL needs WEBHOOK_SECRET)");
  process.exit(1);
}
const secret = process.env.WEBHOOK_SECRET ?? randomBytes(16).toString("hex");
const sign = (body: string) => createHmac("sha256", secret).update(body).digest("hex");
type Hit = { address: string; signature: string; slot: number; err: unknown; logs?: string[] };

// Stand-in receiver for a run without WEBHOOK_URL. It checks the signature the way your server should.
async function demoReceiver() {
  const server = createServer((req, res) => {
    let body = "";
    req.on("data", (c) => (body += c));
    req.on("end", () => {
      const got = Buffer.from(String(req.headers["x-signature"])), want = Buffer.from(sign(body));
      const ok = got.length === want.length && timingSafeEqual(got, want);
      res.writeHead(ok ? 204 : 401).end();
      if (ok) { const h: Hit = JSON.parse(body); console.log(`received ${h.signature} slot=${h.slot} err=${JSON.stringify(h.err)} for ${h.address}`); }
    });
  });
  await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
  return `http://127.0.0.1:${(server.address() as { port: number }).port}`;
}
const hook = process.env.WEBHOOK_URL ?? (await demoReceiver());

const seen = new Set<string>();
const last = new Map<string, string>();
async function deliver(hit: Hit) {
  const id = `${hit.address}:${hit.signature}`;
  if (seen.has(id)) return;
  seen.add(id);
  const body = JSON.stringify(hit);
  for (let attempt = 0; attempt < 4; attempt++) {
    try {
      const r = await fetch(hook, { method: "POST", headers: { "content-type": "application/json", "x-signature": sign(body) }, body });
      if (r.ok) return;
      console.error(`hook answered ${r.status}`);
    } catch (e) {
      console.error(`hook unreachable: ${(e as Error).message}`);
    }
    await sleep(500 * 2 ** attempt);
  }
  console.error(`gave up on ${hit.signature}`);
}

const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }));
async function catchUp(a: string) { // after a reconnect: what the dead socket missed, oldest first
  const since = last.get(a);
  if (!since) return;
  const missed = await rpc.getSignaturesForAddress(address(a), { until: signature(since), limit: 100, commitment: "confirmed" }).send();
  for (const m of [...missed].reverse()) await deliver({ address: a, signature: m.signature, slot: Number(m.slot), err: m.err });
}

const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);
function connect() {
  const ws = new WebSocket(wsUrl);
  const names = new Map<number, string>(); // subscription id -> watched address
  ws.addEventListener("open", () => watched.forEach((a, i) => ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 1, method: "logsSubscribe", params: [{ mentions: [a] }, { commitment: "confirmed" }] }))));
  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") {
      const a = names.get(msg.params.subscription) as string;
      const { context, value } = msg.params.result;
      last.set(a, value.signature);
      void deliver({ address: a, signature: value.signature, slot: context.slot, err: value.err, logs: value.logs });
    } else if (typeof msg.result === "number") {
      const a = watched[msg.id - 1] as string;
      names.set(msg.result, a);
      console.log(`watching ${a}`);
      catchUp(a).catch((e) => console.error(`catch-up failed: ${e.message}`));
    }
  });
  ws.addEventListener("close", () => { console.error("socket closed, reconnecting"); setTimeout(connect, 2000); });
}
connect();
```

The subscription sends `logsSubscribe` with `mentions` set to one address, once per address, because the filter takes a single address. The notification gives the signature, the slot, `err` and the log lines, and the file posts those with the address attached. `deliver` signs the exact body bytes with HMAC SHA256, sends the hex digest in `x-signature`, and tries up to four times with a doubling pause when the server answers anything but 2xx or cannot be reached. `catchUp` calls `getSignaturesForAddress` with `until` set to the last signature the socket delivered, so a reconnect fetches what the dead socket missed. A set of `address:signature` keys drops the duplicates where the live feed and the catch-up overlap.

## What your server receives

| Part | Value |
|---|---|
| address | The watched address that the transaction mentions. |
| signature | The transaction signature as base58 text. On its own it is the idempotency key for one transaction. |
| slot | The slot the transaction was seen in, as a number. |
| err | null when the transaction succeeded, an error object when it failed. |
| logs | The program log lines as an array of strings. Events filled in by the catch-up carry none. |
| x-signature header | Hex HMAC SHA256 of the raw body, keyed with your secret. |

Verify before you parse. Compute the HMAC over the raw bytes you received, compare it with `timingSafeEqual` and answer 401 on a mismatch. Parsing the JSON and serialising it again changes the bytes and breaks the match. Answer with any 2xx status once the event is stored. The relay treats every other status as a failure and tries again, so the handler has to be safe to run twice for one signature.

> A transaction that fails on chain still produces a notification, with `err` set. Filter on it in your handler if you only want the ones that succeeded.

## On Carbium

The WebSocket endpoint is `wss://services.carbium.sh`. The key rides in the URL as `?api-key=`, so the file builds the URL with `searchParams` and never prints it. The one RPC call goes to `https://services.carbium.sh`, and the [key](https://carbium.sh/docs#auth) travels in the `x-api-key` header.

A `logsSubscribe` with `mentions` opens at 25 credits, then costs 20 credits per MiB sent. A refused subscription is free. Free carries 5 sockets, and connection and subscription counts are [capped per account](https://carbium.sh/docs#limits) by tier. An account's keys share one budget. The file opens one socket with one subscription per address.

Watch addresses that belong to you. A popular mint is mentioned by many transactions, and every notification counts toward the 20 credits per MiB.

`getSignaturesForAddress` costs 50 cells, and Free, Dev, Business and Pro allow 0.24, 1.2, 100 and 500 calls per second. It is the only [RPC](https://carbium.sh/docs#rpc) call the file makes, and it runs once per address after a reconnect.

## Where it ends

Delivery can repeat an event, can lose one, and keeps no order. A retry of one event can land after the next event. Dedupe on the signature, and sort by `slot` when order matters.

The relay keeps its state in memory. `last` and `seen` vanish when the process exits, so a restart begins at now and misses whatever happened while it was down. To close that gap, store the last signature per address in `node:sqlite` and fill `last` from it at start. `catchUp` then does the rest.

The catch-up reads up to 100 signatures from Carbium's own address index, which keeps up to 30 days. An outage that produced more than 100 transactions for one address leaves a hole. Page with `before` for a longer gap. An empty page past 30 days is the index's age limit and says nothing about where the address began. Older history is not served.

The payload has no amounts. A log line says which program ran and whether it succeeded. For a plain SOL wallet it is also the only live signal, because `accountSubscribe` stays silent for one. To read amounts, call `getTransaction` on the signature from your handler with `maxSupportedTransactionVersion: 1` and an encoding, because mainnet carries v1 transactions and the call returns an error without it. It costs 50 cells.

A receiver that stays down for more than a few seconds loses events. After four tries the relay logs the signature and drops the event. If your server is not always up, write each event to a table first and post from there.

## When it goes wrong

| What goes wrong | What 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 tier. Free carries 5 sockets, and a refused subscription costs no credits. Close an idle socket or move to a plan with a higher cap, then restart. |
| The receiver answers 401 to every event. | The two sides disagree on the secret or on the bytes. Set the same `WEBHOOK_SECRET` on both, and hash the raw request body, never a parsed and re-serialised copy. |
| `hook unreachable` or `hook answered 500`, then `gave up on` a signature. | The relay tried four times, with 7.5 seconds of pauses in all, and dropped the event. Bring the receiver back, then read the missed signatures with `getSignaturesForAddress`. For a receiver that is often down, write events to a table first and post from there. |
| `socket closed, reconnecting` repeating every 2 seconds. | Check `CARBIUM_KEY` and that the account is under its socket cap. If the handshake is turned down, the socket never opens and the loop retries forever. Add a growing pause or a retry limit before you run the file unattended. |
| `catch-up failed` with HTTP 429. | `getSignaturesForAddress` costs 50 cells, and Free allows 0.24 calls per second, so a call over that rate gets 429 with a retry-after hint. Wait that long and call again. The file reports the failure and does not retry it. |
| The same transaction reaches your server twice. | A transaction that mentions two watched addresses is posted once per address, because the dedupe key is the address and the signature together. A retry whose first attempt arrived but whose answer was lost also repeats it. Dedupe on the signature alone when you want one event per transaction. |

## Questions

### Does a failed transaction fire the webhook?

Yes. The notification carries `err`, which is null for a success and an object for a failure. Filter on it in your handler.

### How many addresses can one relay watch?

The limit is your tier's subscription cap. The relay opens one socket with one subscription per address, each at 25 credits, so it uses only one of Free's 5 sockets.

### Why logs instead of account changes?

`accountSubscribe` stays silent for a plain SOL wallet. `logsSubscribe` with `mentions` reports every transaction that names the address, and `getBalance` gives you the SOL amount when you need it.

### How do I get the amount that moved?

Call `getTransaction` on the signature from your handler with `maxSupportedTransactionVersion: 1` and an encoding, then compare the pre and post balances. Without that value the call returns an error for a v1 transaction. It costs 50 cells, so do it only for the events you act on.

## Related

- [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) (Integrations, I0001)
- [Failed-mint monitor](https://carbium.sh/library/blockchainideas/failed-mint-monitor) (Blockchain ideas, BI0001)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
