library / AI and blockchain / SI0024
Custom GPT action for chain reads
A Node service with an OpenAPI schema that a Custom GPT imports as an Action. It answers account and token balance reads from Carbium through @solana/kit, keeps the API key on your server and checks a bearer token on every call.
What the GPT calls
A Custom GPT reaches outside ChatGPT through an Action. You paste an OpenAPI schema into the GPT builder, and the model decides when to call each operation in it. ChatGPT sends the HTTP request from its own servers, so the other end has to be a public HTTPS address you control. For chain reads that means a small web service: it holds your Carbium key, accepts a plain GET with an address, and returns short JSON.
The GPT never sees the key and never builds a JSON-RPC body. It sees two operations, /account and /token-balance, each with one address query parameter. The service turns them into getAccountInfo and getTokenAccountBalance through @solana/kit and sends them to https://services.carbium.sh with the key in the x-api-key header.
Two routes keep the schema short, and a short schema is easier for the model to pick from. Each call costs 10 cells, the price of any account read.
The action server
spec is the OpenAPI document, handle maps a web Request to a Response, and createServer from node:http wraps it. Because handle never touches Node's request objects, the check can call it with no socket open. Set CARBIUM_KEY and ACTION_TOKEN, then PUBLIC_URL to the HTTPS address the GPT will reach. PORT defaults to 8787.
// SI0024 · Custom GPT action for chain reads// https://carbium.sh/library/si/custom-gpt-action-for-chain-reads// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Chain-read backend for a Custom GPT Action. Run: CARBIUM_KEY=... ACTION_TOKEN=... node main.ts [--once [address]]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import { createServer } from "node:http";const key = process.env.CARBIUM_KEY;const token = process.env.ACTION_TOKEN;if (!key || !token) { console.error("Set CARBIUM_KEY (Carbium API key) and ACTION_TOKEN (the bearer token the GPT sends)."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const publicUrl = process.env.PUBLIC_URL ?? "http://localhost:8787";const route = (operationId: string, summary: string, description: string) => ({ get: { operationId, summary, parameters: [{ name: "address", in: "query", required: true, description: "Base58 address, 32 to 44 characters", schema: { type: "string" } }], responses: { "200": { description } }, },});export const spec = { openapi: "3.1.0", info: { title: "Solana chain reads", version: "1.0.0" }, servers: [{ url: publicUrl }], paths: { "/account": route("readAccount", "Read one account: wallet, program or mint. Read only.", "lamports (1 SOL is 1,000,000,000), owner, executable, dataLength"), "/token-balance": route("readTokenBalance", "Balance of one SPL token account, never a wallet or mint. Read only.", "uiAmountString, decimals, amount"), },};const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });export async function handle(req: Request): Promise<Response> { const url = new URL(req.url); if (url.pathname === "/openapi.json") return json(200, spec); if (req.headers.get("authorization") !== `Bearer ${token}`) return json(401, { error: "bad token" }); let target; try { target = address(url.searchParams.get("address") ?? ""); } catch { return json(400, { error: "address is not a base58 public key" }); } try { if (url.pathname === "/account") { const { value } = await rpc.getAccountInfo(target, { encoding: "base64" }).send(); if (!value) return json(404, { error: "account not found" }); const dataLength = Buffer.from(value.data[0], "base64").length; return json(200, { lamports: Number(value.lamports), owner: value.owner, executable: value.executable, dataLength }); } if (url.pathname === "/token-balance") { const { value } = await rpc.getTokenAccountBalance(target).send(); return json(200, { uiAmountString: value.uiAmountString, decimals: value.decimals, amount: value.amount }); } return json(404, { error: "unknown path" }); } catch (e) { const status = (e as { context?: { statusCode?: number } }).context?.statusCode; return json(status === 429 ? 429 : 502, { error: e instanceof Error ? e.message : "rpc failed" }); }}if (import.meta.main) { if (process.argv[2] === "--once") { const probe = process.argv[3] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; const call = async (path: string, auth = true) => { const res = await handle(new Request(`http://localhost${path}`, { headers: auth ? { authorization: `Bearer ${token}` } : {} })); return `${res.ok ? "ok" : "refused"} ${await res.text()}`; }; const find = async (mint: string) => { for (const { signature } of await rpc.getSignaturesForAddress(address(mint), { limit: 5 }).send()) { const owner = (await rpc.getTransaction(signature, { encoding: "json", maxSupportedTransactionVersion: 1 }).send())?.transaction.message.accountKeys[0]; const found = owner && (await rpc.getTokenAccountsByOwner(owner, { mint: address(mint) }, { encoding: "base64" }).send()).value[0]; if (found) return found.pubkey; } }; console.log("spec paths:", Object.keys(spec.paths).join(" ")); console.log(await call(`/account?address=${probe}`)); console.log(await call("/account?address=not-an-address")); console.log(await call(`/account?address=${probe}`, false)); try { console.log(await call(`/token-balance?address=${await find(probe)}`)); } catch (e) { console.log("token account lookup failed:", e instanceof Error ? e.message : e); } } else { const port = Number(process.env.PORT ?? 8787); createServer(async (req, res) => { const out = await handle(new Request(new URL(req.url ?? "/", "http://localhost"), { headers: req.headers as Record<string, string> })); res.writeHead(out.status, { "content-type": "application/json" }).end(await out.text()); }).listen(port, () => console.log(`listening on ${port}; import ${publicUrl}/openapi.json in the GPT builder`)); }}
run: node main.ts --once
node main.ts --once runs without opening a port. It prints the paths in the spec, then makes four calls. The first asks for the USDC mint with the right token and gets lamports, owner, executable and dataLength; for the mint, owner is the token program and dataLength is 82. The second sends a malformed address and is refused with an address error. The third repeats the mint with no token and is refused with a bad token error. Each refused line starts with the word refused. The fourth finds a token account on its own: it lists the newest signatures of the USDC mint, takes the fee payer of the first transaction it can read, lists that wallet's USDC token accounts with getTokenAccountsByOwner, and sends the first one to /token-balance. Its line shows uiAmountString, decimals and amount. Without --once the service listens and prints the schema URL.
Wiring it into the builder
- Run the service behind a reverse proxy or a tunnel that gives it a public HTTPS address, and set PUBLIC_URL to that address.
- In the GPT builder, open Configure, choose Create new action and import from the URL PUBLIC_URL/openapi.json.
- Under Authentication pick API key, set the auth type to Bearer and paste the value of ACTION_TOKEN.
- Add one line to the GPT's instructions: call readAccount for wallets, programs and mints, and readTokenBalance for token accounts only.
- Test in the builder preview by asking about the USDC mint address.
ACTION_TOKEN is a second secret that sits between ChatGPT and your service. It has no connection to the Carbium key, so rotating it means changing one string in the builder and one in the environment.
What the model gets back
| Route | Kit call | Fields returned |
|---|---|---|
| /account | getAccountInfo | lamports, owner, executable, dataLength |
| /token-balance | getTokenAccountBalance | uiAmountString, decimals, amount |
The service returns the fields that answer a question and drops the rest. Account data is base64 bytes that mean nothing to a model and fill its context, so only the byte length goes back. For a token balance, uiAmountString comes first because it has the decimal point placed, then decimals, then the raw amount for exact comparison.
@solana/kit 8.6.0 hands back lamports as a bigint, which JSON.stringify refuses, so the service converts it with Number. That is exact up to 2^53 lamports, about 9 million SOL. A treasury larger than that needs the value sent as a string.
The model reads summary and the response description to decide which operation fits, so they say that 1 SOL is 1,000,000,000 lamports and that /token-balance takes a token account and never a wallet. Neither call sets a commitment, so @solana/kit 8.6.0 fills in confirmed: a balance the GPT quotes is confirmed state at the moment of the call.
Cost and rate limits
Account reads run at 0.5, 15, 50 and 400 req/s on Free, Dev, Business and Pro. A rate class absorbs a burst of 1,024 cells, about 100 account reads, so a dozen reads in one chat turn are served even on Free. A long chat that keeps fanning out uses up that burst and then gets 0.5 req/s on Free. Limits are per account and an account's keys share one budget, so a script running on another key draws on the same allowance.
The service passes a Carbium 429 straight through with the same status, and ChatGPT shows the model that the call was refused for rate. Credits meter this work as well, so a leaked ACTION_TOKEN lets a stranger spend them, and it needs the same care as the Carbium key.
Cheap cached reads such as getSlot cost 1 cell each, a tenth of an account read. A route for the current slot adds almost nothing to the bill, and it answers the common question of how fresh the data is.
Where it ends
- ChatGPT calls your service from the internet. A laptop on localhost is out of reach, so the service needs a public HTTPS host before the builder can import anything.
- One shared bearer token is the only gate. Add a request rate limit at the proxy, and keep the Carbium key in the service environment only.
- The service is read-only: no signing, no send route, no private key. A GPT cannot move funds with it, and adding that path needs a separate design with a human approval step.
- A wallet can own more than one token account for one mint, and /token-balance reads exactly one account. A wallet-level answer needs a route that lists the wallet's token accounts first.
- The model can still misquote a number it was handed. The service returns exact strings and integers, and the GPT's wording stays outside your control.
- Text that strangers wrote on chain, such as token names, can carry instructions. These two routes return only numbers and addresses; a route that returns names must treat them as untrusted input.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The builder cannot import the schema. | Check that PUBLIC_URL is the public HTTPS address and that /openapi.json opens in a browser. The servers entry in the schema comes from PUBLIC_URL, and an http or localhost value is refused. |
| Every call returns 401. | The token in the builder differs from ACTION_TOKEN, or the auth type is set to Basic or a custom header. Use API key with the Bearer type. |
| The GPT sends a wallet address to /token-balance and gets a 502 with the node's message. | Say in the GPT's instructions that readTokenBalance takes a token account only. For a wallet's tokens, add a route over getTokenAccountsByOwner. |
| A long chat starts returning 429. | Tell the GPT to look up one address at a time, and look for other keys on the account spending the same budget. |
| The GPT quotes lamports as if they were SOL. | Keep the conversion, 1 SOL is 1,000,000,000 lamports, in the readAccount response description, where main.ts already has it, and repeat it in the GPT's instructions. |
| /account answers 404 for an address you just funded. | The read runs at confirmed, and a brand new account may not exist at that level yet. Ask again a moment later. |
Questions
Why put a service between the GPT and Carbium?
The Action would otherwise hold your Carbium key in the builder and could reach every method, sendTransaction included at 20 cells without preflight. The service fixes the methods, validates the address and keeps the key in its own environment.
Does ChatGPT run my TypeScript?
No. It sends HTTP requests described by the schema, and the code runs on whatever host you start main.ts on.
How do I add another read?
Add a path to spec, a branch in handle that calls the kit method and trims its result, and a line telling the GPT when to use it. @solana/kit gives each RPC method as a function on rpc.
How do I return lamports as a string for large balances?
In the /account branch, replace Number(value.lamports) with value.lamports.toString(), and say in the response description that lamports is a string. The string stays exact at any size.