library / Integrations / Relational databases / I0073
Drizzle program event schema
A script that reads a busy program's newest transactions from Carbium, pulls every Program data: log line, splits the 8-byte discriminator from the payload and stores one row per event in SQLite, with the same columns a Drizzle table declares.
Where a program's events live
A subgraph gives you tables built from a program's events. On Solana you run that indexer yourself, and the schema is the contract between the chain and every query you will write. Choose the key and the columns once, and a later change to the program's events never forces a rebuild.
An Anchor program announces an event with emit!. The runtime writes it into the transaction's log messages as a line that starts with Program data: followed by base64. The decoded bytes begin with an 8-byte discriminator, the first 8 bytes of the SHA-256 of event: plus the event's name. The rest is the event's fields in Borsh encoding. The discriminator names the event type, so one table holds every event the program emits.
Logs also carry lines from other programs the transaction calls. Each call opens with Program <id> invoke [depth] and closes with success or failed, so a data line belongs to the program on top of that stack. Logs grouped by instruction walks the same structure.
The event table
One row per event, keyed by the transaction signature and the event's position among that program's events in the transaction. Both exist before any decoding, so the key never depends on an event's fields and stays valid when an upgrade adds a new event type.
| Column | Drizzle column | Holds |
|---|---|---|
| signature | text('signature').notNull() | The transaction signature, base58 |
| event_index | integer('event_index').notNull() | Position among the program's events in that transaction |
| slot | integer('slot').notNull() | The slot the transaction landed in |
| discriminator | text('discriminator').notNull() | The first 8 bytes of the event, hex |
| payload | blob('payload', { mode: 'buffer' }).notNull() | The remaining bytes, Borsh-encoded fields |
In a Drizzle project this is a sqliteTable or a pgTable with primaryKey({ columns: [t.signature, t.eventIndex] }) in its extra config. The script creates the same table with node:sqlite, so a single file needs no database server. When one table holds several programs, add a program column and put it in the key.
The payload stays as bytes. Decoding the fields is a second step done with the program's IDL, in a view or at read time, so a change in an event's layout never blocks ingest. On-chain IDL extractor fetches that IDL from the chain.
Splitting discriminator from payload
Cut the 14 characters of Program data: off the line, decode the base64 and split at byte 8. The first 8 bytes become a 16-character hex string and the rest goes in payload. A line that decodes to fewer than 8 bytes has no discriminator, so the script skips it.
Hex discriminators group, join and compare well in SQL, so the table keeps them as hex text and leaves the naming to a lookup at query time.
A failed transaction still logs the events it reached, although its state changes are rolled back. The script skips any transaction whose meta.err is set, so every row is an event that happened. Other programs also write Program data: lines in layouts of their own, which is why the script reads only the lines the target program wrote.
Reading the transactions
getSignaturesForAddress lists the newest signatures that touched the program, and getTransaction returns each one with its logs. Each costs 50 cells. The list call is 50 cells in its own rate class, and the five reads come to 250 cells, inside the 1,024 cells their class absorbs as a burst. A larger run spaces its reads to its plan's rate.
The script leaves commitment out, and @solana/kit 8.6.0 then sends confirmed. getTransaction passes maxSupportedTransactionVersion: 1, because mainnet carries v1 transactions and a call without it answers -32015 for one.
Each transaction read is settled on its own. A read can fail, or answer null for a signature the list shows, since the list comes from an address index that reaches below the validator's ledger floor. The script prints the reads that failed and indexes the rest.
The event indexer
Use Node 24, which strips the types on load, and npm install @solana/[email protected]. The script takes one program address, reads that program's five newest signatures and stores every event in events.db in the working directory. It needs CARBIUM_KEY and exits with a message when it is unset. CARBIUM_RPC_URL is optional. It only reads: no signing and no sending.
// I0073 · Drizzle program event schema// https://carbium.sh/library/integrate/drizzle-program-event-schema// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1);}const program = process.argv[2];if (!program) { console.error("Usage: node main.ts <program address>"); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const message = (e: unknown) => (e instanceof Error ? e.message : String(e));const db = new DatabaseSync("events.db"); // relative: the file lands in the working directorydb.exec(`create table if not exists program_event ( signature text not null, event_index integer not null, slot integer not null, discriminator text not null, payload blob not null, primary key (signature, event_index))`);const put = db.prepare("insert or ignore into program_event values (?, ?, ?, ?, ?)");const sigs = await rpc.getSignaturesForAddress(address(program), { limit: 5 }).send();const reads = await Promise.allSettled( sigs.map((s) => rpc.getTransaction(s.signature, { encoding: "json", maxSupportedTransactionVersion: 1 }).send()),);let scanned = 0;let seen = 0;let stored = 0;const perKind = new Map<string, number>();for (const [i, read] of reads.entries()) { const { signature, slot } = sigs[i]; if (read.status === "rejected") { console.log(`failed ${signature.slice(0, 8)}: ${message(read.reason)}`); continue; } if (read.value === null) { console.log(`null ${signature.slice(0, 8)}: the ledger no longer holds it`); continue; } scanned++; if (read.value.meta?.err) continue; // a failed transaction's state changes were rolled back const stack: string[] = []; let index = 0; for (const line of read.value.meta?.logMessages ?? []) { const call = /^Program (\w+) invoke \[\d+\]$/.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[stack.length - 1] === program) { const bytes = Buffer.from(line.slice(14), "base64"); // 14 characters: "Program data: " if (bytes.length < 8) continue; const kind = bytes.subarray(0, 8).toString("hex"); stored += Number(put.run(signature, index++, Number(slot), kind, bytes.subarray(8)).changes); seen++; perKind.set(kind, (perKind.get(kind) ?? 0) + 1); } }}console.log(`transactions scanned ${scanned}`);console.log(`events seen ${seen}, new rows stored ${stored}`);for (const [kind, n] of perKind) console.log(`discriminator ${kind} ${n}`);
run: node main.ts <program-address>
It prints the transactions scanned, the events it saw, the new rows it stored and one line per discriminator with its count. A second run over the same signatures sees the same events and stores none, because insert or ignore skips a key that exists. In Drizzle the same behaviour is .onConflictDoNothing(). A program that logged no events in those five transactions still gets its summary, with zeros.
Where it ends
- Events sent with emit_cpi! are absent from the logs. The program calls itself and carries the event in the inner instruction's data, so a log reader sees nothing. Those events sit in meta.innerInstructions, which needs its own reader, as in Inner instruction tree.
- A long transaction's log is cut. Validators cap it at 10,000 bytes by default and end it with Log truncated, so events after the cut are not in the logs. The script does not look for that line.
- getSignaturesForAddress reaches back 30 days at most, so a table that must start earlier needs records you already hold.
- The script reads the five newest signatures once. A running indexer pages back with before and keeps a checkpoint, as in Postgres indexer slot checkpoints.
- Payloads stay undecoded, and SQLite fits one writing process. Several writers want a server database.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The run prints events seen 0. | None of the five newest transactions logged an event for that program. It may emit through emit_cpi!, or the transactions failed. Open one transaction's logs and look for Program data:, or raise limit in the signatures call. Each read costs 50 cells, so space the reads to your plan's rate. |
| A line starting failed appears and the other transactions still index. | One read failed and the script moved on. Read the message. A 429 carries a retry-after hint, so wait that long and run again. The rerun skips rows already stored. |
| A line starting null appears. | The signature is listed, but the ledger no longer holds the transaction. Skip it. Recent signatures resolve. |
| A discriminator you do not recognise shows up. | An upgrade added an event type, or the program writes a Program data: line that is not an Anchor event. Check the program's latest release for a new event, and keep the row, since the payload is stored whole. |
| The call answers 401. | Carbium does not recognise the key. Attach the whole key in the x-api-key header. |
Questions
Can drizzle-kit manage this table?
Yes. Declare the table in your schema file with the columns above and let drizzle-kit generate the migration. The script's SQL builds the same table by hand.
Why key by signature and not by slot?
A slot holds many transactions, so a slot and an event index repeat. A signature is unique to a transaction, and the slot sits in its own column for ordering.
How do I follow new events live?
logsSubscribe streams transaction logs, all or by mention. The lines it delivers carry the same Program data: text, so the decoder and the table stay as they are. Anchor events to NATS shows the live side.
How do I name the discriminators?
Hash event: plus the event name with SHA-256 and keep the first 8 bytes, or read the names from the program's IDL. Store them in a small lookup table and join on the hex.