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

# Program failure webhook

One TypeScript file subscribes to a program's logs with logsSubscribe, keeps only the transactions whose err is set, and prints the signature, the error and the Anchor error code. It reads only: no keypair, no signing, no transaction sent.

## What the subscription sees

Most teams first look for failures by polling `getSignaturesForAddress` for the program and fetching each transaction. That works for a sweep of history, but it costs a request per signature and only answers when you ask. A subscription pushes each matching transaction to you once, as the node reports it.

`logsSubscribe` with a `mentions` filter sends one `logsNotification` for every transaction whose account list names the program. Each notification carries `signature`, `err` and `logs`. A transaction that failed still sends its logs, and `err` holds the reason, so a failure is any notification where `err` is not null. The watcher keeps those and drops the rest. The call in this file sets `confirmed` explicitly, so the level never depends on a default.

An alert is a notice that the node has seen the transaction, so `confirmed` is enough for most uses. If an alert must never name a transaction the chain later drops, pass `finalized` in the same call and accept the later message.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips TypeScript types on its own. The first argument is the program address and the second is how many seconds to watch, defaulting to 60. The file opens one WebSocket with the key in the `api-key` query parameter, sends `logsSubscribe` and prints each failed transaction. Kit checks the address, so a typo in the program id stops the file before it connects.

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

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

import { address } from '@solana/kit';

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error('Set CARBIUM_KEY to your Carbium API key.');
  process.exit(1);
}
const [programArg, secondsArg = '60'] = process.argv.slice(2);
const seconds = Number(secondsArg);
if (!programArg || !(seconds > 0)) {
  console.error('Usage: node main.ts <program-address> [seconds]');
  process.exit(1);
}
const program = address(programArg);
const url = new URL(process.env.CARBIUM_WS_URL ?? 'wss://services.carbium.sh');
url.searchParams.set('api-key', key);

let total = 0;
let failed = 0;
let stopped = false;

function describe(logs: string[]): string {
  const code = logs.find((line) => line.includes('Error Code:'));
  if (code) return code.replace('Program log: ', '');
  const failedLines = logs.filter((line) => line.includes('failed'));
  return failedLines.length > 0 ? failedLines[failedLines.length - 1] : 'no Anchor error line';
}

function connect(attempt: number): void {
  const ws = new WebSocket(url);
  ws.onopen = () => {
    console.log(`watching ${program} for ${seconds}s`);
    ws.send(JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'logsSubscribe',
      params: [{ mentions: [program] }, { commitment: 'confirmed' }],
    }));
  };
  ws.onmessage = (event) => {
    const msg = JSON.parse(String(event.data));
    if (msg.error) {
      console.error(`subscribe error: ${msg.error.message}`);
      return;
    }
    if (msg.method !== 'logsNotification') return;
    const { signature, err, logs } = msg.params.result.value;
    total++;
    if (err === null) return;
    failed++;
    console.log(`FAILED ${signature} ${JSON.stringify(err)} ${describe(logs)}`);
  };
  ws.onclose = () => {
    if (stopped) return;
    setTimeout(() => connect(attempt + 1), Math.min(1000 * 2 ** attempt, 10_000));
  };
}

connect(0);
setTimeout(() => {
  stopped = true;
  console.log(`done: ${total} transactions named the program, ${failed} failed`);
  process.exit(0);
}, seconds * 1000);
```

The socket closes when the connection goes idle or the network drops. The file then reconnects after a delay that doubles up to 10 seconds. A subscription made after a reconnect starts from that moment, so the gap in between is a blind spot, covered in the last section. Each failure is checked for an Anchor line: an `Error Code:` entry is printed when present, and otherwise the last log line containing `failed` is shown.

## Reading a failure

Each failed transaction prints one line. The fields come from different places in the message, so the table shows where each one sits.

| Field | Where it sits | Meaning |
|---|---|---|
| signature | value.signature | The transaction id. Use it as the key for de-duplication and for a `getTransaction` call. |
| err | value.err | The runtime's reason. Null for a success. Otherwise an object such as `InstructionError`, with the instruction index and the error. |
| Error Code | a program log line | Anchor's name for the error, such as `ConstraintMut`. |
| Error Number | the same log line | Anchor's number. Framework errors sit below 6000. Errors a program defines in its own error enum start at 6000. |
| logs | value.logs | Every program log in order, including inner calls. The runtime can cut a long log short, so the line you need may be missing. |

Anchor writes these lines only when the program returns an `AnchorError`. A program that panics, or that returns a plain Rust error, has no `Error Code:` line, and the fallback prints the last `failed` line instead. Read `err` first, since it is present for every failed transaction.

## Sending the alert on

The watcher prints to stdout, which is the right first step. To post each failure to a service you run, replace the `console.log` call with a `fetch` POST that carries the signature, the error and the program address. A receiver that answers slowly or with an error needs the retry rules in [webhook retries](https://carbium.sh/library/howsolana/webhook-to-rpc-fetch-retries).

Keep the signatures you have handled and skip any you see again. A retry, a second watcher or a restart can deliver the same failure twice, and the receiver should act on it once.

For delivery from Carbium's side to a URL you own, see [webhooks](https://carbium.sh/docs/webhooks). This file keeps the subscription in your process, so you can change the filter and the message without a server-side setup.

## What it costs on Carbium

A `logsSubscribe` with a `mentions` filter falls in the middle weight class: it costs 25 credits to open and 20 credits per MiB sent after that. A subscription the server refuses costs nothing. Credits meter WebSocket work alongside RPC, stream and webhook work, so a busy program costs more to watch than a quiet one.

The plan caps subscriptions and connections per account, and Free carries 5 sockets, so keep one watcher per program and close the ones you no longer run. [Limits](https://carbium.sh/docs/limits) apply per account, so every key on one account shares the same budget.

The key goes in the URL as `?api-key=`, as [auth](https://carbium.sh/docs/auth) sets out. The file builds that URL from the environment and never prints the key. Connections stay open for 600 seconds, so a watcher left running for hours reconnects whenever a socket closes. The socket address is listed under [endpoints](https://carbium.sh/docs/endpoints), and the subscription methods are described in the [WebSocket](https://carbium.sh/docs/websocket) reference.

## Where it ends

The subscription starts when it opens. A failure in the gap between a socket closing and its reconnect is never sent, and `logsSubscribe` does not replay it. If a gap matters, record the last signature you handled and look for newer ones with `getSignaturesForAddress` on the next start. That call reaches back 30 days at most on Carbium, because its address index keeps no more. An older gap needs another source.

The watcher reports a failure but not its full cause. For the complete account list, compute units and inner instructions, call `getTransaction` with `encoding: 'jsonParsed'` and `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and without that option the call answers -32015. Each `getTransaction` costs 50 cells, so fetch only the signatures you need to read and keep the watcher on the subscription alone.

A failure from a program called through another program appears in the same logs, so an alert can name the outer program while the failing instruction is inner. Only the fetch above shows which instruction failed. The count the file prints covers one socket only, and a second watcher on another host agrees with it only at the same commitment.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The file exits at once with `Usage: node main.ts <program-address> [seconds]`. | Pass a program address as the first argument, and a positive number of seconds as the second if you want one other than 60. |
| The socket closes straight after opening, and no notifications arrive. | Check that `CARBIUM_KEY` holds the whole key. An unknown key gets 401 at the door (UNKNOWN_KEY), so attach the whole key and try again. |
| The subscribe call returns an error message and nothing is printed for failures. | Refused subscriptions cost nothing. Check the socket count on your plan: Free carries 5 sockets per account, so close any watcher you no longer run before you open another. |
| A failure prints with `err` set, but its logs hold no `Error Code` line. | The program did not return an AnchorError, so the fallback shows its last failed line. Read `err` for the instruction index and the error, and fetch the transaction if you need the inner calls. |
| A failure from before a reconnect is missing from the output. | The socket was down and the subscription does not replay. Store the last signature you handled, then look for newer ones with `getSignaturesForAddress`, which reaches back 30 days at most. |
| A `getTransaction` call after an alert answers -32015. | Set `maxSupportedTransactionVersion` to 1 with an encoding. Mainnet carries v1 transactions, and an absent or 0 value answers -32015 for them. |

## Questions

### Can I catch failures without polling every signature?

Yes. A `logsSubscribe` with a `mentions` filter pushes each transaction that names the program, and a failed one carries an `err` value. Keep the notifications where `err` is set.

### Why does some alert show no error code?

Anchor writes an `Error Code:` line only for errors it raises itself. A panic or a plain Rust error reaches the logs as a `failed` line instead.

### Will a restart lose failures?

Yes, for the time the watcher was down, because the subscription does not replay. Store the last signature you handled and check the gap with `getSignaturesForAddress`, which reaches back 30 days at most.

### How many programs can one account watch?

The plan caps subscriptions and sockets per account, and Free carries 5 sockets. Each subscription costs credits to open, so one watcher per program is the usual shape.

## Related

- [Webhook-to-RPC fetch retries](https://carbium.sh/library/howsolana/webhook-to-rpc-fetch-retries) (How to use Solana, HS0041)
- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
- [carbium.sh/docs/webhooks](https://carbium.sh/docs/webhooks)
