library / AI and blockchain / Model tool calling / SI0127
Token-efficient transaction output
In json encoding the accountKeys from getTransaction are already base58 strings. Build the full address list with the lookup table addresses, resolve every instruction index against it, and give a model a short summary of the transaction.
What accountKeys holds
Ask getTransaction for encoding: "json" and accountKeys comes back as a list of base58 strings. Those strings are the public keys, so there is nothing to convert. In @solana/kit an Address is a string too, so the list drops straight into an address() call or a comparison.
The shape changes with the encoding. With jsonParsed, each entry is an object with pubkey, signer, writable and source, and the address is the pubkey field. With base64 or base58 the whole transaction is bytes, and a decoder has to unpack the message before any list exists. Older web3.js code that holds PublicKey objects calls toBase58() on each one; a string has no such method, which is the usual error when that code meets the JSON encoding.
A model needs less than the full answer. A raw getTransaction result carries every signature, the recent blockhash, log lines, balances before and after, and compute units. Most of that is text the model will never reason about, and it costs context on every turn. The script below builds a short summary and prints the size of both versions for the transaction it fetched, so you can see the ratio on your own data.
Static keys and loaded addresses
Instructions point at accounts by index, and the index space is longer than accountKeys. A v0 transaction can pull addresses from lookup tables. In the json encoding they come back outside the message, in meta.loadedAddresses, as two lists named writable and readonly. The full list is the static accountKeys, then the loaded writable addresses, then the loaded readonly ones. Every programIdIndex and every number in an instruction's accounts array indexes that concatenation.
Read an index against accountKeys alone and every account that came from a table resolves to undefined, because those indexes start where the static list ends. Join the two loaded lists in the wrong order and the indexes land on the wrong addresses.
Two more facts need no lookup. The first header.numRequiredSignatures keys are the signers, and the first key pays the fee. The summary states both directly.
The script
Set CARBIUM_KEY first. The script takes one optional argument, a transaction signature or a program address. With a program address it lists the five newest signatures and fetches them in order until one returns a transaction. With no argument it uses a busy program, so the run always finds something recent.
// SI0127 · Token-efficient transaction output// https://carbium.sh/library/si/token-efficient-transaction-output// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Resolve a getTransaction answer to full addresses and a compact summary. Run: CARBIUM_KEY=... node main.ts [program or signature]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } 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 rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);type Tx = { meta: { err: unknown; fee: bigint | number; loadedAddresses?: { writable: string[]; readonly: string[] } } | null; transaction: { message: { accountKeys: string[]; header: { numRequiredSignatures: number }; instructions: { programIdIndex: number; accounts: number[] }[]; }; };};// Static keys, then loaded writable, then loaded readonly: the order instruction indexes use.export function compact(tx: Tx) { const { message } = tx.transaction; const loaded = tx.meta?.loadedAddresses; const keys = [...message.accountKeys, ...(loaded?.writable ?? []), ...(loaded?.readonly ?? [])]; return { ok: tx.meta?.err == null, fee: Number(tx.meta?.fee ?? 0), feePayer: keys[0], signers: keys.slice(0, message.header.numRequiredSignatures), keys, instructions: message.instructions.map((i) => ({ program: keys[i.programIdIndex], accounts: i.accounts })), };}if (import.meta.main) { const arg = process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"; let sigs: string[] = [arg]; if (arg.length < 50) { try { sigs = (await rpc.getSignaturesForAddress(address(arg), { limit: 5 }).send()).map((s) => s.signature); } catch (e) { console.error("signature list failed:", (e as Error).message); process.exit(1); } } for (const sig of sigs) { try { const tx = (await rpc .getTransaction(signature(sig), { encoding: "json", maxSupportedTransactionVersion: 1 }) .send()) as unknown as Tx | null; if (!tx) { console.log("null for", sig, "(below the ledger floor), trying the next"); continue; } const raw = JSON.stringify(tx, (_k, v) => (typeof v === "bigint" ? Number(v) : v)).length; const out = JSON.stringify(compact(tx)); console.log(`${sig}: raw ${raw} chars, compact ${out.length} chars`); console.log(out); break; } catch (e) { console.log("failed", sig, (e as Error).message); } }}
run: node main.ts
The first output line gives the raw and compact sizes in characters. The second is the compact JSON the model would receive. compact builds keys first and reads everything through it: the fee payer is keys[0], the signers are the first numRequiredSignatures keys, and each program is keys[programIdIndex]. ok is true when meta.err is null. The call leaves commitment out, so @solana/kit fills in confirmed; pass commitment: "finalized" in the config to ask for finalized.
A call that fails is printed and the loop moves to the next signature, so one 429 or one null answer does not end the run.
What the model gets
| Part of the answer | Sent to the model | Reason |
|---|---|---|
| accountKeys plus loadedAddresses | once, as keys | each address appears one time and instructions point at it by index |
| header.numRequiredSignatures | as signers | the first keys of the list, already resolved |
| signatures | no | one base58 string of up to 88 characters per signer, with nothing in it the model can read |
| recentBlockhash | no | an expiry token the model cannot act on |
| meta.logMessages | no | long, and only useful when debugging a failure |
| preBalances, postBalances | no | bare lamport lists that need mapping back to accounts |
| meta.err | as ok | a boolean answers the usual first question |
| meta.fee | yes | a lamport count, converted to a plain number |
Listing the addresses once and pointing at them by index keeps the token program and the fee payer from repeating in every instruction. The model has to follow an index into the list, and for a transaction with dozens of keys that gets harder. For those, resolve each instruction's accounts to addresses inside compact and accept a longer answer.
meta.innerInstructions use the same index list. They are left out here because a swap through a router can hold dozens of them. Add them when the question is about what a program did, and see Inner instruction tree for turning them into a tree.
Cost and limits
getTransaction and getSignaturesForAddress cost 50 cells each. getTransaction runs at 0.24, 1.2, 5 and 25 req/s on Free, Dev, Business and Pro, and getSignaturesForAddress at 0.24, 1.2, 100 and 500 req/s. A tool loop that lists five signatures and fetches each one spends up to 300 cells, so cap the fetches per question.
At 0.24 req/s on Free, a fetch that follows a null answer can come back 429 with a retry-after hint; wait that long before the next fetch. A JSON-RPC batch carries up to 100 calls in one request when you need more transactions.
Where it ends
- The summary names programs and accounts. It does not say what an instruction did. Reading instruction data needs the program's layout, and the data field is left out of the summary on purpose.
- getSignaturesForAddress reaches back 30 days at most, and its pages come from an address index that goes below the validator's ledger floor. getTransaction can therefore answer null for an older signature the list returned. The script skips a null and tries the next one; prove your own code on the newest signatures.
- The script reads message.accountKeys and header from the answer. A transaction that arrives without them makes compact throw, and the loop prints that failure and moves on.
- The compact output has no token balance changes. A question about who received which token needs preTokenBalances and postTokenBalances, and each of those carries an account index into the same list.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| An account from a lookup table resolves to undefined or a wrong address. | Concatenate accountKeys, meta.loadedAddresses.writable and meta.loadedAddresses.readonly in that order, and index into the result. |
| getTransaction answers -32015 for a recent transaction. | Set maxSupportedTransactionVersion: 1 in the config. Absent or 0, a v1 transaction is refused. |
| getTransaction answers null for a signature the address listing returned. | Treat null as an older transaction below the ledger floor and move on. Fetch the newest signatures when you are proving a change. |
| toBase58 is not a function on an entry of accountKeys. | In json encoding the entries are already strings. Use them as they are, or call address() on one when a typed value is needed. |
| An includes check on accountKeys never matches under jsonParsed. | Each entry is an object there. Compare against entry.pubkey, or switch to json encoding for the compact summary. |
| The listing and fetch calls come back with 429 one after the other. | Wait the retry-after hint before the next call and cap the fetches per question. |
Questions
Do I need to convert accountKeys at all?
Not in json encoding. The entries are base58 strings, which is the public key text. Only the byte encodings and the older PublicKey objects need a conversion step.
How do I get the address behind a programIdIndex on a v0 transaction?
Build the full key list from the static keys plus the loaded writable and readonly addresses, then read keys[programIdIndex]. The static list alone is too short whenever a program comes from a lookup table.
Which commitment does the script read at?
@solana/kit fills in confirmed when a call leaves commitment out, and the script leaves it out. Add commitment: "finalized" to the config to read finalized.
Why drop the logs and balances from the model's answer?
They are the largest parts of the raw result and rarely change a model's reading of who did what. Fetch them in a second tool when the question is about a failure or a balance.
Can I fetch several transactions in one request?
Yes, a JSON-RPC batch takes up to 100 calls in one request. Send one getTransaction per signature in the batch and run compact on each answer that is not null.