---
id: BI0013
title: "On-chain event webhooks"
url: https://carbium.sh/library/blockchainideas/on-chain-event-webhooks
collection: Blockchain ideas
category: SaaS
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# On-chain event webhooks

A service that watches addresses for your customers and POSTs every transaction that mentions one to their URL, signed and retried. You get the tenant model, the delivery rules, the credit cost per address and a runnable main.ts.

## Who uses it

Product teams want to react to the chain and do not want to hold a socket open to do it. A wallet app needs a message when a deposit address is touched. A ticketing app needs one when a program it owns is called. A treasury tool needs one when a multisig signs. Each already handles an HTTP POST with queues, retries and logs.

The service sits between the chain and those apps. A customer registers an address and a callback URL. The service watches the address on one WebSocket and POSTs every transaction that mentions it, signed with that customer's secret and sent at least once.

A hackathon team can build the working core in one process with SQLite. The sample brings its own receiver, so a demo needs only a public address with traffic. For the single-address recipe, see [address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks). That recipe posts one address to one receiver, with no tenants, signing or retries.

## What a customer receives

Each delivery is one POST with a JSON body and three headers.

| Part | Rule |
|---|---|
| Registration | One row per tenant and address, holding the callback URL and a secret generated at sign-up. |
| Body | `address`, `slot`, `signature`, `ok`, `err` and the last five log lines. `ok` is true when `err` is null. |
| Signature | `x-signature: sha256=<hex>`, an HMAC-SHA256 of the raw body with the tenant's secret. |
| Idempotency | `idempotency-key` carries the transaction signature. Customers skip a signature they have seen. |
| Retries | Up to 4 attempts, with 1, 2 and 4 seconds between them, for a network error, a timeout, a 429 or a 5xx. Any other 4xx stops at once. |
| Ledger | One `deliveries` row per signature and tenant: pending, delivered or failed, with the attempt count. |

Delivery is at least once. If a customer's server answered but the 200 never arrived, the retry sends the same body under the same key, so the handler must be safe to run twice. Retries can reorder events, so the body carries `slot`.

## The build

The service is one file on what Node 24 ships: `node:sqlite`, `node:crypto`, `node:http`, the global `fetch` and `WebSocket`. It is read-only and holds no private key.

1. Open one WebSocket to `wss://services.carbium.sh` with the key as `?api-key=`.
2. Send `logsSubscribe` with `{ mentions: [address] }` at commitment `finalized`. The reply carries the subscription id, or an error if the subscription is refused, and a refusal is free.
3. On each `logsNotification`, build the body from `value.signature`, `value.err`, `value.logs` and `context.slot`.
4. For each tenant on the address, insert the pair (signature, hook) into `deliveries`. The insert changes a row only the first time, so a notification seen twice sends nothing twice.
5. Queue each delivery as its own async call with a 5 second timeout and run at most 20 at once, so a slow customer never blocks the socket and a busy address cannot flood the process. The queue lives in memory.
6. When the socket closes, print its close code and reason, wait 2 seconds and subscribe again.

With no second argument the sample seeds two tenants on the address and starts a receiver on loopback. Each POST that reaches it prints a `receiver:` line with the path and the signature header, and each finished call prints a `delivered` line with its attempt count. Pass a base URL as the second argument to post to your own endpoint, with `/acme` or `/globex` appended. Demo with an address that has steady but modest traffic: a program that most transactions touch streams far more than a demo receiver needs.

`main.ts` (run: `CARBIUM_KEY=<YOUR_KEY> node main.ts <address>`)

```ts
// BI0013 · On-chain event webhooks
// https://carbium.sh/library/blockchainideas/on-chain-event-webhooks
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { DatabaseSync } from "node:sqlite";
import { createHmac, randomUUID } from "node:crypto";
import { createServer } from "node:http";
type Hook = { id: number; url: string; secret: string };
const key = process.env.CARBIUM_KEY ?? "";
const watched = process.argv[2] ?? "";
if (!key || !watched) {
  console.error("Set CARBIUM_KEY and pass an address: node main.ts <address> [callback-base-url]");
  process.exit(1);
}
const WS_URL = `${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}/?api-key=${key}`;
const db = new DatabaseSync(process.env.DB ?? ":memory:");
db.exec(`
  CREATE TABLE IF NOT EXISTS hooks (id INTEGER PRIMARY KEY, tenant TEXT, address TEXT, url TEXT, secret TEXT, UNIQUE (tenant, address));
  CREATE TABLE IF NOT EXISTS deliveries (signature TEXT, hook INTEGER, status TEXT, attempts INTEGER, PRIMARY KEY (signature, hook));
`);
const claim = db.prepare("INSERT OR IGNORE INTO deliveries VALUES (?, ?, 'pending', 0)");
const finish = db.prepare("UPDATE deliveries SET status = ?, attempts = ? WHERE signature = ? AND hook = ?");
const hooksFor = db.prepare("SELECT id, url, secret FROM hooks WHERE address = ?");
// Signed POST. A network error, a 429 or a 5xx retries with backoff; any other 4xx stops at once.
async function deliver(hook: Hook, signature: string, body: string): Promise<void> {
  const mac = createHmac("sha256", hook.secret).update(body).digest("hex");
  for (let attempt = 1; ; attempt++) {
    let retry = true;
    try {
      const res = await fetch(hook.url, {
        method: "POST",
        headers: { "content-type": "application/json", "x-signature": `sha256=${mac}`, "idempotency-key": signature },
        body,
        signal: AbortSignal.timeout(5000),
      });
      if (res.ok) {
        finish.run("delivered", attempt, signature, hook.id);
        return console.log(`delivered ${signature.slice(0, 8)} to hook ${hook.id}, attempt ${attempt}`);
      }
      retry = res.status === 429 || res.status >= 500;
    } catch (e) {
      console.error(`hook ${hook.id} attempt ${attempt}: ${e instanceof Error ? e.message : e}`);
    }
    if (!retry || attempt === 4) {
      finish.run("failed", attempt, signature, hook.id);
      return console.log(`gave up ${signature.slice(0, 8)} for hook ${hook.id} after ${attempt}`);
    }
    await new Promise((r) => setTimeout(r, 1000 * 2 ** (attempt - 1)));
  }
}
// At most 20 deliveries run at once; the rest wait here, so a busy address cannot flood the event loop.
const waiting: (() => Promise<void>)[] = [];
let active = 0;
function pump(): void {
  while (active < 20 && waiting.length) {
    active++; void waiting.shift()!().finally(() => { active--; pump(); });
  }
}
function connect(): void {
  const ws = new WebSocket(WS_URL);
  ws.onopen = () => ws.send(JSON.stringify({
    jsonrpc: "2.0", id: 1, method: "logsSubscribe",
    params: [{ mentions: [watched] }, { commitment: "finalized" }],
  }));
  ws.onmessage = (ev) => {
    const msg = JSON.parse(String(ev.data));
    if (msg.id === 1) return console.log(msg.error ? `subscribe refused: ${msg.error.message}` : `subscribed, id ${msg.result}`);
    if (msg.method !== "logsNotification") return;
    const { context, value } = msg.params.result;
    const body = JSON.stringify({
      address: watched, slot: context.slot, signature: value.signature,
      ok: value.err === null, err: value.err, logs: (value.logs ?? []).slice(-5),
    });
    for (const h of hooksFor.all(watched) as unknown as Hook[]) {
      if (Number(claim.run(value.signature, h.id).changes) === 1) { waiting.push(() => deliver(h, value.signature, body)); pump(); }
    }
  };
  ws.onclose = (ev) => { console.error(`socket closed ${ev.code} ${ev.reason}`); setTimeout(connect, 2000); };
  ws.onerror = () => ws.close();
}
function start(base: string): void {
  const seed = db.prepare("INSERT INTO hooks (tenant, address, url, secret) VALUES (?, ?, ?, ?) ON CONFLICT (tenant, address) DO UPDATE SET url = excluded.url");
  for (const tenant of ["acme", "globex"]) seed.run(tenant, watched, `${base}/${tenant}`, randomUUID());
  connect();
}
const base = process.argv[3];
if (base) start(base);
else {
  // Demo receiver on loopback so one run shows the whole path; a real tenant brings its own URL.
  const receiver = createServer((req, res) => { console.log(`receiver: POST ${req.url} ${req.headers["x-signature"]}`); res.end("ok"); });
  receiver.listen(0, "127.0.0.1", () => start(`http://127.0.0.1:${(receiver.address() as { port: number }).port}`));
}
```

A webhook cannot be unsent, and `finalized` is the level that never rolls back, so the subscription asks for it. Since the Alpenglow switch on mainnet (2026-10-21) a slot is about 200 ms and finalized sits 0 to 1 slots behind processed, so the wait is short.

## What it costs

The read side is billed in credits per subscription. A logs-mentions subscription opens at 25 credits, then costs 20 credits per MiB sent, and every notification that mentions the address counts. Delivery runs from your process to your customers' URLs and draws nothing from Carbium.

The table below assumes 2 KiB per notification, so sum the real message bytes in the first hour and rescale. It covers one subscription, traffic only. The 25 credits to open come once, and again whenever a reconnect subscribes anew.

| Mentions per second | MiB per hour | Credits per hour |
|---|---|---|
| 0.1 | 0.70 | 14 |
| 1 | 7.03 | 141 |
| 10 | 70.3 | 1,406 |
| 100 | 703 | 14,063 |

Now size a product: 100 customers, each watching a different address at 0.1 mentions per second. That is 100 subscriptions, 70.3 MiB an hour, 1,406 credits an hour and about 1.01M credits over 30 days.

| Plan | Credits | Backfill rate | That load over 30 days |
|---|---|---|---|
| Free ($0) | 500K once, at sign-up | 0.24 req/s | about 2 times the grant |
| Dev ($20) | 10M per month | 1.2 req/s | about 10% of the month |
| Business ($250) | 50M per month | 100 req/s | about 2% of the month |
| Pro ($500) | 200M per month | 500 req/s | about 0.5% of the month |

Backfill rate is the plan's `getSignaturesForAddress` ceiling, at 50 cells a call. Limits are per account, so other tools on your keys draw on the same budget. Free carries 5 sockets and the service uses one. Subscription counts are capped per account by tier, so check that cap against your customer count.

> A backfill loop that gets a 429 should honor its retry-after hint. [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) shows how to watch for them.

## What to add next

- Many addresses: loop over `SELECT DISTINCT address FROM hooks`, send one `logsSubscribe` each and map each subscription id in the reply to its address.
- Restart backfill: store the last signature per address. On start, call `getSignaturesForAddress` with `until` set to it and commitment `finalized`, then deliver what was missed, oldest first. That call returns `err` and no logs, so read each signature with `getTransaction` at `finalized` to fill `logs`, or the body goes out with an empty `logs` field. Pass `maxSupportedTransactionVersion: 1` with an encoding, or the call answers -32015 for a v1 transaction. It can also answer null for a listed signature below the ledger floor, so the backfill has to handle null. Both calls go to `https://services.carbium.sh` with the key in `x-api-key`.
- Stored bodies: keep the JSON in `deliveries`, so pending rows resend after a crash.
- A circuit breaker: pause a callback after a run of failures and show its state on a tenant page with a Replay button.

## Where it ends

- A delivery says a transaction mentioned the address. It does not say what moved. A transfer, a swap and a failed instruction arrive the same way, with `ok` and the last five log lines.
- `logsSubscribe` takes one mention per subscription and has no failed-only filter, so credits cover every notification.
- A plain SOL wallet stays silent on `accountSubscribe`. Use the logs mention, then read the balance with `getBalance` after the event.
- Only transactions that landed produce logs. One rejected in preflight, or whose blockhash expired, never appears.
- Delivery is at least once and can arrive out of order. Customers dedupe on `idempotency-key` and sort on `slot`.
- The stream does not replay what you missed while your process was down. A backfill reaches back 30 days at most, because `getSignaturesForAddress` pages come from Carbium's own address index. An empty page past that is the index's age limit and says nothing about the address's first transaction.
- A busy program as a tenant address streams all of its traffic at your cost. Cap or refuse those registrations.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The subscribe reply is an error, or the socket closes at once. | Check CARBIUM_KEY and that the account is under its socket cap, which is 5 on Free. The close code and reason print before each reconnect. A refused subscription is free, so a retry costs nothing. |
| A customer reports the same event twice. | A lost 200 triggers a retry with the same body. Tell customers to dedupe on `idempotency-key`. |
| A customer's signature check fails. | The HMAC covers the raw body bytes. If their server parses the JSON and writes it out again, the bytes change. Verify against the raw request body. |
| One slow endpoint keeps deliveries waiting. | Each delivery times out at 5 seconds and stops after 4 attempts, so one dead endpoint holds one of the 20 slots for about 27 seconds. Add a circuit breaker for repeat offenders. |
| Credits drop by more than the table says. | Sum the received bytes. A program id as the address streams every call to that program. Register a narrower address or refuse the registration. |

## Questions

### Why subscribe at finalized and not confirmed?

Customers act on a delivery and a delivery cannot be recalled, so the signal should come from a slot that can no longer be dropped. The wait for it is small. Change the commitment string if a customer wants the earlier signal.

### Does one socket serve all my customers?

One socket carries one subscription per distinct address, and tenants on the same address share it. Free carries 5 sockets, and subscription counts are capped per account by tier, so check the cap in the [WebSocket docs](https://carbium.sh/docs#websocket).

### Does delivery cost Carbium credits?

No. Credits go to the subscription, 25 to open and 20 per MiB sent; a backfill call also weighs 50 cells against your req/s ceiling.

### What survives a restart?

Set `DB` to a file and the `deliveries` ledger survives, so signatures already sent are not sent again. The sample does not store pending bodies, and events during the downtime need the restart backfill.

### Can I watch a plain wallet for incoming SOL?

Yes, with a logs mention on the wallet address, since a transfer lists it among the transaction's accounts. `accountSubscribe` stays silent for a plain SOL wallet, so read the balance with `getBalance` after the event. [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) covers token accounts.

## Related

- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) (How to use Solana, HS0018)
- [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)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
