services
Get a key

library / AI and blockchain / SI0046

Strict JSON wallet summaries

A wallet summary a program can depend on: SOL balance, token holdings, recent activity count and slot, filled from three chain reads and checked by a validator. A model writes only the one sentence.

By Carbium · Model tool calling · SI0046 · updated 2026-11-22

01

The schema

A model API's structured output mode keeps a reply inside a JSON schema. It cannot know your wallet, so a model asked for sol.lamports returns a plausible integer from nowhere. The way out is to split the object by who knows each field. Chain reads fill every number. The model writes one string, sentence, and the validator treats that string as untrusted input.

FieldTypeFilled by
asOfSlotintegerthe lower slot of the balance and token reads
sol.lamportsdigit stringgetBalance
sol.soldecimal stringcomputed from the lamports
tokens[]mint, amount, decimals, ui, accountsgetTokenAccountsByOwner
activity.countintegergetSignaturesForAddress
activity.limitintegerthe limit sent with that call
sentencestring, 1 to 240 charactersthe model

The response format you send to the model API is a one-field schema: sentence, a string of at most 240 characters. The program puts that string into the object the reads filled, then runs validate on the whole object. The object has exactly five top-level keys, and an extra key is a rejection, which catches a field added by a later code change or a hand edit. The validator is the part you can depend on, because it runs in your process after the reply arrives.

02

Which read fills which field

Three reads run together under Promise.allSettled, each at confirmed commitment. getBalance returns the lamports and the slot it read at. getTokenAccountsByOwner takes the Token program as its filter and jsonParsed encoding, so each account arrives with mint, raw amount and decimals already split out. getSignaturesForAddress with limit: 100 returns up to 100 of the newest signatures, and the length of that array is the activity count.

The reads see the chain at slightly different moments, and only the first two return a context slot. asOfSlot is the lower of those two, so a reader who sees slot N knows that no balance or holding in the summary is older than N.

One wallet can own several token accounts for the same mint. The script adds the raw amounts per mint with BigInt, records how many accounts it merged in accounts and drops mints that add up to zero. Without the merge a mint shows up twice and a model quotes whichever line it read first.

getSignaturesForAddress costs 50 cells and is limited to 0.24 req/s on Free and 1.2 req/s on Dev, so size a batch of wallets against that figure and the rate limits of your plan.

03

Validating and repairing a reply

validate returns a list of problems instead of throwing, so a failure can go back to the model as plain text. It checks the key set of every object, integer fields, digit strings, base58 mints, and that each decimal string equals what its raw amount formats to. Then it pulls every number out of the sentence and requires each one to appear among the values the reads produced: the SOL decimal, the token count, the activity count and limit, and each token's decimal amount.

That last check catches invented figures. A sentence ending "that is about 9,999 SOL" fails because 9,999 is a value nowhere in the object. A figure written in words, such as "about forty", slips through, so tell the model to use digits and keep the sentence short.

Repair is a loop of two attempts at most. Send the problem list back with the original object and ask for the sentence again. If the second reply fails, drop the model's text and keep the object with a template sentence. The numbers are identical on both paths, because the model never held them.

$The script writes its sentence from a template so the run needs no model key. A model's reply goes into the same field and meets the same validator.
04

Amounts as strings and decimals

A JavaScript number holds integers exactly up to 9,007,199,254,740,991. Raw amounts of a token with 9 decimals and a large supply can pass that, and many JSON parsers round silently. So amount and lamports are digit strings parsed with BigInt, decimals is a small integer, and ui is the decimal string: the raw digits with the point placed and trailing zeros trimmed.

fmt pads the raw string to at least one digit more than the decimals, so 5 raw units at 9 decimals reads 0.000000005, and a token with 0 decimals gets no point at all. The RPC's float uiAmount is left out of the summary, since a float is the one field here that loses digits.

Keeping both amount and ui lets the validator recompute one from the other and reject a mismatch, which catches a field that a model or a hand edit changed.

05

The script

Set CARBIUM_KEY first. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh. The reads are the kind a model calls through read-only model tools; here they run directly so the numbers never pass through a model.

main.ts
// SI0046 · Strict JSON wallet summaries// https://carbium.sh/library/si/strict-json-wallet-summaries// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Wallet summary that always validates: chain reads fill every number, a validator checks the rest.// Run: CARBIUM_KEY=... node main.ts [wallet]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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const LIMIT = 100;const commitment = "confirmed";// No argument: the fee payer of the newest readable signature on a busy program (v1 transactions included).async function findWallet(): Promise<string> {  for (const { signature: sig } of await rpc.getSignaturesForAddress(TOKEN_PROGRAM, { limit: 5, commitment }).send()) {    const tx: any = await rpc.getTransaction(signature(sig), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment }).send().catch((e) => (console.error("getTransaction failed:", String(e)), null));    const payer = tx?.transaction.message.accountKeys[0]?.pubkey;    if (payer) return payer;  }  throw new Error("no readable transaction found");}const fmt = (raw: bigint, decimals: number) => {  const s = raw.toString().padStart(decimals + 1, "0");  const frac = s.slice(s.length - decimals).replace(/0+$/, "");  return s.slice(0, s.length - decimals) + (frac ? `.${frac}` : "");};const isInt = (v: unknown) => Number.isSafeInteger(v) && (v as number) >= 0;const isStr = (v: unknown, re: RegExp) => typeof v === "string" && re.test(v);export function validate(s: any): string[] {  const bad: string[] = [];  const shape = (o: any, keys: string[], at: string) => {    const ok = !!o && typeof o === "object" && Object.keys(o).sort().join() === [...keys].sort().join();    if (!ok) bad.push(`${at}: keys must be ${keys.join(",")}`);    return ok;  };  if (!shape(s, ["asOfSlot", "sol", "tokens", "activity", "sentence"], "summary")) return bad;  if (!isInt(s.asOfSlot)) bad.push("asOfSlot: not a non-negative integer");  if (shape(s.sol, ["lamports", "sol"], "sol") && (!isStr(s.sol.lamports, /^\d+$/) || s.sol.sol !== fmt(BigInt(s.sol.lamports), 9))) bad.push("sol: lamports must be a digit string and sol its decimal form");  if (shape(s.activity, ["count", "limit"], "activity") && !(isInt(s.activity.count) && isInt(s.activity.limit) && s.activity.count <= s.activity.limit)) bad.push("activity: count must be an integer up to limit");  const tokens: any[] = Array.isArray(s.tokens) ? s.tokens : (bad.push("tokens: must be an array"), []);  if (new Set(tokens.map((t) => t?.mint)).size !== tokens.length) bad.push("tokens: a mint appears twice");  tokens.forEach((t, i) => {    if (!shape(t, ["mint", "amount", "decimals", "ui", "accounts"], `tokens[${i}]`)) return;    const fine = isStr(t.mint, /^[1-9A-HJ-NP-Za-km-z]{32,44}$/) && isStr(t.amount, /^\d+$/) && isInt(t.decimals) && t.decimals <= 255 && isInt(t.accounts);    if (!fine || t.ui !== fmt(BigInt(t.amount), t.decimals)) bad.push(`tokens[${i}]: mint, amount, decimals or ui is wrong`);  });  const known = new Set([s.sol?.sol, s.activity?.count, s.activity?.limit, tokens.length, ...tokens.map((t) => t?.ui)].map(String));  if (typeof s.sentence !== "string" || !s.sentence || s.sentence.length > 240) bad.push("sentence: must be 1 to 240 characters");  else for (const n of s.sentence.match(/\d[\d,.]*/g) ?? []) if (!known.has(n.replace(/[.,]$/, ""))) bad.push(`sentence: number ${n} is not in the reads`);  return bad;}if (import.meta.main) {  const wallet = address(process.argv[2] ?? (await findWallet()));  const [bal, held, sigs] = await Promise.allSettled([    rpc.getBalance(wallet, { commitment }).send(),    rpc.getTokenAccountsByOwner(wallet, { programId: TOKEN_PROGRAM }, { encoding: "jsonParsed", commitment }).send(),    rpc.getSignaturesForAddress(wallet, { limit: LIMIT, commitment }).send(),  ]);  if (bal.status !== "fulfilled" || held.status !== "fulfilled" || sigs.status !== "fulfilled") {    for (const r of [bal, held, sigs]) if (r.status === "rejected") console.error("read failed:", String(r.reason));    process.exit(1);  }  const byMint = new Map<string, { raw: bigint; decimals: number; accounts: number }>();  for (const { account } of held.value.value as any[]) {    const { mint, tokenAmount } = account.data.parsed.info;    const t = byMint.get(mint) ?? { raw: BigInt(0), decimals: tokenAmount.decimals, accounts: 0 };    byMint.set(mint, { ...t, raw: t.raw + BigInt(tokenAmount.amount), accounts: t.accounts + 1 });  }  const tokens = [...byMint].filter(([, t]) => t.raw > BigInt(0)).map(([mint, t]) => ({ mint, amount: String(t.raw), decimals: t.decimals, ui: fmt(t.raw, t.decimals), accounts: t.accounts }));  const lamports = String(bal.value.value);  const sol = fmt(BigInt(lamports), 9);  const count = sigs.value.length;  // A model's reply goes in `sentence`; a template stands in so this run needs no model key.  const sentence = `Holds ${sol} SOL and ${tokens.length} token holdings, with ${count} recent signatures.`;  const asOfSlot = Math.min(Number(bal.value.context.slot), Number(held.value.context.slot));  const summary = { asOfSlot, sol: { lamports, sol }, tokens, activity: { count, limit: LIMIT }, sentence };  const broken = { ...summary, sol: { ...summary.sol, lamports: Number(lamports) }, sentence: `${sentence} That is about 9,999 SOL.` };  console.log(JSON.stringify(summary, null, 1));  console.log("problems in the valid copy:", validate(summary).length);  console.log("broken copy rejected:", validate(broken).join(" | "));}

run: node main.ts

The calls go through @solana/kit, which hands back lamports and slots as bigint, so String(value) keeps every digit of a balance. With no argument the script reads the five newest signatures of the Token program and calls getTransaction on each until one answers. It sends maxSupportedTransactionVersion: 1, because mainnet carries v1 transactions and without that value the call answers -32015 for one. The first account key of the transaction is its fee payer, and that address becomes the wallet. A null transaction is skipped, and a failed call prints its error before the next try. Each getTransaction call costs 50 cells.

The output has three parts: the valid object, a count of problems found in it (0), and the rejection reasons for a broken copy that has lamports as a number and an invented figure in the sentence. A failed read prints its error and exits with 1 before any object exists, because a summary with a missing balance would not validate.

06

Where it ends

  • The activity count is the length of one page of at most 100 signatures. A count equal to the limit means there are at least that many, and the total needs paging with before.
  • The signature index keeps up to 30 days. An address with no activity in that window shows a count of 0 with no error, even when it has older transactions.
  • Only Token program accounts are read. Token-2022 holdings need a second getTokenAccountsByOwner call with that program id, and they are missing from this summary.
  • The validator checks digits and shapes. A sentence can still describe correct numbers badly, for example by calling a wallet with 3 holdings empty. The prompt and a short length limit carry that part.
  • The number check also pulls digits out of a base58 mint and out of a rounded figure such as 0.1 for 0.100799027, so a sentence that names a mint or rounds a balance is rejected. The prompt should say to quote figures exactly and leave addresses out.
  • A wallet with thousands of token accounts makes the second read large, and the script does not page it. The summary has no prices and no USD values.
07

When it goes wrong

what goes wrongwhat to do
A lamports value is a JSON number and a parser rounds it.Keep lamports and raw token amounts as digit strings, parse them with BigInt and let the validator reject any other type.
The same mint appears twice in tokens.Add raw amounts per mint before building the object. The validator rejects a repeated mint, and accounts shows how many were merged.
getTransaction answers -32015 while the script looks for a wallet.Send maxSupportedTransactionVersion: 1 in the config object. A value of 0 or none fails for a v1 transaction.
getTransaction returns null for a signature that getSignaturesForAddress just listed.Skip to the next signature. The signature pages reach below the validator's ledger floor, so an older one can list without a readable transaction. Prove the code on the newest signatures.
The sentence quotes a figure that is in no read.Send the validator's problem list back once and ask again. If the second reply fails, use the template sentence and keep the object.
One of the three reads fails and the summary gets a default of 0.Print which read failed and stop. A zero default passes the validator and is wrong.
08

Questions

Why not rely on the model API's structured output alone?

It checks the shape of the reply, and a model fills numbers it cannot see with plausible ones. Here the reads fill the numbers and the validator checks the one string the model writes.

Why is amount a string?

A JavaScript number is exact only up to 9,007,199,254,740,991, and raw token amounts can pass that. A digit string parsed with BigInt keeps every digit.

How do I count activity past 100 signatures?

Call getSignaturesForAddress again with before set to the last signature of the previous page, 100 at a time at 50 cells a call. The index reaches back 30 days at most.

Can the same validator check a reply from any model API?

Yes. It reads a plain JSON value, so it does not matter which API produced the text. Parse the reply, put its sentence into the object the reads filled, pass that object in and act on the problem list.

Which commitment do the reads use?

Confirmed, set on each call, so the three reads ask for the same level. The balance and the token read can still report different slots, which is why asOfSlot takes the lower one.