library / Integrations / Web frameworks / I0098
Vue account data composable
One reader returns lamports, owner, executable flag and raw bytes for an address, and tells a missing account from a failed read. A Vue composable fetches it from your own route and keeps only the newest answer.
Keep the key on a server
A Vue component that calls Carbium straight from the browser puts the key in the page, where anyone can copy it and draw on your account's budget. The read belongs behind a route of your own. The component fetches /api/account/<address>, the route holds CARBIUM_KEY in its environment and answers with plain JSON. Because the route sits on your origin, the browser also needs no cross-origin setup.
The reader below is the route's half. It has no Vue in it and runs under Node 24, so a Nuxt server handler, an Express route or a serverless function can import it unchanged. The composable on the page side stays thin: it calls the route, holds the answer and drops any answer that arrives late.
What one read returns
readAccount(address) makes a single getAccountInfo call with base64 encoding and returns a small object. The same shape comes back for every address, so the component renders one state machine for all of them.
| Field | Type | Holds |
|---|---|---|
| exists | boolean | False when the address has no account on chain, for example a wallet that never received SOL. |
| lamports | bigint or undefined | The balance in lamports. One SOL is 1,000,000,000 lamports. |
| owner | string or undefined | The program that owns the account. A system wallet shows the System program; a token mint shows the Token program. |
| executable | boolean or undefined | True for a program account. |
| bytes | Buffer or undefined | The account data, decoded from base64. |
| slot | bigint | The slot the answer was read at. |
A missing account is a normal answer. The RPC returns a null value for it, and the reader turns that into exists: false so the component can show an empty state. A thrown error is kept for real failures such as a bad key or a network problem.
Both reads pass confirmed commitment and base64 encoding from one OPTS object, so the single read and the list read always ask for the same thing.
The reader file
Run npm install @solana/[email protected], mark the package "type": "module" and use Node 24, which strips types as it loads. CARBIUM_KEY must be set or the file exits with a message. Copy everything down to toJson into the server route; the lines after it are a command-line demo.
// I0098 · Vue account data composable// https://carbium.sh/library/integrate/vue-account-data-composable// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address as toAddress, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (!apiKey) { console.error("CARBIUM_KEY is not set."); process.exit(1);}const client = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey }, }),);const CHUNK = 100; // a call below the Pro plan carries at most 100 addressesconst OPTS = { commitment: "confirmed", encoding: "base64" } as const;export interface AccountView { address: string; slot: bigint; exists: boolean; lamports?: bigint; owner?: string; executable?: boolean; bytes?: Buffer;}interface Row { lamports: bigint; owner: string; executable: boolean; data: unknown;}function shape(addr: string, slot: bigint, row: Row | null): AccountView { if (row === null) return { address: addr, slot, exists: false }; const raw = Array.isArray(row.data) ? row.data[0] : row.data; const { lamports, owner, executable } = row; return { address: addr, slot, exists: true, lamports, owner, executable, bytes: Buffer.from(String(raw), "base64") };}export async function readAccount(addr: string): Promise<AccountView> { const res = await client.getAccountInfo(toAddress(addr), OPTS).send(); return shape(addr, res.context.slot, res.value);}export async function readMany(addrs: string[]): Promise<AccountView[]> { const views: AccountView[] = []; for (let from = 0; from < addrs.length; from += CHUNK) { const group = addrs.slice(from, from + CHUNK); const res = await client.getMultipleAccounts(group.map(toAddress), OPTS).send(); group.forEach((addr, n) => views.push(shape(addr, res.context.slot, res.value[n]))); } return views;}// Safe for JSON: slot and lamports become decimal strings, bytes become base64.export function toJson(view: AccountView) { return { ...view, slot: view.slot.toString(), lamports: view.lamports?.toString(), bytes: view.bytes?.toString("base64") };}function line(view: AccountView): string { const head = `${view.address.slice(0, 4)}..${view.address.slice(-4)} @${view.slot}`; if (!view.exists) return `${head} missing`; const whole = (view.lamports ?? 0n) / 1_000_000_000n; const frac = String((view.lamports ?? 0n) % 1_000_000_000n).padStart(9, "0"); return `${head} ${whole}.${frac} SOL, owner ${view.owner?.slice(0, 4)}.., ${view.bytes?.length} bytes${view.executable ? ", executable" : ""}`;}const given = process.argv.slice(2);const list = given.length > 0 ? given : [ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "11111111111111111111111111111111",];const [single, batch] = await Promise.allSettled([readAccount(list[0]), readMany(list)]);const failed: string[] = [];if (single.status === "fulfilled") console.log(line(single.value));else failed.push(`getAccountInfo: ${single.reason instanceof Error ? single.reason.message : single.reason}`);if (batch.status === "fulfilled") for (const v of batch.value) console.log(line(v));else failed.push(`getMultipleAccounts: ${batch.reason instanceof Error ? batch.reason.message : batch.reason}`);for (const f of failed) console.error(`failed ${f}`);if (failed.length === 2) process.exitCode = 1;
run: node main.ts [address ...]
With no arguments the demo reads three well-known accounts: the USDC mint, the Token program and the System program. It sends the first one through readAccount and the whole list through readMany, and each call settles on its own, so a failure in one leaves the other's lines on screen. Pass your own addresses to read them instead. The USDC mint shows an owner starting Toke and 82 bytes of data. The two programs show executable, owned by their loaders.
toJson is the step that makes the result safe to send. A lamport count can pass 2^53, where a JavaScript number drops digits, and JSON.stringify throws on a bigint. The route sends the slot and the lamports as decimal strings and the bytes as base64, and the component calls BigInt() only where it does arithmetic.
The composable around it
The Vue side is a function that takes a ref holding an address and returns refs for the answer. It needs no library beyond Vue and fetch.
- State: data for the last good answer, error for the last failure and pending while a request runs. Keep the previous data on screen during a reload, so the number does not flash empty.
- Trigger: a watch on the address ref with immediate: true. When the address changes, start a new request at once.
- Late answers: give each request a counter value, or an AbortController, and apply a response only if it is still the newest. A slow answer for the previous address would otherwise land after the new one and overwrite it.
- Sharing: keep a module-level map from address to the in-flight promise. Ten components that show the same address then make one call, and the map entry is removed when the promise settles.
- Refresh: expose a refresh() function and call it after the user's own action, such as a confirmed payment. Avoid a timer per component.
The sharing step matters on the lower plans. An account read is 10 cells, and a Free account is held to 0.5 account reads a second, Dev to 15, Business to 50 and Pro to 400, shared by all of the account's keys. A page that mounts a dozen components with the same address and no sharing makes twelve calls where one would do, and at Free's 0.5 a second that is 24 seconds of budget for one lookup.
Many addresses in one call
A list view that shows balances for twenty addresses should send one getMultipleAccounts call and not twenty getAccountInfo calls. The response carries one slot for the whole list, so every row comes from the same moment. Twenty separate calls can land in different slots, and rows can then disagree with each other.
readMany sends at most 100 addresses a call and walks longer lists in chunks of 100. That limit comes from the call cost: getMultipleAccounts charges 10 cells per pubkey, so 100 pubkeys cost 1000 cells, and a call over a 4 KiB body costs 1001. The method takes up to 300 pubkeys, but that size belongs to Pro, since below Pro the 1024-cell burst caps a call at 100.
Results come back in the order you sent the addresses, with null in the place of a missing account, which readMany turns into exists: false. Keep a list you show twice in the same order and key the rows by address.
Where it ends
- The composable pulls and never pushes. An accountSubscribe sends nothing for a plain SOL wallet, so a live balance for one needs a logs subscription on the wallet's address as a trigger and a fresh readAccount after each notification. Open that on the server, and send the browser an event.
- bytes is raw account data. Turning it into fields means reading the program's layout yourself; Account info response fields shows what else the response carries.
- Token balances live in token accounts, a different read; React token balance provider sums them per mint for a wallet.
- The reader has no cache of its own. Add one in the route if the same address is asked for more than once a second.
- Everything here is read-only. Nothing signs or sends.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The key shows up in the browser's network tab. | The component called Carbium directly. Move the call into a route on your server, keep CARBIUM_KEY in that server's environment and have the component fetch the route. |
| The component shows an error for an address that has never been funded. | A missing account is a normal answer. Read exists from the reader and show an empty state, and keep the error state for a thrown failure. |
| The route throws Do not know how to serialize a BigInt. | lamports and slot are bigints and bytes is a Buffer. Send the object through toJson, which turns them into strings, and rebuild a bigint in the component with BigInt() where arithmetic needs one. |
| The page shows the previous address's balance after a quick change. | A slow answer for the first address landed after the second. Stamp each request with a counter, or abort the old one, and apply only the newest response. |
| The route answers 401. | Carbium does not know the key it received. Check that the whole key reaches the x-api-key header from the server's environment, with no trailing space or line break. |
| A list of many addresses fails or stops at 100 rows. | A call below Pro carries at most 100 addresses. readMany already chunks by 100, so check that the list reaches it whole and that the route does not cut it. |
Questions
Why not call Carbium from the browser with a second key?
Anyone can read a key in the page source and use it. Limits are per account and every key on it shares one budget, so a second key fences nothing off. A route of your own keeps the key out of the page and lets you add caching and input checks.
Why base64 and not jsonParsed?
Base64 works for every account, with the bytes you can decode yourself. jsonParsed only fills in fields for account types the node knows, and falls back to base64 for the rest, so a component that expects fields breaks on the first custom program.
Do I need a library for the Vue part?
No. A ref, a watch and fetch are enough. A query library helps if you already use one, since it brings request sharing and stale-answer handling, but the reader behind the route is the same.
Why send lamports as a string?
The total supply of SOL in lamports is far above 2^53, so a JavaScript number can drop digits on large accounts. A string keeps every digit across the JSON boundary.