---
id: SI0032
title: "Plain-English balance comparison"
url: https://carbium.sh/library/si/plain-english-balance-comparison
collection: AI and blockchain
category: Plain-English chain queries
revision: 3
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Plain-English balance comparison

Which of these wallets holds more SOL? A model gets this wrong when it compares raw lamport strings. The tool reads every balance in one call, ranks them in code and gives the model one sentence with the gap.

## Why a model misjudges balances

A model asked which of two wallets holds more SOL can call a tool and read numbers, or it can guess from a pasted list. With a tool, the failure moves into the arithmetic. A balance arrives as lamports, an integer that can run to sixteen digits or more, and a language model compares long digit strings by their look. 4,812,000,000 and 48,120,000,000 resemble each other and differ tenfold. One misplaced decimal point turns 1.5 SOL into 15 SOL.

So the tool does the comparison. Code sorts the balances as integers, writes each as a SOL string with all nine decimals, and returns a ranked list with the gap to the leader and one plain sentence naming the winner. The model quotes that sentence and does no arithmetic of its own.

The same question comes in other forms: which wallet has more of one token, which is worth more in dollars, which grew over a week. Each needs a different read. The tool handles SOL held by two or more addresses right now.

## One call, one slot

The tool reads every address with a single `getMultipleAccounts` call at `confirmed` commitment, named in the call. All balances then come from the same slot, and the answer carries it in `context.slot`. A slot lasts about 200 ms, and an active wallet can change between two of them, so separate `getBalance` calls made one after another compare numbers from slightly different moments. One call fixes the moment for every address in the list.

The call also asks for a zero-length `dataSlice`, so the node returns lamports and no data bytes. A wallet is a system account with no data, so nothing is lost, and a mint or program address passed by mistake adds no payload.

An address that holds no lamports has no account, and the node answers null for it. A system account drained to 0 lamports is deleted, so null covers both a never-funded address and an emptied one. The code reads null as 0 and sets `accountExists: false`, which tells the model the address held no lamports at that slot. [SOL balances for many accounts](https://carbium.sh/library/howsolana/sol-balances-for-many-accounts) covers reading a long list of balances; this tool ranks them and words the result.

## The tool file

One file on @solana/kit 8.6.0, run by Node 24 straight from the TypeScript. 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`.

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

```ts
// SI0032 · Plain-English balance comparison
// https://carbium.sh/library/si/plain-english-balance-comparison
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Compare SOL balances for a model's tool call. Run: CARBIUM_KEY=... node main.ts [address ...]
import { createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress } from "@solana/kit";
import type { Address } 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 } }));

// JSON Schema tool definition; some model APIs call `parameters` by another name.
export const tool = {
  name: "compare_sol_balances",
  description: "Rank 2 to 100 Solana addresses by SOL held right now and say which holds more. Quote the summary. Read only.",
  parameters: {
    type: "object",
    properties: { addresses: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 100 } },
    required: ["addresses"],
    additionalProperties: false,
  },
};

const LAMPORTS = 1_000_000_000n;
const sol = (n: bigint) => `${n / LAMPORTS}.${String(n % LAMPORTS).padStart(9, "0")}`;

export async function compareBalances(input: unknown): Promise<string> {
  const list: unknown = (input as { addresses?: unknown } | null)?.addresses;
  if (!Array.isArray(list)) throw new Error("addresses must be an array of strings");
  const unique = [...new Set<unknown>(list)];
  if (unique.length < 2 || unique.length > 100) throw new Error("send 2 to 100 distinct addresses");
  const bad = unique.filter((a) => typeof a !== "string" || !isAddress(a));
  if (bad.length) throw new Error(`not a Solana address: ${bad.map(String).join(", ")}`);
  const addresses = unique as Address[];
  const { context, value } = await rpc
    .getMultipleAccounts(addresses, { commitment: "confirmed", encoding: "base64", dataSlice: { offset: 0, length: 0 } })
    .send();
  const rows = addresses
    .map((address, i) => ({ address, lamports: BigInt(value[i]?.lamports ?? 0n), accountExists: value[i] != null }))
    .sort((a, b) => (a.lamports === b.lamports ? 0 : a.lamports > b.lamports ? -1 : 1));
  const top = rows[0];
  const next = rows[1];
  const summary =
    top.lamports === next.lamports
      ? `The top two addresses hold the same amount, ${sol(top.lamports)} SOL.`
      : `${top.address} holds the most, ${sol(top.lamports)} SOL, which is ${sol(top.lamports - next.lamports)} SOL more than ${next.address}.`;
  const ranked = rows.map((r, i) => ({
    rank: i + 1,
    address: r.address,
    sol: sol(r.lamports),
    lamports: String(r.lamports),
    behindLeaderSol: sol(top.lamports - r.lamports),
    accountExists: r.accountExists,
  }));
  return JSON.stringify({ summary, slot: String(context.slot), commitment: "confirmed", ranked });
}

const WALLETS = [
  "5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9",
  "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
  "H8sMJSCQxfKiFTCfDR3DUMLPwcRbM61LGFJ8N4dK3WjS",
];

if (import.meta.main) {
  const given = process.argv.slice(2);
  const addresses = given.length ? given : WALLETS;
  const runs = await Promise.allSettled([compareBalances({ addresses }), compareBalances({ addresses: addresses.slice(0, 1) })]);
  runs.forEach((run, i) => {
    const label = i === 0 ? "compare:" : "one address:";
    console.log(label, run.status === "fulfilled" ? run.value : `refused: ${(run.reason as Error).message}`);
  });
}
```

The main block runs the path a model's tool call would take. It compares the addresses you pass, or three known wallets when you pass none, and prints the JSON the model would receive. It then calls the tool with a single address and prints the refusal. Both calls are settled, so one failing leaves the other's output on screen.

`tool` is the JSON Schema definition to register with your model API. Some APIs call the field `parameters` and others `input_schema`. `compareBalances` checks the arguments again itself: the list must be an array, duplicates collapse, two to 100 distinct entries are required, and every entry must pass `isAddress`. A refusal throws before any request leaves the process.

## What the model gets back

The result is one compact JSON line. The model needs the answer and the figures behind it, and nothing else from the node's reply.

| Field | Content | Why it is there |
|---|---|---|
| `summary` | one sentence naming the leader and the gap to the next address | the model can quote it without any arithmetic |
| `ranked[].sol` | balance as a string with nine decimals | no float, no rounding, the point stays in place |
| `ranked[].lamports` | the raw integer as a string | exact comparison if the model must check a claim |
| `ranked[].behindLeaderSol` | gap to the first address | answers "by how much" for every row |
| `ranked[].accountExists` | true or false | false means the address held no lamports at that slot |
| `slot`, `commitment` | the slot the read came from and the level used | lets the model say when the figures were true |

Amounts are strings because a JSON number above 2^53 loses digits in some runtimes. 2^53 lamports is about 9.007 million SOL, and a wallet holding 9300003431406335 lamports (about 9.3 million SOL) already passes it. String amounts are required for them.

When two addresses tie, the sentence says the top two hold the same amount and does not invent a winner. The sort is stable, so a tie keeps the order you sent.

## Cost and rate limits

`getMultipleAccounts` charges 10 cells per pubkey. A 100-address call costs 1000 cells, or 1001 when the request body passes 4 KiB, which 100 base58 addresses usually do. Below Pro, a rate class absorbs bursts up to 1,024 cells, so one full call fits the burst and takes nearly all of it, and a second full call right behind the first waits or gets a 429. On Pro the [burst](https://carbium.sh/docs#limits) is one second of its rate, which is larger.

The call accepts up to 300 pubkeys, but only on Pro. Below Pro the 1,024-cell burst caps a call at 100, which is why the file refuses a longer list instead of sending it. Code written for Pro can raise the cap.

Account reads run at 0.5, 15, 50 and 400 req/s on Free, Dev, Business and Pro, and limits are per account: an account's keys share one budget. A model that compares the same two wallets on every turn of a conversation spends that budget for no gain. Cache the answer for the length of the task, or tell the model in the tool description to compare once and reuse the sentence.

## Where it ends

- The tool compares SOL held directly by each address. SOL locked in other accounts the owner controls is not counted, and neither are tokens. A wallet can own several token accounts for one mint, so a token comparison sums every account for the mint through `getTokenAccountsByOwner` before it ranks anything.
- The figures are a snapshot of one slot at `confirmed`. A busy wallet changes right after, so the sentence is true for that slot. The tool returns the slot so the model can say so.
- The tool compares amounts of SOL and does not price them. A dollar comparison needs a price for the same moment, and that is a second read with its own failure modes.
- History is a different job. "Who held more last month" needs a balance series, and a snapshot read cannot answer it.
- `accountSubscribe` sends nothing for a plain SOL wallet, so to keep a comparison live, open one `logsSubscribe` per address, each mentioning that address, and call this tool when a log arrives.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The model ranks two balances wrongly, or quotes SOL with the decimal point in the wrong place. | Do the comparison in code and return `summary` and string amounts. Tell the model in the tool description to quote the sentence and not to subtract. |
| The tool throws "not a Solana address" because the model passed a wallet name, a domain or a truncated string. | Return the message to the model as an error tool result. It then asks the user for the full address instead of retrying the same string. |
| One address shows 0 SOL while the user insists it holds funds. | Check `accountExists`. A false value means the address held no lamports at that slot. A wrong address, or a funding transaction not yet at `confirmed`, are the usual causes. |
| Below Pro, a second comparison right after a 100-address one gets a 429. | Back off for the retry-after hint, then send it again. Keep lists short, and cap comparisons per task in your loop. |
| The file refuses a list of more than 100 addresses. | Split it into calls of 100 or fewer and merge the rows in code. The ranking needs one sort over all rows, so compare after merging, and note that the slots of the calls then differ. |
| The call returns 401 on every request. | Send the whole key in the `x-api-key` header, from the environment inside the file only. Keep it out of prompts, tool arguments and logs. |

## Questions

### Why use getMultipleAccounts instead of getBalance for each wallet?

One call returns every balance from the same slot, so the comparison is between simultaneous numbers.

### Can the tool compare tokens as well?

Not this file; a token comparison sums each wallet's accounts for the mint first, then ranks the sums.

### How many wallets can one call compare?

The file sends at most 100. A call can carry 300 pubkeys on Pro; below Pro the [burst](https://carbium.sh/docs#limits) caps it at 100.

### Should the model do the final sentence itself?

Let it quote `summary`. The numbers are exact there, and the model adds only the framing the user asked for. For other tool shapes see [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools).

## Related

- [SOL balances for many accounts](https://carbium.sh/library/howsolana/sol-balances-for-many-accounts) (How to use Solana, HS0016)
- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
