---
id: SI0118
title: "Log message embeddings"
url: https://carbium.sh/library/si/log-message-embeddings
collection: AI and blockchain
category: RAG and embeddings
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Log message embeddings

No RPC method searches program logs, so you build the index. The file reads a program's newest transactions, embeds each log line into SQLite, and answers a text query with the signatures whose logs match it.

## The RPC has no log search

Solana's JSON-RPC lists the transactions that touch an address and returns one transaction by its signature. It has no call that finds transactions by what their logs say. A line such as `Program log: Instruction: Transfer`, or a custom error string a program prints before it fails, sits inside the transaction's metadata. The only way to search that text is to read the transactions and build the index yourself.

The index here is small. Take the newest signatures of a program, fetch each transaction, pull its `logMessages`, embed every line and store the vector in SQLite beside the signature. A text query is embedded the same way and compared with every stored line. Each transaction is ranked by its best line, so the answer is a list of signatures, each with the line that matched.

| Need | Where it comes from |
|---|---|
| Transactions that touch a program | `getSignaturesForAddress` on the program address |
| Log lines of one transaction | `getTransaction`, field `meta.logMessages` |
| Lines similar to a query | your embedding and your store |
| New lines as they land | `logsSubscribe` with a mention |

> [Streamed transaction embeddings](https://carbium.sh/library/si/streamed-transaction-embeddings) embeds whole transactions as they stream. The file below indexes single log lines from reads, so a query lands on a line and its signature comes with it.

## The file

One file for Node 24, with `@solana/kit` as its only dependency and `node:sqlite` for storage. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. `CARBIUM_RPC_URL` overrides the endpoint, which defaults to `https://services.carbium.sh`. The database is `logs.db` in the working directory.

`main.ts` (run: `node main.ts "Instruction: Route"`)

```ts
// SI0118 · Log message embeddings
// https://carbium.sh/library/si/log-message-embeddings
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Log message embeddings: index a program's log lines in SQLite, then search them by similarity.
// Run: CARBIUM_KEY=... node main.ts "Instruction: Route" [program]
import { DatabaseSync } from "node:sqlite";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));
const COMMITMENT = "confirmed" as const;
const query = process.argv[2] ?? "Instruction: Route";
const program = address(process.argv[3] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");

// Addresses and long numbers differ on every transaction; mask them so wording decides the match.
const normalise = (line: string) =>
  line.replace(/[1-9A-HJ-NP-Za-km-z]{32,44}/g, "<addr>").replace(/\d{4,}/g, "<n>");

// Character-trigram hash embedding: it matches wording. Swap in a model's embedding with the same shape.
const DIMS = 1024;
function embed(text: string): Float32Array {
  const v = new Float32Array(DIMS);
  for (const word of normalise(text).toLowerCase().match(/[a-z0-9<>]+/g) ?? []) {
    const padded = ` ${word} `;
    for (let i = 0; i + 3 <= padded.length; i++) {
      let h = 2166136261;
      for (let j = i; j < i + 3; j++) h = Math.imul(h ^ padded.charCodeAt(j), 16777619);
      v[(h >>> 0) % DIMS] += 1;
    }
  }
  let norm = 0;
  for (const x of v) norm += x * x;
  return v.map((x) => x / (Math.sqrt(norm) || 1));
}
const dot = (a: Float32Array, b: Float32Array) => a.reduce((sum, x, i) => sum + x * (b[i] as number), 0);

const db = new DatabaseSync("logs.db");
db.exec("CREATE TABLE IF NOT EXISTS lines (sig TEXT, norm TEXT, line TEXT, vec BLOB, PRIMARY KEY (sig, norm))");
const insert = db.prepare("INSERT OR IGNORE INTO lines VALUES (?, ?, ?, ?)");

// Backfill: newest signatures of the program, then each transaction's log lines.
const listed = await rpc.getSignaturesForAddress(program, { limit: 12, commitment: COMMITMENT }).send();
const fetched = await Promise.allSettled(
  listed.map(async ({ signature }) => ({
    signature,
    tx: await rpc
      .getTransaction(signature, { commitment: COMMITMENT, encoding: "json", maxSupportedTransactionVersion: 1 })
      .send(),
  })),
);
let skipped = 0;
for (const r of fetched) {
  if (r.status === "rejected") {
    console.error("read failed:", String(r.reason));
    continue;
  }
  if (!r.value.tx) {
    skipped++; // listed below the ledger floor, so no transaction to read
    continue;
  }
  for (const line of r.value.tx.meta?.logMessages ?? []) {
    insert.run(r.value.signature, normalise(line), line, Buffer.from(embed(line).buffer));
  }
}

// Search: best line per signature.
const q = embed(query);
const rows = db.prepare("SELECT sig, line, vec FROM lines").all() as unknown as { sig: string; line: string; vec: Uint8Array }[];
const best = new Map<string, { score: number; line: string }>();
for (const r of rows) {
  const score = dot(q, new Float32Array(new Uint8Array(r.vec).buffer));
  if (score > (best.get(r.sig)?.score ?? 0)) best.set(r.sig, { score, line: r.line });
}
console.log(`indexed ${rows.length} lines; ${skipped} listed signatures had no transaction`);
for (const [sig, hit] of [...best].sort((a, b) => b[1].score - a[1].score).slice(0, 5)) {
  console.log(`${hit.score.toFixed(2)} ${sig} ${hit.line}`);
}
```

The first argument is the query and the optional second is a program address. Without them it searches the Jupiter v6 program for `Instruction: Route`. The run prints how many lines the table holds and how many listed signatures had no transaction, then up to five signatures with a score and the matching line. Run it again later and the table keeps the old rows, so the index grows with each run.

`embed` hashes character trigrams into 1,024 buckets and normalises the vector. It matches wording: a query that says `insufficient funds` finds lines that say it, and it does not know that `out of lamports` means the same. Replace it with your model's embedding call and keep the same normalised `Float32Array` shape. A model call is async, so the insert loop and the query embedding need `await` once you do.

Both calls read at confirmed commitment. `getTransaction` also carries `maxSupportedTransactionVersion: 1`, since mainnet has v1 transactions and a call for one without that setting answers -32015.

## Why lines are normalised first

Raw logs are full of values that differ on every transaction: addresses inside `invoke` lines, and compute counts in `Program consumed 41203 of 200000 compute units`. Embedded as they are, two lines with the same wording look different, and a query made of words matches on whichever digits happen to share a trigram.

`normalise` replaces anything that looks like a base58 address with `<addr>` and any run of four or more digits with `<n>`. Repeated lines inside one transaction collapse into one row, because the primary key is the signature plus the normalised text. The stored `line` column keeps the original text for display. Short numbers such as the `[1]` in `invoke [1]` and small error codes survive, so `custom program error: 0x1` still differs from `0x2`.

The price of this choice is that a query cannot find a specific amount or a specific address. For those, filter on the transaction itself: the signatures come back from `getSignaturesForAddress` for the address you care about, and the balance fields are in the same `getTransaction` response.

## What the fetch costs

Indexing is a read job, and the reads are the expensive part. [`getSignaturesForAddress` and `getTransaction`](https://carbium.sh/docs/rpc) cost 50 cells each. The rates in calls per second differ a lot by plan and by method.

| Method | Free | Dev | Business | Pro |
|---|---|---|---|---|
| getTransaction | 0.24 | 1.2 | 5 | 25 |
| getSignaturesForAddress | 0.24 | 1.2 | 100 | 500 |

The file asks for 12 signatures: one listing call and up to 12 transaction reads, 650 cells in total. A class absorbs a burst of 1,024 cells or one second of its rate, whichever is larger, so that first pass fits. A larger backfill has to pace itself to the table above. On Free that is about one transaction every four seconds.

A call that has no transaction for a signature is skipped and counted. The file settles every transaction read with `Promise.allSettled`, so one failing read prints its reason and the others still land in the index.

## Keeping the index current

A backfill from signatures goes back at most 30 days. For new transactions as they land, a [WebSocket](https://carbium.sh/docs/websocket) `logsSubscribe` streams the logs of transactions that mention an address, or all logs. The notification carries the signature, the error field and the log lines, so each one can go straight into the same `insert` without a `getTransaction` read.

A subscription filtered by mention opens at 25 credits, and an all-logs one at 200. Both then cost 20 credits per MiB sent, and a refused subscription costs nothing. A busy program emits a lot of text, so budget the MiB before pointing the subscription at a program like Jupiter. [Logs grouped by instruction](https://carbium.sh/library/howsolana/logs-grouped-by-instruction) shows how to group the lines of a transaction by the instruction that printed them, which gives each embedded line a clean parent.

## Where it ends

- The index holds only what you fetched. A query returns nothing about transactions the file never read, and no call asks the chain whether a matching one exists elsewhere.
- History is 30 days at most. `getSignaturesForAddress` pages come from an address index that keeps up to 30 days, so an empty page past that is the index's age limit and the address may have older transactions. Pages reach below the validator's ledger floor, which means `getTransaction` can answer null for an older signature the listing returned. The file counts those and moves on.
- The trigram embedding matches spelling only. Paraphrase, synonyms and other languages need a model embedding in place of `embed`.
- The runtime truncates a transaction's log once it grows past its size limit, and a `Log truncated` line replaces the rest. Those lines are not in the index and no read recovers them.
- Log text is whatever the program's author chose to print. A program can print a misleading line, and any text a stranger can influence belongs in a prompt only as quoted data. For balances and amounts, read the transaction's balance fields.
- A match proves wording. It does not prove the transaction did what the line says; check `err` and the balance changes before you act on a hit.
- The file is read-only: no signing, no sending, no keys beyond the Carbium key.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| `getTransaction` answers -32015 for a transaction the listing returned. | Pass `maxSupportedTransactionVersion: 1` with an encoding, as the file does. Absent or 0, a v1 transaction is refused, and the refused call costs nothing. |
| `getTransaction` returns null for a signature that `getSignaturesForAddress` just listed. | Treat null as a skipped row and count it. The address index reaches below the ledger floor, so older signatures can list without being readable. Index the newest signatures first. |
| A query that contains an amount or an address finds nothing useful. | Normalisation turns addresses and numbers of four digits or more into placeholders. Search by wording, then check the amount in the transaction's balance fields. |
| The backfill loop gets 429 on a Free key. | Read the retry-after hint and pace to the plan's rate for `getTransaction`, or lower the signature limit. Settle each read so one refusal does not stop the others. |
| Every transaction of a program returns the same top line, such as an `invoke [1]` line. | Lines that every transaction shares carry no information. Index only `Program log:` lines, or drop any normalised line that appears in more than half of the transactions. |
| A rerun fills the table with duplicate rows. | Keep the primary key on signature and normalised text and insert with `INSERT OR IGNORE`, as the file does. |

## Questions

### Is there an RPC method that searches logs for me?

No. The RPC lists transactions by address and returns one by signature, and the log text comes with the transaction. You fetch the transactions you care about and search them in your own store.

### How far back can the index reach?

A backfill from `getSignaturesForAddress` reaches back 30 days at most, because that is how long Carbium's address index keeps signatures. For text older than that you need your own record, built from the live subscription.

### Do I need an embedding model for this?

Not as written. `embed` runs locally and matches wording, which is enough for fixed phrases such as instruction names and error strings. For questions in free language, swap in a model embedding with the same output shape.

### Should I embed every line or only `Program log:` lines?

Start with every line, since failures and `invoke` lines carry meaning too. If the top results are dominated by lines every transaction shares, restrict the index to `Program log:` lines.

## Related

- [Logs grouped by instruction](https://carbium.sh/library/howsolana/logs-grouped-by-instruction) (How to use Solana, HS0064)
- [Streamed transaction embeddings](https://carbium.sh/library/si/streamed-transaction-embeddings) (AI and blockchain, SI0073)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/migrate](https://carbium.sh/docs/migrate)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
