---
id: SI0022
title: "Agent skill for chain reads"
url: https://carbium.sh/library/si/agent-skill-for-chain-reads
collection: AI and blockchain
category: Solana agent kits
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Agent skill for chain reads

A skill folder an agent opens when a task needs chain data: a SKILL.md with its instructions and one TypeScript script that reads an account, a wallet's token holdings or an address's latest transactions, with no signing in reach.

## What a chain-read skill holds

An agent skill is a folder the agent opens when a task matches its description. It has a `SKILL.md` with a name, a one-line description and instructions, plus any scripts those instructions point to. The agent keeps only the name and description in view until a task fits, then reads the rest. For Solana reads that split works well: the description costs a few tokens in every session, and the instructions and script load when someone asks about a balance or a transaction.

A skill differs from a tool schema in who runs the code. A tool call goes through your application's loop, where you can inspect it. A skill's script runs in the agent's shell, so the agent picks the arguments and reads stdout. That makes the script the boundary: anything it can do, the agent can do. This one holds three reads and no signing, so the worst a confused agent can do with it is spend some of your request budget.

The script answers three commands: `account`, `tokens` and `recent`. Each prints one line of JSON, because stdout goes straight into the model's context and a pretty-printed account dump wastes it. If you want the same reads behind a tool loop in your own application, [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) shows the allowlist version. For the plain token balance call the skill builds on, see [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).

## The SKILL.md

Keep the file short. The agent reads it every time the skill triggers, so every line should change what the agent does. A working version has these parts:

- Front matter with `name: solana-chain-reads` and a description that names the jobs: read Solana mainnet account info, a wallet's token holdings and an address's latest transactions, read only. The description decides when the agent opens the skill, so it names the questions it answers in the words a user would use.
- The command line: `node main.ts <account|tokens|recent> [address]`, run from the folder that holds `main.ts`. One line each on what the three commands return.
- A rule about the key: `CARBIUM_KEY` is already in the environment, so never ask the user for it, never echo it and never write it to a file.
- A rule about units: 1 SOL is 1,000,000,000 lamports, and token amounts come as a raw integer plus decimals. The agent must put the decimal point itself, and a model that does mental division gets it wrong often enough to matter.
- A rule about errors: when the output has an `error` key, report it to the user and make at most one more attempt with the same arguments.
- A refusal line: the skill cannot sign, send or move funds, and the agent says so when asked.

The last line matters more than it looks. Users will ask an agent with a Solana skill to swap or send. If the file is silent, the agent improvises, often by writing its own script. A clear refusal in the instructions sends it back to the user with an honest answer.

## The script

One file on `@solana/kit` and Node's built-ins. Node 24 strips the types on load, so `node main.ts` runs it directly. The client is built once with `createDefaultRpcTransport` against `https://services.carbium.sh`, and the key leaves the process only in the `x-api-key` header. `CARBIUM_RPC_URL` overrides the endpoint when you point the skill at another one.

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

```ts
// SI0022 · Agent skill for chain reads
// https://carbium.sh/library/si/agent-skill-for-chain-reads
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only chain commands for an agent skill. Run: CARBIUM_KEY=... node main.ts <account|tokens|recent> [address]
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, 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 rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const [command, target = USDC_MINT] = process.argv.slice(2);
const print = (v: unknown) => console.log(JSON.stringify(v, (_, x) => (typeof x === "bigint" ? x.toString() : x)));

const commands: Record<string, (a: Address) => Promise<unknown>> = {
  async account(a) {
    const { value } = await rpc.getAccountInfo(a, { encoding: "base64" }).send();
    if (!value) return { error: "account not found" };
    const { lamports, owner, executable } = value;
    return { lamports, owner, executable, dataLength: Buffer.from(value.data[0], "base64").length };
  },
  async tokens(a) {
    const { value } = await rpc.getTokenAccountsByOwner(a, { programId: TOKEN_PROGRAM }, { encoding: "jsonParsed" }).send();
    const byMint: Record<string, { amount: bigint; decimals: number }> = {};
    for (const { account } of value) {
      const info = account.data.parsed.info as any;
      const sum = byMint[info.mint] ?? { amount: 0n, decimals: info.tokenAmount.decimals };
      sum.amount += BigInt(info.tokenAmount.amount);
      byMint[info.mint] = sum;
    }
    return byMint;
  },
  async recent(a) {
    const sigs = await rpc.getSignaturesForAddress(a, { limit: 3 }).send();
    const fetched = await Promise.allSettled(
      sigs.map((s) => rpc.getTransaction(s.signature, { maxSupportedTransactionVersion: 1, encoding: "json" }).send()),
    );
    return sigs.map((s, i) => {
      const r = fetched[i]!;
      if (r.status === "rejected") return { signature: s.signature, error: String(r.reason?.message ?? r.reason) };
      return { signature: s.signature, slot: s.slot, failed: s.err !== null, found: r.value !== null, fee: r.value?.meta?.fee ?? null };
    });
  },
};

if (!command || !Object.hasOwn(commands, command)) {
  console.error("Usage: node main.ts <account|tokens|recent> [address]");
  process.exit(1);
}
try {
  print(await commands[command]!(address(target)));
} catch (e) {
  print({ error: String((e as Error).message) });
  process.exitCode = 1;
}
```

`commands` is a plain object, and `Object.hasOwn` decides whether the first argument names a command, so `constructor` and other inherited names get the usage line. Any address that fails `address()` throws inside the `try`, and the catch prints it as an `error` line with exit code 1. Nothing in the file builds a method name from user input, so there is no path from the agent's arguments to a write method.

No call sets a commitment, so kit fills in `confirmed`. Say so in your own skill if exact finality matters to your users. JSON cannot hold a `bigint`, which kit uses for lamports and slots, so `print` turns each one into a string on the way out.

`tokens` asks for every account under the original Token program owned by the wallet and sums by mint. A wallet can own more than one token account for the same mint, and an agent reading the raw list would report two balances for one token. The sum stays in raw integer units with the decimals beside it, so the agent does the one division the instructions describe.

`recent` lists the three newest signatures, then fetches the three transactions in parallel with `Promise.allSettled`. One failing fetch becomes an `error` on its own row and the other two still print. With no address, the command reads the USDC mint, which has transactions every few seconds. Run it as `node main.ts recent`, or pass any address after the command.

## What account and recent cost

| Command | Methods called | Cells per run |
|---|---|---|
| `account` | `getAccountInfo` | 10 |
| `recent` (3 transactions) | `getSignaturesForAddress`, then 3 x `getTransaction` | 50 + 3 x 50 = 200 |

Cells are the admission charge per call, and `getSlot`-style cached reads cost 1. On Free, `getAccountInfo` runs at 0.5 req/s, while `getSignaturesForAddress` and `getTransaction` each run at 0.24 req/s. Each rate class absorbs a burst of up to 1,024 cells, and one `recent` run splits across two of them: 50 cells in address signatures and 150 in ledger and tx lookups. The lookups class holds about six runs in a row at 150 cells each before its 0.24 req/s Free rate takes over.

Agents loop. A user who asks for "the last 20 transactions of these 10 wallets" makes the agent run `recent` ten times and then ask for more. Put a cap in the SKILL.md, such as at most ten script runs per question, and raise `limit` in the script only when a task needs a longer list. Every key on an account draws from [one budget](https://carbium.sh/docs#limits), so a skill running in several agents shares it.

## History, nulls and transaction versions

`getSignaturesForAddress` on Carbium reads from an address index that keeps up to 30 days. Its pages reach below the validator's ledger floor, so `getTransaction` can answer `null` for an older signature the list still shows. The script maps that to `found: false` and still prints the signature, slot and failed flag from the listing, with `fee` set to null. Prove changes to the script on the newest signatures of a busy address, where every fetch returns a body.

An empty list for an address means the index holds nothing inside 30 days. The address may have older transactions. Write that into the SKILL.md in those words, because an agent left to guess will tell the user the wallet has never been used.

Mainnet carries v1 transactions. With `maxSupportedTransactionVersion` absent or 0, `getTransaction` answers -32015 for a v1 transaction, and the same holds for `getBlock` on a block that contains one. The script passes `1`, which kit 8.6.0 accepts as a typed value next to `'legacy'` and `0`. If you keep that option in a variable, declare it `as const` or the type widens to `number`.

## Where it ends

- The 30-day address index is the history limit. Older transactions of an address are not served by this command, and the agent has to say so.
- `getTokenLargestAccounts` is not served and answers -32601, which means do not retry. A question about top holders of a mint has no answer from this skill, and the instructions should tell the agent to say that.
- `tokens` filters on the original Token program. Token-2022 accounts live under a different program id and do not appear.
- The output carries raw integers and addresses. It does not name tokens, decode program data or explain an instruction; `account` reports only the length of the data.
- The SKILL.md is advice, and the script enforces the read-only part. A skill does not sandbox the agent's shell, so an agent with shell access can still read the environment where the key lives. Run the agent as a user with nothing else in reach and give it a key made for this job.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The agent asks the user to paste the API key, or prints it while debugging. | State in the SKILL.md that the key is already in the environment and must never be echoed. The script reads it from `CARBIUM_KEY`, exits with a message when it is unset and prints it nowhere. |
| `recent` returns an empty list for a wallet the user knows is old, and the agent reports that the wallet was never used. | Tell the agent that the address index keeps up to 30 days, so an empty list means nothing inside that window and older transactions may exist. |
| A row shows `found: false` for a signature that was just listed. | `getTransaction` answers null for a signature older than the validator's ledger, which the index can still list. Report the signature and slot from the listing and move on. |
| `getTransaction` fails with -32015. | The transaction is v1 and the call left `maxSupportedTransactionVersion` out or set it to 0. Pass `maxSupportedTransactionVersion: 1`, as the script does. |
| The agent asks for the largest holders of a mint and keeps retrying the error. | The method answers -32601. Add a line to the SKILL.md that top-holder lists are unavailable, and cap script runs per question. |
| `JSON.stringify` throws on a `bigint` when you add a command that returns lamports or a slot. | Send every result through `print`, which converts bigints to strings, and keep any arithmetic on raw values before that point. |

## Questions

### Why a script in a skill and not a tool definition?

A skill runs in the agent's shell, so it works in any agent that can run a command and read stdout, with no application loop. A tool definition needs your own code in the middle, which is the better place for per-call checks such as a call budget.

### What should the SKILL.md description say?

Name the jobs and the chain in the words a user would type: account info, token holdings, recent transactions, Solana mainnet, read only. The agent matches the task to this text, and a vague description makes the skill trigger late or never.

### Can the skill send a transaction or sign anything?

No. The script has no signing code, no private key input and no write method. The refusal line in the SKILL.md makes the agent say so and stop.

### How do I add a command, such as the current slot?

Add one function to `commands` that calls the method and returns a plain object, then add a line to the SKILL.md. `getSlot` is a cached read at 1 cell, so it adds almost nothing to the budget.

### Does the agent ever see the key?

Only if it reads the environment itself. The script never prints the key, and the SKILL.md tells the agent not to, but the shell can still read its own environment, so use a key made only for this agent.

## Related

- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [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#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
