library / Integrations / I0038
GraphQL dApp data API
A Node file that takes one GraphQL-style query for a dApp page, gathers every account it names into one getMultipleAccounts call, runs the other fields beside it, and returns one JSON answer, printed once or served on a port.
What the file does
A dApp page rarely needs one value. It wants the current slot, a handful of accounts, a mint's supply and the latest activity for an address, and the usual way to get them is one request per value. This file puts a single endpoint in front of Carbium RPC that takes one query naming all of those and returns one JSON object shaped like the query.
The query language is a small subset of GraphQL, parsed by about twenty lines in the file, so the only dependency is @solana/kit. Before any field runs, the executor collects every account field in the query, removes duplicate addresses, and starts one read with getMultipleAccounts in chunks of 100. The other fields run beside that read, and only the account fields wait for it. The sample query below has five root fields and costs four RPC calls, and the file prints both numbers.
| Field | Arguments | RPC method | Returns |
|---|---|---|---|
| slot | none | getSlot | the slot as a string |
| account | address | getMultipleAccounts, shared by every account field | lamports, owner, executable, or null when the account does not exist |
| supply | mint | getTokenSupply | amount, decimals, uiAmountString |
| activity | address, limit (at most 50) | getSignaturesForAddress | signature, slot, ok, blockTime for each entry |
The query it accepts
A field takes arguments in parentheses and a selection in braces. A name before a colon is an alias, and the answer is keyed by alias, so usdc: account(address: "...") { lamports owner } and pool: account(address: "...") { owner } can sit in one query without overwriting each other.
- A selection picks keys from the result. A key the field does not have comes back as null.
- Slots, lamports and token amounts come back as strings, since they are 64-bit values and a JSON number loses precision past 2^53.
- Each root field fails alone. A field that throws returns null, and its message goes into an errors array beside data, so one bad address does not blank the page. A malformed address is left out of the batch and fails only its own field with not fetched.
- Variables, fragments, directives and introspection are left out.
Batching the account reads
Carbium's getMultipleAccounts takes up to 300 pubkeys, and that size is Pro's. Below Pro the 1,024-cell burst caps a call at 100 pubkeys, so the file sends at most 100 a call and splits a longer list into chunks. On a Pro key you can raise CHUNK at the top of the file to 300.
The charge stays at 10 cells per pubkey, the same as getAccountInfo for each address alone. Twenty accounts cost 200 cells either way. What batching removes is nineteen calls and round trips, and the page waits on one read instead of twenty. For a first look at the same call by itself, see SOL balances for many accounts.
Every call in the file leaves commitment out, and @solana/kit 8.6.0 fills in confirmed for such a call, so each field reads at confirmed. The account fields carry no slot, and a cached account can be up to 2 seconds old, so the slot field and the accounts beside it can describe different moments.
A small in-memory cache keeps each account for 2 seconds. A second page load inside that window skips the RPC call for addresses it already holds. Each request copies its cache hits and its fetched results into its own map, and the account fields read that map, so another request evicting an entry mid-flight cannot empty a field. Only account results are cached, and the cache lives in the process, so two instances behind a balancer each keep their own.
An account read of a mint returns the token program as owner. A wallet's token balances need getTokenAccountsByOwner, and one wallet can own more than one token account for the same mint, so a balance field would have to sum them.
The file
Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. The file reads CARBIUM_KEY and exits with a message when it is missing. CARBIUM_RPC_URL and PORT are optional. Two addresses can follow on the command line, a program and a mint, and the sample query is built from them.
// I0038 · GraphQL dApp data API// https://carbium.sh/library/integrate/graphql-dapp-data-api// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress } from "@solana/kit";import { createServer } from "node:http";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1); }const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key },}));const CHUNK = 100; // pubkeys per getMultipleAccounts call: 100 below Pro, up to 300 on Prolet calls = 0; const send = <T>(r: { send: () => Promise<T> }) => { calls++; return r.send(); };const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));type Row = Record<string, unknown> | null; type Field = { alias: string; name: string; args: Record<string, unknown>; sel: Field[] };function parse(src: string): Field[] { const t = src.match(/"(?:[^"\\]|\\.)*"|-?\d+|[A-Za-z_]\w*|[{}()[\]:,]/g) ?? []; let i = 0; const value = (): unknown => { const x = t[i++]; if (x === "[") { const out: unknown[] = []; while (i < t.length && t[i] !== "]") { out.push(value()); if (t[i] === ",") i++; } i++; return out; } return x.startsWith('"') ? JSON.parse(x) : /^-?\d/.test(x) ? Number(x) : x; }; const set = (): Field[] => { const out: Field[] = []; i++; while (i < t.length && t[i] !== "}") { let name = t[i++]; const alias = t[i] === ":" ? name : ""; if (alias) { i++; name = t[i++]; } const args: Record<string, unknown> = {}; if (t[i] === "(") { i++; while (i < t.length && t[i] !== ")") { const k = t[i++]; i++; args[k] = value(); if (t[i] === ",") i++; } i++; } out.push({ alias: alias || name, name, args, sel: t[i] === "{" ? set() : [] }); if (t[i] === ",") i++; } i++; return out; }; if (t[0] === "query") t.shift(); return set();}const pick = (o: Record<string, unknown>, sel: Field[]) => Object.fromEntries(sel.map((f) => [f.alias, o[f.name] ?? null]));const cache = new Map<string, { at: number; v: Row }>();async function loadAccounts(addrs: string[]) { const now = Date.now(), got = new Map<string, Row>(); for (const [k, e] of cache) if (e.at < now - 2000) cache.delete(k); for (const a of addrs) { const e = cache.get(a); if (e) got.set(a, e.v); } const need = [...new Set(addrs)].filter((a) => isAddress(a) && !got.has(a)); for (let n = 0; n < need.length; n += CHUNK) { const chunk = need.slice(n, n + CHUNK); const res = await send(rpc.getMultipleAccounts(chunk.map(address), { encoding: "base64" })); chunk.forEach((a, j) => { const v = res.value[j], row = v && { lamports: v.lamports.toString(), owner: v.owner, executable: v.executable }; cache.set(a, { at: now, v: row }); got.set(a, row); }); } return got;}async function resolve(f: Field, loaded: Promise<Map<string, Row>>): Promise<unknown> { const a = f.args; if (f.name === "slot") return (await send(rpc.getSlot())).toString(); if (f.name === "account") { const hit = (await loaded).get(String(a.address)); if (hit === undefined) throw new Error("not fetched"); return hit && pick(hit, f.sel); } if (f.name === "activity") { const rows = await send(rpc.getSignaturesForAddress(address(String(a.address)), { limit: Math.min(Number(a.limit ?? 5), 50) })); return rows.map((r) => pick({ signature: r.signature, slot: r.slot.toString(), ok: r.err === null, blockTime: r.blockTime?.toString() ?? null }, f.sel)); } if (f.name === "supply") { const s = (await send(rpc.getTokenSupply(address(String(a.mint))))).value; return pick({ amount: s.amount, decimals: s.decimals, uiAmountString: s.uiAmountString }, f.sel); } throw new Error(`unknown field ${f.name}`);}async function execute(query: string) { const roots = parse(query); const errors: string[] = []; const loaded = loadAccounts(roots.filter((f) => f.name === "account").map((f) => String(f.args.address))) .catch((e: unknown) => { errors.push(`accounts: ${msg(e)}`); return new Map<string, Row>(); }); const entries = await Promise.all(roots.map(async (f) => { try { return [f.alias, await resolve(f, loaded)] as const; } catch (e) { errors.push(`${f.alias}: ${msg(e)}`); return [f.alias, null] as const; } })); return { data: Object.fromEntries(entries), ...(errors.length ? { errors } : {}) };}if (process.env.PORT) { createServer(async (req, res) => { let body = ""; for await (const c of req) body += c; const out = await Promise.resolve().then(() => execute((JSON.parse(body) as { query: string }).query)).catch((e: unknown) => ({ errors: [msg(e)] })); res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(out)); }).listen(Number(process.env.PORT), "127.0.0.1");} else { const [program = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4", mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"] = process.argv.slice(2); const q = `{ slot usdc: account(address: "${mint}") { lamports owner } prog: account(address: "${program}") { owner executable } supply(mint: "${mint}") { amount decimals } activity(address: "${program}", limit: 3) { signature slot ok } }`; console.log(JSON.stringify(await execute(q), null, 2)); console.log(`rpc calls: ${calls} for 5 root fields`);}
run: node main.ts
Run it once, then serve it
node main.ts <program> <mint> prints the answer to the sample query, the errors array when something failed, and the line rpc calls: 4 for 5 root fields. With no addresses it falls back to a busy program and the USDC mint.
With PORT set the file listens on 127.0.0.1 and takes a POST with a JSON body such as {"query": "{ slot }"}, answering with the same object. The key stays on the server. Your pages send queries to this endpoint and never see the Carbium key. The listener has no login of its own, so put your app's auth or a reverse proxy in front before anything outside the machine can reach it.
What a page costs against your limits
A page that asks for 20 accounts, the slot and one activity list spends 200 cells on the accounts, 1 on the slot and 50 on the signatures, plus the supply read if the query has one. The two reads that matter on a small plan are the account class and the signatures class.
| Plan | Account reads (req/s) | getSignaturesForAddress (req/s) |
|---|---|---|
| Free | 0.5 | 0.24 |
| Dev | 15 | 1.2 |
| Business | 50 | 100 |
| Pro | 400 | 500 |
The account class is drawn in 10-cell reads, so a call with 20 pubkeys uses 20 reads of a class that refills at 0.5 a second on Free. The 1,024-cell burst lets that call through at once, and the class then needs about 40 seconds to refill.
The file caches only account results, which is what keeps repeat page loads off that class. Limits are per account, so every key on the account draws from one budget. A page that builds a query from user input should cap the number of root fields before it runs them.
Where it ends
- It is a subset of GraphQL with four fields. Client tools that fetch a schema by introspection find none, and the parser is lenient: a query with a missing closing brace still runs.
- It wires no token balances for a wallet, no parsed account data and no transactions. Add each as another branch of resolve.
- activity reaches back 30 days at most. An empty list for an old address does not mean it never had transactions.
- It reads on request. Live updates need a WebSocket subscription, and accountSubscribe sends nothing for a plain SOL wallet, so use logsSubscribe with a mention plus getBalance there.
- The cache lasts 2 seconds in one process and drops stale entries each time accounts load, and nothing limits one caller to a number of accounts or fields.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every field comes back null, and errors holds an accounts: entry that mentions HTTP error (401) beside the same error for slot, supply and activity. | The key is unknown at the door, so every call fails alike. Set CARBIUM_KEY to the whole key and restart; the file sends it in x-api-key. |
| An errors entry such as activity: ... HTTP error (429) shows up under load while the other fields answer. | The account is over the rate for that class. Cache activity per address for a few seconds, and let the page pause before it asks again. On Free the signatures class runs at 0.24 req/s. |
| The answer says unknown field. | Only slot, account, supply and activity exist. Add a branch to resolve for another, and a method Carbium does not serve answers -32601, so check the method first. |
| Two account fields in one query return a single result. | The answer is keyed by alias, and the second unaliased field replaces the first. Give each one an alias. |
| activity returns an empty list for an address that has history. | The list covers only the last 30 days. An address that has been quiet for longer can come back empty while older transactions exist. |
| Every account field errors with not fetched while slot answers. | The account read failed as a whole, and the accounts: entry in errors says why. A query naming over 100 addresses splits into chunks, and on a plan below Pro a long list can trip the burst cap. Send fewer addresses per query. If only one field fails this way, its address is malformed. |
Questions
Why a hand-written parser and not a GraphQL library?
Four fields need no schema, and keeping the dependency list to @solana/kit keeps the file short. If you already run a full GraphQL server, keep its schema and copy the one idea here: collect the account addresses first, read them in one getMultipleAccounts call, then resolve.
Does batching lower what I spend?
No. getMultipleAccounts charges 10 cells per pubkey, the same as separate account reads. You save calls and round trips, and the page waits on one read.
Can the endpoint push updates to the browser?
Not as written. Carbium's WebSocket takes account and logs-mention subscriptions, which open at 25 credits and then cost 20 credits per MiB sent. Run those on the server and push through your own channel, or poll this endpoint.
Why are slots and lamports strings?
Both are 64-bit integers and JSON numbers lose precision past 2^53. Strings keep every digit, and the client can turn them into BigInt.