---
id: SI0001
title: "Read-only model tools"
url: https://carbium.sh/library/si/read-only-model-tools
collection: AI and blockchain
category: Model tool calling
revision: 3
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Read-only model tools

Does getAccountInfo modify state? No: it reads one account, needs no signature and changes nothing. Put it behind a fixed allowlist so a model's tool call can only read, trim the answer and handle the two errors a tool loop meets.

## Does getAccountInfo modify state?

No. `getAccountInfo` is a read-only JSON-RPC method. It returns the lamports, owner, executable flag and data of one account as of the commitment you ask for; the tool file asks at confirmed commitment. It takes no signature and changes nothing on chain. `getTokenAccountBalance` is read-only in the same way, and [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) uses it to read a token balance. A model that can call only those two methods can look at the chain and do nothing else.

That is a property of the methods. Whether your agent has it depends on the code between the model and the RPC, because the model chooses what goes into the tool call, and a prompt-injected or confused model will sooner or later ask for something you did not plan for.

The endpoint will not catch that for you. Carbium serves `sendTransaction` (20 cells without preflight, 70 with it), so the endpoint answers a request for it like any other call. Methods such as `getTokenLargestAccounts`, a read method, are not served and answer -32601, so the list of served methods is not a read/write policy, and the allowlist has to live in your own code.

Three layers do the work. The tool schema tells the model what exists. A frozen allowlist maps each tool name to one fixed JSON-RPC method and refuses everything else before any network call. A trimming step decides which fields of the answer the model gets to see.

## The allowlist between the model and the network

The model never supplies a method string. It supplies a tool name and arguments, and `ALLOWED` maps the name to the method: `get_account_info` to `getAccountInfo`, `get_token_balance` to `getTokenAccountBalance`. Any other name makes `callTool` throw before `fetch` runs, so a call to `send_transaction` costs no request and reaches no network.

The lookup uses `Object.hasOwn` on a frozen object. A plain `name in ALLOWED` check would accept `constructor` and `toString`, which are inherited properties of every object.

Arguments get a shape check too. An address must be 32 to 44 base58 characters. That keeps a URL, a sentence or an injected instruction out of the params and saves a request. It does not prove the account exists; the node answers that.

> `callTool` throws on a refused name. In your loop, catch the error and send the message back as a tool result marked as an error, so the model sees the refusal and the loop carries on.

## The tool file

One file, no dependencies. Node 24 runs the TypeScript directly, and the global `fetch` does the HTTP. Set `CARBIUM_KEY` in the environment 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
// SI0001 · Read-only model tools
// https://carbium.sh/library/si/read-only-model-tools
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only Solana tools for a model's tool calls. Run: CARBIUM_KEY=... node main.ts [address]
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 address = (what: string) => ({
  type: "object",
  properties: { [what]: { type: "string", description: "Base58 address, 32 to 44 characters" } },
  required: [what],
  additionalProperties: false,
});

// JSON Schema tool definitions; some model APIs call `parameters` by another name.
export const tools = [
  { name: "get_account_info", description: "Lamports (1 SOL is 1,000,000,000), owner, executable flag and data length of one account. Read only.", parameters: address("pubkey") },
  { name: "get_token_balance", description: "Balance of one SPL token account. Wallet and mint addresses fail. Read only.", parameters: address("account") },
];

const ALLOWED: Readonly<Record<string, string>> = Object.freeze({
  get_account_info: "getAccountInfo",
  get_token_balance: "getTokenAccountBalance",
});
const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
type Failure = { error: string; retry: boolean };

async function rpc(method: string, params: unknown[], retried = false): Promise<{ result: any } | Failure> {
  const res = await fetch(url, {
    method: "POST",
    headers: { "content-type": "application/json", "x-api-key": key as string },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
  });
  if (res.status === 429) {
    await res.body?.cancel();
    if (retried) return { error: "rate limited, back off before the next call", retry: false };
    const seconds = Math.min(Number(res.headers.get("retry-after")) || 1, 10);
    await new Promise((done) => setTimeout(done, seconds * 1000));
    return rpc(method, params, true);
  }
  const body: any = await res.json().catch(() => ({}));
  if (body.error?.code === -32601) return { error: "method not available, do not retry", retry: false };
  if (body.error) return { error: String(body.error.message), retry: false };
  if (!res.ok) return { error: `HTTP ${res.status}`, retry: false };
  return { result: body.result };
}

export async function callTool(name: string, args: Record<string, unknown>): Promise<string> {
  if (!Object.hasOwn(ALLOWED, name)) throw new Error(`tool "${name}" is not allowed`);
  const target = args.pubkey ?? args.account;
  if (typeof target !== "string" || !BASE58.test(target)) throw new Error("argument is not a base58 address");
  const method = ALLOWED[name] as string;
  const config = { commitment: "confirmed", ...(method === "getAccountInfo" ? { encoding: "base64" } : {}) };
  const out = await rpc(method, [target, config]);
  if ("error" in out) return JSON.stringify(out);
  if (method === "getTokenAccountBalance") {
    const { amount, decimals, uiAmountString } = out.result.value;
    return JSON.stringify({ uiAmountString, decimals, amount });
  }
  const account = out.result.value;
  if (!account) return JSON.stringify({ error: "account not found", retry: false });
  const { lamports, owner, executable } = account;
  return JSON.stringify({ lamports, owner, executable, dataLength: Buffer.from(account.data[0], "base64").length });
}

if (import.meta.main) {
  const usdcMint = process.argv[2] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
  console.log(await callTool("get_account_info", { pubkey: usdcMint }));
  try {
    await callTool("send_transaction", { transaction: "AQAB" });
  } catch (e) {
    console.log("refused locally:", (e as Error).message);
  }
}
```

The main block runs the path a model's `tool_use` block would take. It calls `get_account_info` on the USDC mint (pass any other address as the first argument), prints the trimmed result, then calls `send_transaction` and prints the local refusal. The first line is one JSON object with `lamports`, `owner`, `executable` and `dataLength`; for the mint, `owner` is the token program and `dataLength` is 82. The second line is the refusal, printed before any request is sent.

`tools` holds the two JSON Schema definitions. Some model APIs name the schema field `parameters` and others `input_schema`; rename it where you register the tools; nothing in the schema is enforced.

## Shaping what the model sees

| Field in the RPC answer | Sent to the model | Reason |
|---|---|---|
| `lamports`, `owner`, `executable` | yes | the three facts that tell a wallet, a token account and a program apart |
| account `data` (base64) | only its byte length | bytes mean nothing to a model and fill its context |
| `context`, `apiVersion`, slot | no | bookkeeping the model cannot use |
| `value.uiAmountString`, `decimals`, `amount` | yes, in that order | for the token tool: the decimal string with the point placed, the precision, then the raw integer for exact comparisons |
| `value.uiAmount` | no | a float, redundant next to the string |

`lamports` counts billionths of a SOL: 1 SOL is 1,000,000,000 lamports. A model handed only that will divide it itself and sometimes misplace the point, so the tool description states the conversion. A token amount has the same trap, which is why `uiAmountString` goes first. Every result is one compact line of JSON, and a failure is always `{error, retry}`. The model then has one place to look for what went wrong and whether to try again.

## The two errors a tool loop meets

On a 429 the helper reads the Retry-After header as seconds, falls back to 1 s if it is missing, caps the wait at 10 s and retries once. A second 429 returns `retry: false`. Limits are per account and an account's keys share one budget, so a second 429 can come from other keys spending it; hand the model `retry: false` and let the loop back off before the next call.

On -32601, method not found, the rule is do not retry. The helper returns `{error, retry: false}` without a second request. Here it can appear only if a method in the map is misspelt or not served, but the rule costs one line and covers a later edit that extends the map.

Every other JSON-RPC error, such as a wallet address passed to `getTokenAccountBalance`, returns the node's message with `retry: false`. An address with no account behind it is not an error at all: `getAccountInfo` answers with a null value, and the helper turns that into `account not found` with the same flag. Models retry whatever looks temporary, so the flag has to be explicit in the result.

## Cost and the key

Account reads cost 10 cells each, ten times a cached read such as `getSlot`. A loop of account checks adds up, so cap tool calls per task in your loop; the allowlist does not count them.

Keep the key inside the helper, so it appears in no prompt, tool argument, tool result or log line.

## Where it ends

- The allowlist covers methods only. Text that strangers wrote on chain, such as token names and memos, can contain instructions. This file returns only numbers and addresses. A tool that returns on-chain text needs that text treated as untrusted input.
- `getAccountInfo` returns an account's raw bytes, and this file reports only their length. Reading what the bytes mean, such as a token balance or a program's state, needs that program's layout. The token tool answers for token accounts only, and a wallet's SOL balance is already in `lamports`.
- The base58 check is a shape check. A 44-character string can still decode to the wrong length, and the node rejects it.
- There is no signing here and no send tool. A tool that spends needs its own design, with a separate process and a human approval step.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A tool name such as `constructor` passes the allowlist check. | Check with `Object.hasOwn` on a frozen object. An `in` check or a plain property lookup sees inherited properties. |
| The model retries a -32601 answer in a loop. | Return `{error, retry: false}` and cap tool calls per task in your loop. A prompt that says "do not retry" is weaker than a flag in the result. |
| The model reads a lamport count as SOL, or quotes a token balance with the point in the wrong place. | Say in the tool description that 1 SOL is 1,000,000,000 lamports. For the token tool, send `uiAmountString` first and `decimals` next, keep the raw `amount` last and drop the float. |
| A second 429 arrives right after the retry. | Return `retry: false` and let the loop back off before the next call. Limits are per account, so look for other keys or services spending the same budget. |
| A missing account, or a wallet address passed to `get_token_balance`, returns the same answer every turn. | Return `account not found` or the node's message with `retry: false`, and say in the tool description that `get_token_balance` takes a token account only. |
| The key shows up in the model's context or in logs. | Read it from the environment inside the helper only. Keep it out of tool arguments, tool results, error strings and any request log. |

## Questions

### Does getAccountInfo need a signature or a keypair?

No. It is a read, so nothing is signed and no keypair is involved. The only secret in the file is your Carbium key, which goes out in the `x-api-key` header.

### Does Carbium itself block sendTransaction for a model?

No. sendTransaction is served, so the block is your allowlist, which refuses it before any request is made.

### How do I return a refused call to the model as an error?

Catch the exception from `callTool` and send its message back as the tool result, flagged as an error in your model API's format. A `{error, retry}` line that `callTool` returns normally goes back the same way, so the model reads both kinds of failure in one place.

### How many tool calls can the agent make?

Each account read costs 10 cells, and your plan's [rate limits](https://carbium.sh/docs#limits) set how many run per second. The allowlist does not count calls, so set a cap in the loop.

### How do I add another read method?

Add one line to `ALLOWED`, add a branch that trims its result, and add a tool definition. Cached reads such as `getSlot` cost 1 cell each.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
