---
id: SI0023
title: "Event-driven agent loop"
url: https://carbium.sh/library/si/event-driven-agent-loop
collection: AI and blockchain
category: General agent frameworks
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Event-driven agent loop

A Node loop that sleeps until a Solana program's log notification arrives, picks the event worth a look, reads that transaction, and goes back to sleep. A rule decides today, and the file marks the step where a model call fits.

## Why an agent loop waits on events

An agent loop has three steps: observe, decide, act. The usual way to run it is a timer. Every few seconds the agent asks the chain what changed, and on a quiet address nearly every question returns the same answer. Each question costs cells at the door, and the agent reacts half a timer interval late on average and a full interval late at worst.

An event-driven loop removes the timer. The process holds one WebSocket open, the node pushes a notification when a transaction mentions the address, and the loop wakes only then. Between events it sleeps on a promise and does nothing. The read calls are spent on transactions that happened.

The shape matters most when the decide step is slow. A model call takes seconds, and the chain keeps producing while it thinks. A loop that handles events one by one in arrival order falls further behind on a busy program. The loop in this file takes everything that arrived during the last step as one batch, looks at it once and acts on one item.

## The loop file

One file: Node 24 runs the TypeScript directly, `@solana/kit` 8.6.0 makes the RPC calls, and the global `WebSocket` carries the feed. Set `CARBIUM_KEY` and pass a program address, plus an optional step count that defaults to 5. `CARBIUM_RPC_URL` and `CARBIUM_WS_URL` override the two endpoints, which default to `https://services.carbium.sh` and `wss://services.carbium.sh`. `GAP_MS` sets the pause after each read and defaults to 4500.

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

```ts
// SI0023 · Event-driven agent loop
// https://carbium.sh/library/si/event-driven-agent-loop
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Event-driven agent loop, read only. Run: CARBIUM_KEY=... node main.ts <program address> [steps]
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";

const key = process.env.CARBIUM_KEY ?? "";
const target = process.argv[2];
const steps = Number(process.argv[3] ?? 5);
if (!key || !target) {
  console.error("Set CARBIUM_KEY to your Carbium API key and pass a program address.");
  process.exit(1);
}
const program = address(target);
const gapMs = Number(process.env.GAP_MS ?? 4500);
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);

type Seen = { slot: number; signature: string; failed: boolean };
let pending: Seen[] = [];
let dropped = 0;
let wake: (() => void) | undefined;
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

// The one function a model call would replace: batch in, one event to read out.
function decide(batch: Seen[]): { pick: Seen; skipped: number } {
  let pick = batch[batch.length - 1];
  for (let i = batch.length - 1; i >= 0; i--) if (batch[i].failed) { pick = batch[i]; break; }
  return { pick, skipped: batch.length - 1 };
}

async function act(e: Seen): Promise<string> {
  const tx = await rpc
    .getTransaction(signature(e.signature), {
      commitment: "confirmed",
      encoding: "json",
      maxSupportedTransactionVersion: 1,
    })
    .send();
  if (!tx) return "no transaction body yet";
  const units = tx.meta?.computeUnitsConsumed ?? "unknown";
  return `fee ${tx.meta?.fee} lamports, ${units} compute units, ${tx.transaction.message.instructions.length} instructions`;
}

const ws = new WebSocket(wsUrl);
ws.addEventListener("open", () => {
  const params = [{ mentions: [program] }, { commitment: "confirmed" }];
  ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params }));
});
ws.addEventListener("message", (event) => {
  const msg = JSON.parse(String(event.data));
  if (msg.error) {
    console.error("subscription refused:", msg.error.message);
    process.exit(1);
  }
  if (typeof msg.result === "number") console.log("subscribed");
  const result = msg.params?.result;
  if (!result?.value) return;
  pending.push({ slot: result.context.slot, signature: result.value.signature, failed: result.value.err !== null });
  if (pending.length > 200) { pending.shift(); dropped++; }
  wake?.(); wake = undefined;
});
ws.addEventListener("close", () => {
  console.error("socket closed, exiting so a supervisor restarts the loop");
  process.exit(1);
});

for (let step = 1; step <= steps; step++) {
  while (pending.length === 0) {
    await new Promise<void>((resolve) => {
      wake = resolve;
    });
  }
  const batch = pending;
  pending = [];
  const { pick, skipped } = decide(batch);
  const head = `step ${step} slot ${pick.slot} ${pick.signature.slice(0, 12)}${pick.failed ? " failed" : ""} skipped ${skipped}`;
  try {
    console.log(`${head}: ${await act(pick)}`);
  } catch (e) {
    console.error(`${head}: read failed:`, (e as Error).message);
  }
  if (step < steps) await sleep(gapMs);
}
console.log(`done, ${dropped} events dropped`);
process.exit(0);
```

The socket handler only appends to `pending` and wakes the loop. It does no reading, so a slow call never holds up the feed. The loop takes `pending` whole, hands it to `decide`, and gets back one event to read and a count of the others it skipped. `act` makes the one `getTransaction` call. After the pause the loop goes round again, and the events that arrived during the pause form the next batch. `pending` is capped at 200, and the oldest events fall off first.

`decide` is a rule: a failed transaction wins, otherwise the newest event does. When a batch holds several failures, a scan from the end picks the newest of them. Failed transactions are the ones an operator usually wants explained, and the newest event is the freshest view of what the program is doing now. The rule is plain code so the loop needs nothing beyond Carbium.

## What the loop prints

| Line | Meaning | What to do |
|---|---|---|
| `subscribed` | The node accepted the `logsSubscribe` request. | Nothing. Events follow if the program is active. |
| `step 2 slot 472447594 5Kq... skipped 9: fee 5000 lamports, ...` | The loop read one transaction and passed over nine others from that batch. | Compare the skipped count with your plan's read rate. |
| `failed` after the signature | The chosen event carried an error, so the rule picked it first. | Open the transaction and find the failing instruction. |
| `no transaction body yet` | `getTransaction` answered null for a signature the feed listed. | Nothing. The loop moves on to the next batch. |
| `read failed: ...` | The read call returned an error, with its message. | Check the message. A 429 means the pause is too short. |
| `done, N events dropped` | The step count ran out. N events fell off the full queue. | Raise the step count or slow the feed. |

The read asks for `confirmed` and sets `maxSupportedTransactionVersion` to 1 with the `json` encoding. Mainnet carries v1 transactions, and without that option a v1 transaction answers -32015, uncharged. In `@solana/kit` 8.6.0 the value 1 is part of the type, so it needs no cast.

## Pacing, cost and one socket

`getTransaction` costs 50 cells, and cells are the admission charge per call. The `GAP_MS` pause is what keeps the loop under that rate, so pick it so one read per gap fits your plan's [getTransaction rate](https://carbium.sh/docs#rpc). A call over its rate gets 429 with a retry-after hint once the one short wait at the door is spent. The loop prints that failure and takes the next batch.

The feed bills credits too. A `logsSubscribe` with a `mentions` filter opens at 25 credits and then costs 20 credits per MiB sent, and a busy program sends logs for every transaction that mentions it. A refused subscription costs nothing. The file builds one socket and keeps it, so the 25-credit open is paid once and the loop holds one of Free's 5 sockets. Limits are per account, so a second service on the same account spends the same budget.

## Where a model call fits

`decide` is the one function to replace. Give the model the batch as short text lines, one per event with signature, slot and failed flag, and ask for one signature or none. Check that the answer is a signature from the batch before `act` runs, because a model can return text that looks right and names something else. Leave `act` alone: one read method, fixed in code.

The model never calls the RPC itself. It picks, and the loop's code reads. That keeps the model's reach at one method with fixed arguments. [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) shows an allowlist for the case where the model does call tools directly.

To follow many wallets, [Multi-wallet log watcher](https://carbium.sh/library/howsolana/multi-wallet-log-watcher) shows one socket carrying a subscription per address.

## Where it ends

- The loop samples. Events that lose the pick are never read, and the skipped count is the only trace they leave. If every transaction needs a read, run a worker pool sized to your plan's `getTransaction` rate, or move to the gRPC stream, which opens on Dev, Business and Pro and is off on Free.
- Delivery is at most once. The file has no reconnect and exits with status 1 when the socket closes, so anything that landed while it was down is missed. `getSignaturesForAddress` can fill the gap, but its pages come from an address index that keeps up to 30 days.
- `pending` and the counters live in memory, and a restart forgets what the loop saw.
- `mentions` matches transactions that list the program's address. A token transfer lists token accounts and not the receiving wallet, so for one wallet's activity watch its token accounts as well.
- `getTransaction` can answer null for a signature the feed just listed. The file reports that and moves on without a retry.
- The rule looks at the failed flag and recency only. It does not examine what the program did, and the loop signs and sends nothing.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The loop prints `subscribed` and then nothing. | The program address is quiet or mistyped. Point it at a program with transactions in the last minutes. With no events the loop sleeps by design. |
| Every step prints `read failed` with a 429. | The pause is shorter than your plan's `getTransaction` rate allows. After the one wait at the door the call gets 429 with a retry-after hint. Raise `GAP_MS` to at least that hint. |
| A read answers -32015. | The call left out `maxSupportedTransactionVersion`, or set it to 0, and the transaction is v1. Keep the option at 1 on every `getTransaction` and `getBlock` call. |
| `no transaction body yet` appears on many steps. | `getTransaction` answered null for a signature the feed listed. The loop skips it. If it happens on most steps, check that the read still uses `confirmed`. |
| The subscription is refused and the process exits. | Connection and subscription counts are capped per account by plan, and Free carries 5 sockets. Close sockets you do not use. A refused subscription costs nothing. |
| Credits fall fast while the loop idles between reads. | The feed bills 20 credits per MiB sent, and a busy program sends logs for every transaction that mentions it. Choose a quieter program, or stop the loop when no one is looking at the output. |

## Questions

### How is this different from a webhook?

A webhook posts to a URL you host, so you run a public endpoint. This loop holds one outbound socket from your process and needs no inbound port. [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) covers the webhook route.

### Why read the newest event and not the oldest first?

On a busy program the oldest events are already stale by the time a slow step finishes. The newest shows what the program is doing now, and a failed event beats it because an error is what usually needs explaining.

### Where does the model go?

Into `decide`. Hand it the batch as text, accept only a signature from that batch, and keep `act` as the single fixed read.

### Can the loop send a transaction?

No. It makes read calls and one subscription, holds no keypair and signs nothing.

### Why does the file exit after the step count?

So a run ends on its own and prints how many events the queue dropped. Pass a large count for a long-lived watcher and run it under a supervisor.

## Related

- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [Multi-wallet log watcher](https://carbium.sh/library/howsolana/multi-wallet-log-watcher) (How to use Solana, HS0011)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
