services
Get a key

library / AI and blockchain / Solana agent kits / SI0123

Typed agent actions from Codama

Codama clients wrap Kit's fetch and decode calls. This file does the same by hand for an SPL token mint: one batched fetch, an owner and size check, and a typed result an agent action can return as JSON.

By Carbium · Solana agent kits · SI0123 · updated 2026-11-23

01

Fetching and decoding with Kit

Codama turns a program's IDL into a TypeScript client built on Solana Kit. For each account type it emits a decoder, a fetch function and a fetchAll function, and those wrap the same two Kit steps: fetch the raw account, then decode its bytes. For the token program a generated client already exists: @solana-program/token is built by Codama and exports fetchMint, fetchAllMint and getMintDecoder. You can see how those work without the generated package, and a program an agent has to read often has no published client anyway. The file below writes by hand the decoder Codama would emit for an SPL token mint, using only Kit.

The fetch step is fetchEncodedAccounts, which calls getMultipleAccounts. Each answer is an encoded account with its address, its owner program (programAddress) and its raw bytes, or a record with exists set to false when nothing lives at the address. Kit fills in confirmed commitment when a call leaves it out. The file passes commitment: "confirmed" anyway, so the line says what it does.

The decode step is a struct of fixed-size fields in the order the program wrote them. A mint is 82 bytes: an optional mint authority (a 4-byte flag, then 32 bytes), the supply as a u64, the decimals as a u8, an initialized flag and an optional freeze authority. getNullableDecoder with a u32 prefix and noneValue: "zeroes" reads the optional fields and gives null when the flag is zero. Supply decodes to a bigint. JSON cannot carry one, so the file prints it as a string.

02

The decoder file

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. Pass any addresses as arguments. With none, it reads three: the USDC mint, the wrapped SOL mint and the System Program account.

main.ts
// SI0123 · Typed agent actions from Codama// https://carbium.sh/library/si/typed-agent-actions-from-codama// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Fetch accounts with Solana Kit and decode an SPL token mint. Run: CARBIUM_KEY=... node main.ts [address ...]import {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  fetchEncodedAccounts,  getAddressDecoder,  getBooleanDecoder,  getNullableDecoder,  getStructDecoder,  getU32Decoder,  getU64Decoder,  getU8Decoder,} 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 } }));// The decoder a Codama client would emit for an SPL token mint: 82 bytes.const optionalAddress = () => getNullableDecoder(getAddressDecoder(), { prefix: getU32Decoder(), noneValue: "zeroes" });const mintDecoder = getStructDecoder([  ["mintAuthority", optionalAddress()],  ["supply", getU64Decoder()],  ["decimals", getU8Decoder()],  ["isInitialized", getBooleanDecoder()],  ["freezeAuthority", optionalAddress()],]);// Layouts are trusted per owner program and per byte length.const TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";const layouts = new Map([[TOKEN_PROGRAM, { kind: "mint" as const, size: 82, decoder: mintDecoder }]]);export async function describeAccounts(addresses: string[]) {  if (addresses.length > 100) throw new Error("send at most 100 addresses per call");  const accounts = await fetchEncodedAccounts(rpc, addresses.map((a) => address(a)), { commitment: "confirmed" });  return accounts.map((a) => {    if (!a.exists) return { address: a.address, error: "account not found" };    const layout = layouts.get(a.programAddress);    if (!layout || a.data.length !== layout.size) {      return { address: a.address, error: `no decoder for owner ${a.programAddress}, ${a.data.length} bytes` };    }    const mint = layout.decoder.decode(a.data);    return { address: a.address, kind: layout.kind, ...mint, supply: String(mint.supply) };  });}if (import.meta.main) {  const targets = process.argv.length > 2    ? process.argv.slice(2)    : [        "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC mint        "So11111111111111111111111111111111111111112", // wrapped SOL mint        "11111111111111111111111111111111", // System Program: no decoder      ];  try {    for (const line of await describeAccounts(targets)) console.log(JSON.stringify(line));  } catch (e) {    console.error("fetch failed:", (e as Error).message);    process.exit(1);  }}

run: node main.ts

The USDC mint and the wrapped SOL mint come back as decoded JSON lines with kind set to mint, decimals 6 and 9, and the supply as a string. The System Program line is a refusal, because that account belongs to a different owner and has no decoder in the registry. All three addresses travel in one getMultipleAccounts call, so the refusal costs no extra request.

03

Match owner and size before decoding

Anyone can create an account under their own program and fill it with any bytes, including bytes that decode cleanly as a mint. Decoding by length alone would let such an account answer as a real one. The registry is keyed by owner program, and each entry carries the byte length of its layout. An account is decoded only when both match.

CheckWhat it catchesWhat the action returns
exists is truean address with no account, or one that was closedaccount not found
owner is the token programan account owned by another program, whatever its bytesno decoder for owner
data length is 82a different layout under the same owner, such as a token accountno decoder for owner with the length
decode succeedsbytes too short for the structthe thrown error, caught by the caller

A mint with Token-2022 extensions is longer than 82 bytes and belongs to a different program, so it is refused until you add a layout for it. A token account has its own struct (mint, owner, amount, delegate and more) and takes its own layout under the same owner, which means the registry holds a list per owner. Token account layout decoder walks through that layout.

04

Returning the result from an agent action

The function returns one object per requested address: either a decoded record with a kind field or an error string. A model reading a tool result needs that single shape. It can branch on kind for a mint and on error for everything else, and it never sees raw bytes or a stack trace.

The TypeScript type comes from the decoder, so a field you rename in the struct shows up as a compile error in the code that reads it. That is the same benefit a generated Codama client gives you, held in about twenty lines. When a program does have an IDL, a generated client replaces the hand-written struct. Keep the owner check in your own code around it, because a generated fetch decodes whatever bytes it gets without comparing the owner. On-chain IDL retrieval for models covers fetching an IDL for a model.

Keep the list of addresses an action accepts short and explicit. The file refuses more than 100 in one call, which is the cap that fits every plan.

05

What a decode costs

Account reads cost 10 cells each. getMultipleAccounts charges 10 cells per pubkey, so the default three addresses cost 30 cells in a single call, and a full 100-pubkey call costs 1000 cells (1001 when the request body passes 4 KiB). Up to 300 pubkeys per call is a Pro plan figure. Below Pro, the 1,024-cell burst caps a call at 100 pubkeys, which is why the file stops there.

A loop of single getAccountInfo calls spends the same cells per account and sends one request each. One batched call keeps the request count at one. Account reads are limited to 0.5, 15, 50 and 400 requests per second on Free, Dev, Business and Pro, and a batched call counts as one request. These rate limits are per account, so every key on it shares them.

06

Where it ends

  • The registry holds one layout, the classic token mint. Token accounts, Token-2022 mints and any other program need their own struct and size.
  • No Codama package runs here. The file shows what a generated client does. An Anchor account starts with an 8-byte discriminator, and a generated decoder reads it as a plain field, so compare it to the expected value before trusting the rest. A token mint has no discriminator.
  • A read at confirmed commitment is a snapshot. A supply or authority can change in the next slot, so a decoded record is a view from the moment of the read.
  • Bytes shorter than the decoder make it throw, and a decoder shorter than the account ignores the tail. The length check stops both before decode runs.
  • The file reads and decodes only. It signs nothing and sends nothing.
07

When it goes wrong

what goes wrongwhat to do
A mint decodes with a wrong supply or an authority that is not an address.Check the field order and widths against the on-chain layout. The optional fields take a 4-byte flag plus 32 bytes. A 1-byte prefix shifts every field after it.
JSON.stringify throws on a decoded record.Supply and other u64 fields decode to bigint. Convert them to strings before serializing, as the file does for supply.
An account owned by an unknown program decodes into plausible numbers.Look up the layout by owner program first and compare the data length to the layout's size. Refuse anything that does not match.
A call with more than 100 addresses fails or is refused.Split the list into groups of 100. Below Pro the 1,024-cell burst caps one getMultipleAccounts call at 100 pubkeys.
A closed or never-created address ends the run with a thrown error.Test exists on each answer before reading programAddress or data, and return account not found for the others.
The call returns 401 on the first request.Send the whole key in the x-api-key header. A truncated or unknown key is refused at the door.
08

Questions

Do I need the Codama packages to decode accounts with Kit?

No. A Codama client is generated code on top of Kit's fetchEncodedAccount, decodeAccount and codec functions. Writing the struct yourself, as this file does, gives the same typed result for a layout you already know.

What commitment does the fetch use?

Confirmed. Kit fills in confirmed when a call leaves commitment out, and the file sets it explicitly. The JSON-RPC server's own default is finalized, so a client that sends nothing and a Kit call can differ.

Why a registry keyed by owner program?

The runtime lets only an account's owner program write its data, so the owner tells you which program wrote the bytes. A layout is trusted only for accounts that program owns.

How do I add a token account decoder?

Add a second struct with the 165-byte token account fields, and make the registry map the token program to a list of layouts, each with its own size. The size check then picks the mint or the token account.