library / AI and blockchain / RAG and embeddings / SI0119
Recency-ranked retrieval by slot
A small SQLite store that pulls the newest transactions for an address, then ranks them for a language model by text match weighted by how many slots old each one is. You get fresh context first, with a score you can print and audit.
Why slot age belongs in the ranking
A retrieval step for a chain question weighs two things. One is how well a transaction matches the question. The other is how recent it is. A question like "what happened to this program lately" gets a poor answer if the top result is a perfect text match from three weeks ago. On a busy program the useful rows are the newest few dozen.
A slot gives recency an exact clock. Every transaction carries the slot it landed in, and getSlot returns the current one, so age is a subtraction of two integers. You need no timestamps and no allowance for clock drift between your machine and the chain. A slot lasts about 200 ms, so 150 slots is roughly 30 seconds, and a half-life measured in slots is easy to reason about.
The script keeps the idea small. It reads the newest signatures for one address, fetches each transaction, stores the slot and the log lines in SQLite, and ranks the rows with one formula. No embedding model sits in the loop, so you can read why each row won, and you can swap in a vector score later without touching the recency term.
Reading the newest transactions
getSignaturesForAddress returns signatures newest first, each with its slot. With limit set to 5 you get the five latest. getTransaction then returns the logs for each signature, and getSlot gives the head to measure age against. The three calls cost different amounts on the RPC endpoint, and the transaction lookups dominate.
| Method | Cost in cells | Free req/s | Dev req/s |
|---|---|---|---|
| getSlot | 1 | 5 | 30 |
| getSignaturesForAddress | 50 | 0.24 | 1.2 |
| getTransaction | 50 | 0.24 | 1.2 |
One run with a page of five signatures costs 1 + 50 + 5 x 50 = 301 cells. Cells are the admission charge per call, so the number to watch is how many getTransaction calls a page triggers. Keep limit small while you tune the ranking, and raise it once the scores look right.
Leave commitment out and @solana/kit fills in confirmed, so all three calls here read at confirmed. The server's own default is finalized, so a client built another way reads at that level instead. For a recency ranking the difference is small, since processed, confirmed and finalized sit within a slot of each other.
Mainnet carries v1 transactions, and getTransaction answers -32015 for one unless maxSupportedTransactionVersion is 1. The code passes 1 with the json encoding. Kit types the field as 'legacy' | 0 | 1, so the inline 1 needs no cast.
The code
Run it with an address and a query word. Without arguments it reads the Token program and ranks on the word transfer. Each failed transaction lookup prints its reason, and the run goes on with the rows that arrived.
// SI0119 · Recency-ranked retrieval by slot// https://carbium.sh/library/si/recency-ranked-retrieval-by-slot// 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 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 target = address(process.argv[2] ?? "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const word = (process.argv[3] ?? "transfer").toLowerCase();const HALF_LIFE = 150;const db = new DatabaseSync("recent.db");db.exec("CREATE TABLE IF NOT EXISTS tx (sig TEXT PRIMARY KEY, slot INTEGER, logs TEXT)");const put = db.prepare("INSERT OR REPLACE INTO tx VALUES (?, ?, ?)");const sigs = await rpc.getSignaturesForAddress(target, { limit: 5 }).send();const fetched = await Promise.allSettled( sigs.map((s) => rpc.getTransaction(s.signature, { maxSupportedTransactionVersion: 1, encoding: "json" }).send(), ),);const head = Number(await rpc.getSlot().send());let skipped = 0;fetched.forEach((r, i) => { const sig = sigs[i]!.signature; if (r.status === "rejected") { console.error(`failed ${sig.slice(0, 12)}: ${String(r.reason)}`); skipped++; } else if (r.value === null) { console.error(`null ${sig.slice(0, 12)}: no transaction served`); skipped++; } else { const logs = (r.value.meta?.logMessages ?? []).join("\n"); put.run(sig, Number(r.value.slot), logs); }});type Row = { sig: string; slot: number; logs: string };const rows = db.prepare("SELECT sig, slot, logs FROM tx").all() as unknown as Row[];const ranked = rows .map((row) => { const hits = row.logs.toLowerCase().split(word).length - 1; const age = Math.max(0, head - row.slot); return { ...row, hits, age, score: (1 + hits) * 0.5 ** (age / HALF_LIFE) }; }) .sort((a, b) => b.score - a.score);console.log(`head slot ${head}, ${rows.length} rows stored, ${skipped} skipped`);for (const r of ranked.slice(0, 3)) { console.log(`${r.score.toFixed(3)} slot ${r.slot} age ${r.age} hits ${r.hits} ${r.sig.slice(0, 16)}`);}
run: node main.ts TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA transfer
How the score works
The score is (1 + hits) * 0.5 ** (age / 150). Hits is the number of times the query word appears in the transaction logs, and age is the head slot minus the transaction slot, floored at 0 for a row at or past the head. A row 150 slots old counts half as much as a row from the head slot, and a row 300 slots old counts a quarter.
Adding 1 to the hits keeps a row with no match in the ranking, ordered by recency alone. That matters when the question is vague. If you drop the 1, a query word absent from every log gives every row a score of zero and the order becomes arbitrary.
- Half-life: 150 slots suits a live program where the last half minute matters. Raise it to 1,500 for slower addresses.
- Hit count: a plain substring count over the logs. Swap it for a vector similarity when the question is semantic.
- Stored value: the slot. Age grows with every new slot, so the script computes it from a fresh head at ranking time.
Because the table holds slots, the same rows rank correctly an hour later. Run getSlot again at question time and recompute the score in the query. The database never needs rewriting for the ranking to stay fresh.
Feeding the ranked rows to a model
Take the top three or four rows and write each as one line with the signature, the slot, the age in slots and the matching log lines. The model can then cite a slot for each claim, and you can check the claim by reading that transaction. The pattern pairs well with Live account RAG, which keeps account state in the same kind of store.
For long address histories, page back with the before option and keep the same table. Signature history pagination walks through the cursor handling, which this script skips because it only wants the newest page.
Where it ends
- The address index behind getSignaturesForAddress keeps up to 30 days, so an empty page past that point marks the index's age limit and the address may have older transactions.
- Pages reach below the validator's ledger floor, so getTransaction can answer null for an older signature it listed. The script counts and skips those, and it works on the newest signatures where that does not occur.
- The match score is a substring count over log lines. It finds the word transfer and misses a paraphrase of it.
- The SQLite file grows with every run. Delete rows older than your useful window, or the table will rank thousands of stale rows to find a few fresh ones.
- A Free key sustains getTransaction at 0.24 req/s and Dev at 1.2 req/s.
The script sends every lookup in a page at once, so size limit to your plan's rate before you raise it.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTransaction returns null for a signature that getSignaturesForAddress just listed. | The address index reaches below the validator's ledger floor, so an older signature can have no transaction to return. Skip it, count it, and prove the ranking on the newest signatures. |
| getTransaction answers -32015 for some signatures. | The transaction is v1 and the request left maxSupportedTransactionVersion out or set it to 0. Pass 1 together with an encoding. |
| An old row ranks first after the database has sat for a day. | The age was stored instead of the slot, or the head slot in the query is stale. Store the slot and read getSlot again when the question arrives. |
| Calls fail with 429 when the page grows. | Each transaction lookup costs 50 cells and a Free key allows 0.24 req/s. Wait for the retry-after hint, lower limit, or move to a plan with a higher rate. |
| Every call fails with 401 UNKNOWN_KEY. | The key was cut short or is wrong. Attach the whole key from CARBIUM_KEY and check there is no trailing whitespace. |
Questions
Why rank by slot and not by blockTime?
The slot is an integer you already hold for every transaction, and getSlot gives the matching head, so age needs no second call. Block time can come back null, while every transaction has a slot, so the subtraction has no gap to handle.
Can I replace the hit count with embeddings?
Yes. Keep the recency factor as it is and multiply it by the cosine similarity instead of 1 + hits. The slot column and the half-life stay the same.
How many rows should the model see?
Start with three or four. The half-life already pushes stale rows down, so a longer list mostly adds older text the model has to ignore.
Does this work for a wallet and not only a program?
Yes. Pass any address and the same three calls run. A quiet wallet gives fewer signatures than the limit, and the ranking handles a short list without change.