library / Integrations / Web frameworks / I0100
Vite Buffer-free RPC reads
A read-only file that fetches a wallet's SOL and token accounts through Carbium and decodes the account bytes with atob and DataView. The decoding runs unchanged in a Vite page and in Node and never touches Buffer.
Where the Buffer error comes from
Node ships a global Buffer. A browser does not, and Vite does not add one: it leaves Node built-ins out of the browser bundle, so a line that calls Buffer.from throws Buffer is not defined the first time it runs. The error turns up on wallet pages because a few paths in code written for @solana/web3.js 1.x build byte arrays through Buffer, and a library you installed can do the same.
The read side of an app needs none of it. An RPC response hands account data back as base64 text, and the browser already decodes base64 (atob) and reads integers out of bytes (DataView). @solana/kit 8.6.0 works on Uint8Array throughout, so a page that reads through kit and decodes with those two has no reason to reach for a polyfill.
The file further down reads a wallet's SOL balance and its first token accounts, decodes each token account's raw bytes itself and compares the decoded amount with the amount the RPC server parsed. Nothing in it touches Buffer. The decoding functions run the same in a Vite module and in Node 24; only the key, argument and exit handling at the top uses Node's process.
Decoding account data without Buffer
A token account of the original Token program starts with a fixed layout. Three fields matter for a balance.
| Offset | Field | Read with |
|---|---|---|
| 0 to 31 | Mint address | getAddressDecoder().decode on a 32-byte slice |
| 32 to 63 | Owner address | The same decoder on the next slice |
| 64 to 71 | Amount | DataView.getBigUint64(64, true) |
The amount is a little-endian unsigned 64-bit integer. The second argument true selects little-endian, and leaving it out reads the bytes big-endian and gives a wrong number with no error. getBigUint64 returns a bigint, so a large balance keeps every digit, where a JavaScript number drops digits above 2^53.
The account is requested with encoding: "base64". kit types the answer as a pair of the text and the encoding name, so the text sits at data[0]. atob turns it into a binary string and Uint8Array.from maps each character to its byte. The DataView is given the array's byteOffset and byteLength explicitly, because a subarray or a decoder's output can be a view into a larger buffer, and a view built without the offset reads the wrong bytes.
The reads
getBalance and getTokenAccountsByOwner go out together through Promise.allSettled, so a failure in one leaves the other's result in place. The token list uses jsonParsed encoding, which gives each account's address and a server-parsed amount. The code then reads up to three of those accounts with getAccountInfo as raw base64 and decodes them itself. Each of those is an account read at 10 cells, so three accounts cost 30 cells on top of the list call.
The balance, list and account reads pass confirmed commitment. The demo's signature and transaction reads leave it out, and @solana/kit 8.6.0 fills in confirmed for them. The server parsed the list at one moment and the raw read happened a moment later, so a wallet that moves tokens between the two reads can show a mismatch that is only a changed balance.
With no argument the demo asks getSignaturesForAddress for the newest signatures of the USDC mint and reads them with getTransaction at maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and a read with that setting absent or 0 answers -32015 for one. The signature list comes from an address index that keeps up to 30 days and reaches below the validator's ledger floor, so getTransaction can return null for an older signature it lists. The demo reads only the newest and skips a null.
The 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. Pass a wallet address, or leave it out and the demo picks a recent USDC holder.
// I0100 · Vite Buffer-free RPC reads// https://carbium.sh/library/integrate/vite-buffer-free-rpc-reads// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder } from "@solana/kit";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 TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");type Parsed = { parsed: { info: { tokenAmount: { amount: string } } } };const why = (e: unknown) => (e instanceof Error ? e.message : String(e));// atob and DataView exist in every browser and in Node, so Buffer is never needed.const fromBase64 = (text: string) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));// Token account bytes: mint at 0, owner at 32, amount at 64 as a little-endian u64.async function readTokenAccount(pubkey: string) { const { value } = await rpc.getAccountInfo(address(pubkey), { commitment: "confirmed", encoding: "base64" }).send(); if (!value) throw new Error("account is closed"); const bytes = fromBase64(value.data[0]); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); return { mint: getAddressDecoder().decode(bytes.subarray(0, 32)), raw: view.getBigUint64(64, true) };}// No argument: take a holder from the newest USDC mint transactions.async function findWallet(): Promise<string> { const sigs = await rpc.getSignaturesForAddress(USDC, { limit: 10 }).send(); for (const s of sigs) { try { const tx = await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send(); const hit = tx?.meta?.postTokenBalances?.find((b) => b.mint === USDC && b.owner); if (hit?.owner) return hit.owner; } catch (e) { console.error("getTransaction:", why(e)); } } throw new Error("no USDC holder in the newest transactions");}async function show(owner: string) { const who = address(owner); const [sol, list] = await Promise.allSettled([ rpc.getBalance(who, { commitment: "confirmed" }).send(), rpc.getTokenAccountsByOwner(who, { programId: TOKEN_PROGRAM }, { commitment: "confirmed", encoding: "jsonParsed" }).send(), ]); console.log(`wallet ${owner.slice(0, 4)}..${owner.slice(-4)}`); if (sol.status === "fulfilled") console.log(`lamports ${sol.value.value}`); else console.error("getBalance failed:", why(sol.reason)); if (list.status === "rejected") return console.error("getTokenAccountsByOwner failed:", why(list.reason)); const first = list.value.value.slice(0, 3); const reads = await Promise.allSettled(first.map((a) => readTokenAccount(a.pubkey))); reads.forEach((r, i) => { if (r.status === "rejected") return console.error(`getAccountInfo failed: ${why(r.reason)}`); const parsed = (first[i].account.data as unknown as Parsed).parsed.info.tokenAmount.amount; const same = r.value.raw.toString() === parsed ? "match" : "differ"; console.log(`${r.value.mint} decoded ${r.value.raw}, server parsed ${parsed}, ${same}`); });}const arg = process.argv[2];(arg ? Promise.resolve(arg) : findWallet()).then(show).catch((e) => { console.error(why(e)); process.exitCode = 1;});
run: node main.ts [wallet address]
It prints the wallet, its lamports, then one line per token account with the mint, the amount decoded here, the amount the server parsed and whether the two match.
Moving it into a Vite page
Copy fromBase64 and readTokenAccount into a module, with the rpc they call, and import them from your components. Three points change in the browser.
- Do not ship the key. Anything in the bundle, including a VITE_ variable, is readable by every visitor, and the key carries your account's budget. Point the transport at a small route of your own that adds the x-api-key header, as in Edge worker RPC reads, and give createDefaultRpcTransport that route's URL.
- Keep reads out of the wallet's signing path. Reading needs no wallet at all, so a balance can render before anyone connects.
- If a dependency still needs Buffer, find the importer from the first line of the stack trace before adding anything. The last resort is the buffer npm package: assign its Buffer export to globalThis.Buffer in a module of its own and import that module on the first line of your entry file. An assignment written in the entry file itself runs only after every import has loaded, too late for a library that reads Buffer as it loads. Fix the importing library when you can, since the polyfill adds weight to every page.
Where it ends
- Sending a transaction is outside this file. Everything here is read-only, and the signing code that tripped on Buffer is the code you have to fix or polyfill in your own app.
- The list asks for the original Token program only. A Token-2022 token account keeps the same first 165 bytes and puts extension data after them, so the same offsets read it; list those accounts with a second getTokenAccountsByOwner call on the Token-2022 program id. A token account decoder is covered by Token account layout decoder.
- The decoder takes the first three accounts only, to keep the demo short. The list call already returns every account, so reading more of them is a matter of raising that slice.
- The raw read costs 10 cells an account. When the server's parsed amount is all you need, skip the second read.
- Names, logos and prices come from other sources.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The page still throws Buffer is not defined after switching the reads to kit. | The remaining caller is another library or your signing code. Open the first frame of the stack trace to find the importer, replace that call with Uint8Array and DataView, or assign the buffer package's Buffer to globalThis.Buffer in a module the entry file imports first. |
| The decoded amount is huge or does not match the parsed amount. | The getBigUint64 call is missing the second argument true, so the bytes read big-endian. Check also that the DataView was built with the array's byteOffset and byteLength. |
| getAccountInfo answers null for a token account the list just returned. | The account was closed between the two reads. The demo reports it as a failed read and carries on with the others. |
| The call answers 401. | The key is unknown at the door. Check that the whole key reaches the x-api-key header from the environment, and that a browser build is not sending the header from a variable that Vite left empty. |
| The call answers 429. | The account is over its rate. Its keys share one budget, so a page that reads on every render burns it. Cache the result and read again on a wallet change. |
| A getTransaction call of your own answers -32015. | The read is missing maxSupportedTransactionVersion: 1 and the transaction is v1. Set it on every getTransaction and getBlock call. |
Questions
Does Vite have a setting that defines Buffer for me?
Not by default. Plugins exist that inject a polyfill, but they add weight and hide which library needed it. Reads through kit need none, so remove the cause first.
Can I decode with `Buffer.from(data, "base64")` in Node and `atob` in the browser?
One code path is simpler. atob and Uint8Array.from exist in Node 24 as well, so the same function runs in both and a test in Node proves the browser code.
Why decode by hand when the server returns parsed data?
Parsed encoding is fine for token accounts. Hand decoding covers account types the server does not parse and shows how little a read needs, since the same three lines work for any fixed layout.
Is it safe to call the RPC endpoint straight from the page?
A key in the bundle is public. Send the browser's calls through a route of your own that attaches the key, and keep the key in that server's environment.