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

# Streamed transaction embeddings

A filtered live feed of one program's transactions becomes text records and vectors in a local SQLite file. After fifteen seconds the file prints how many rows it stored and the nearest neighbours of one of them.

## Picking the feed

A dataset for analysis starts with a decision about the slice. Reading every block and filtering afterward pulls and pays for all of each block's transactions, including the ones you never wanted. A filtered live feed hands you only the transactions that touch one program, and the store fills as they arrive. The pipeline has four stages: subscribe, write a text record per transaction, embed the record, store the vector beside the row.

[`logsSubscribe`](https://carbium.sh/docs#websocket) streams transaction logs, all or by mention. A mention filter names one address, here a busy program, and the feed carries each transaction that lists it. The file passes `confirmed` in the subscription, so a notification arrives once its transaction has reached that commitment.

| Feed | Endpoint and key | Plans | Opening cost |
|---|---|---|---|
| logsSubscribe by mention | `wss://services.carbium.sh`, key as `?api-key=` | Free carries 5 sockets | 25 credits, then 20 per MiB sent |
| gRPC stream | `https://services.carbium.sh:9443`, key in `x-token` | Dev, Business and Pro; Free is off | 5, 25 or 200 credits by filter weight, then 20 per MiB sent |

Start with the WebSocket. When one mention does not describe the slice you want, the [gRPC stream](https://carbium.sh/docs#stream) filters on the server and opens on Dev and up.

Cost follows volume. A busy program sends a lot of data, and every MiB sent costs 20 credits, so the file listens for a fixed fifteen seconds and stops.

## One text record per transaction

A logs notification carries the signature, the error field, the log lines and the slot. It has no account list and no amounts. The log lines are the text, and the record keeps three things from them.

- Status: `ok`, or `failed` when the error field is set.
- Programs: every program id from the `Program <id> invoke` lines, once each, in order of first call.
- Messages: up to five `Program log:` lines, cut to 400 characters together.

The cut keeps the record inside the bounded amount of text an embedding model reads, since a long record spends that budget on boilerplate. Separately, the runtime truncates very large logs by itself and marks the cut with a `Log truncated` line, so a record from a heavy transaction can be short anyway.

Program ids and log words both drive the score. Two transactions that call the same set of programs and print similar messages share most of their record, so they land close together. A failed transaction starts with the word `failed`, which adds one more shared token among failures.

## The file

One file. Node 24 runs the TypeScript directly, and the only import is `node:sqlite`. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. `CARBIUM_WS_URL` overrides the endpoint. The one argument is a program address, which defaults to a busy swap router program.

`main.ts` (run: `node main.ts JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4`)

```ts
// SI0073 · Streamed transaction embeddings
// https://carbium.sh/library/si/streamed-transaction-embeddings
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Streamed transaction embeddings: logsSubscribe, a text record per transaction, a hashed vector, SQLite, nearest neighbours.
// Run: CARBIUM_KEY=... node main.ts JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4
import { DatabaseSync } from "node:sqlite";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const program = process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";
const wsUrl = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";
const DIMS = 512;
const WINDOW_MS = 15_000;

// Stand-in embedding: hashed tokens, normalised. Swap in a model's embedding with the same return type.
function embed(text: string): Float32Array {
  const v = new Float32Array(DIMS);
  for (const token of text.match(/[A-Za-z0-9]+/g) ?? []) {
    let h = 2166136261;
    for (let i = 0; i < token.length; i++) h = Math.imul(h ^ token.charCodeAt(i), 16777619);
    v[(h >>> 0) % DIMS] += 1;
  }
  const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;
  return v.map((x) => x / norm);
}

// Status, invoked programs, and a few trimmed log messages.
function toRecord(err: unknown, logs: string[]): string {
  const programs = new Set<string>();
  for (const line of logs) {
    const m = /^Program (\w+) invoke/.exec(line);
    if (m) programs.add(m[1] as string);
  }
  const messages = logs.filter((l) => l.startsWith("Program log:")).slice(0, 5).join(" ").slice(0, 400);
  return `${err ? "failed" : "ok"} programs ${[...programs].join(" ")} ${messages}`;
}

const db = new DatabaseSync("transactions.db");
db.exec("CREATE TABLE IF NOT EXISTS tx (signature TEXT PRIMARY KEY, slot INTEGER, doc TEXT, vec BLOB)");
const insert = db.prepare("INSERT OR IGNORE INTO tx (signature, slot, doc, vec) VALUES (?, ?, ?, ?)");

const ws = new WebSocket(`${wsUrl}?api-key=${key}`);
ws.addEventListener("open", () =>
  ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [program] }, { commitment: "confirmed" }] })),
);
ws.addEventListener("error", () => {
  console.error("WebSocket error: check CARBIUM_KEY and CARBIUM_WS_URL.");
  process.exit(1);
});
ws.addEventListener("message", (ev) => {
  const msg = JSON.parse(String(ev.data));
  if (msg.error) return console.error("subscribe failed:", msg.error.message);
  if (msg.method !== "logsNotification") return;
  const { context, value } = msg.params.result;
  const doc = toRecord(value.err, value.logs ?? []);
  insert.run(value.signature, context.slot, doc, new Uint8Array(embed(doc).buffer));
});

setTimeout(() => {
  ws.close();
  const rows = db.prepare("SELECT signature, doc, vec FROM tx").all() as unknown as { signature: string; doc: string; vec: Uint8Array }[];
  console.log(`stored ${rows.length} transactions in transactions.db (listened ${WINDOW_MS / 1000} s to ${program})`);
  const probe = rows[0];
  if (!probe) {
    console.log("No notifications arrived. Try a busier program address.");
    process.exit(0);
  }
  const vec = (b: Uint8Array) => new Float32Array(b.slice().buffer);
  const p = vec(probe.vec);
  console.log(`probe ${probe.signature.slice(0, 12)}: ${probe.doc.slice(0, 90)}`);
  rows
    .slice(1)
    .map((r) => ({ r, score: vec(r.vec).reduce((s, x, i) => s + x * (p[i] as number), 0) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, 3)
    .forEach(({ r, score }) => console.log(`near ${score.toFixed(3)} ${r.signature.slice(0, 12)}: ${r.doc.slice(0, 90)}`));
  process.exit(0);
}, WINDOW_MS);
```

The run prints the number of rows in the database, the probe (the first stored record, cut to 90 characters) and its three nearest neighbours with their cosine scores. The row count depends on how busy the program is during the window. A quiet program prints a message and no neighbours. The database file `transactions.db` sits in the working directory and keeps its rows between runs. The signature is the primary key, so a repeated notification is ignored.

## The embed step and its swap point

`embed` splits the record into alphanumeric tokens, hashes each into one of 512 buckets and normalises the result. It is a stand-in. Records that share program ids and log words score high, and two records that describe the same event in different words do not. It measures overlap of tokens and says nothing about meaning.

That is enough to group transactions by the programs they call and the messages they print. For meaning, replace `embed` with a call to an embedding model of your choice and keep the signature: text in, normalised `Float32Array` out. Three edits follow. Set `DIMS` to the model's dimension. Make `embed` async and await it in the handler, ideally batching records every few seconds so the socket handler does not wait on the model for each message. Then re-embed the rows already stored, which the `doc` column makes possible, because vectors from two embeddings cannot be compared with each other.

## Storing and querying

Each row holds the signature, the slot, the record and the vector as 2,048 bytes (512 floats of 4 bytes). The record and its vector live in one row, so a later re-embed reads `doc` from the same table.

The query loads every vector and scores it against the probe with a dot product, which on normalised vectors equals cosine similarity. It is a full scan: fine for thousands of rows, the wrong tool for millions. Past that size, move the vectors into an index built for nearest-neighbour search and keep SQLite for the signature, slot and record.

To add what the logs lack, such as amounts and account lists, read the transaction with [`getTransaction`](https://carbium.sh/docs#rpc), which costs 50 cells. Pass `maxSupportedTransactionVersion: 1` with an encoding. Mainnet carries v1 transactions, and with the value absent or 0 the call answers -32015 for one of them.

## Where it ends

- The vector is a stand-in. It matches shared tokens, so a search by meaning needs a model's embedding in its place.
- The feed starts when you subscribe. Transactions from before that moment are never delivered, so they are not in the table.
- Backfill reaches 30 days at most. `getSignaturesForAddress` costs 50 cells and pages from Carbium's address index, which keeps up to 30 days. An empty page past that marks the index's age limit, and the address may have older transactions. `getTransaction` can answer null for an older signature the index lists, so handle null. [30-day training dataset](https://carbium.sh/library/si/30-day-training-dataset) builds on that window.
- A subscription lives as long as its connection. A collector that loses its connection subscribes again and fills the gap from `getSignaturesForAddress`. [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect) covers the loop.
- One mention is one program. A slice defined by several programs or by account contents needs the gRPC stream on Dev and up, or several subscriptions that each count against your socket and subscription caps.
- Log text is written by program authors. If records reach a language model's prompt, place them below the instruction line as quoted data.
- 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 |
|---|---|
| The run stores 0 transactions and prints the no-notifications message. | The program was quiet for fifteen seconds or the address is wrong. Pass the address of a busier program, and read the `subscribe failed` line if one was printed. |
| The socket errors out right away. | An unknown key gets 401 at the door. Attach the whole key in `CARBIUM_KEY`, and check that `CARBIUM_WS_URL` has no query string of its own. |
| Credits drop faster than expected. | Every MiB sent costs 20 credits, and a busy program sends a lot. Keep the listening window short, pick a narrower program, or stop the collector when the table has enough rows. |
| Nearest neighbours look unrelated in meaning. | The stand-in vector groups records by the tokens they share, such as program ids and log words. Swap in a model's embedding and re-embed the stored `doc` values. |
| A follow-up `getTransaction` answers -32015. | Send `maxSupportedTransactionVersion: 1` with an encoding. Without it, a v1 transaction is refused. |
| A resubscribe after a reconnect delivers a transaction already stored. | The signature is the primary key and the insert ignores a repeat, so the table stays clean. |

## Questions

### Is the hashed vector good enough for semantic search?

No. It scores token overlap, so it groups transactions by the programs and messages they share. For search by meaning, replace `embed` with an embedding model and keep the same input and output shape.

### Why subscribe instead of polling getSignaturesForAddress?

A poll costs 50 cells per call whether or not anything new arrived, and it only sees transactions the index has already listed. A subscription is billed in credits by MiB sent and delivers each transaction as it reaches confirmed.

### How long can the collector run?

It runs as long as its connection holds, so wrap the subscribe step in a reconnect loop and fill any gap from `getSignaturesForAddress`, which reaches back 30 days at most.

### Can I use the gRPC stream instead?

Yes on Dev, Business and Pro. It filters on the server at `https://services.carbium.sh:9443` with the key in the `x-token` header, and Free is off. The record, embed and store steps stay the same.

### How far back can I load history into the table?

As far as Carbium's address index reaches, which is up to 30 days. Page `getSignaturesForAddress`, read each signature with `getTransaction`, and handle null for the ones that no longer resolve.

## Related

- [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect) (How to use Solana, HS0036)
- [30-day training dataset](https://carbium.sh/library/si/30-day-training-dataset) (AI and blockchain, SI0014)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#stream](https://carbium.sh/docs#stream)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
