---
id: I0007
title: "Edge worker RPC reads"
url: https://carbium.sh/library/integrate/edge-worker-rpc-reads
collection: Integrations
category: Serverless and edge
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Edge worker RPC reads

A Worker handler and a Node check script that read up to 20 accounts through Carbium in one call, decode token supply with DataView instead of Buffer, keep the key in a secret binding and pass a 429 on to the caller.

## Where the Buffer error comes from

The error `Buffer is not defined` means some code calls the Node `Buffer` global in a runtime that has none. A Cloudflare Worker runs on web APIs such as `fetch`, `Uint8Array` and `crypto.subtle`. `Buffer` is a Node API, so a Worker has it only when the `nodejs_compat` compatibility flag is on.

The usual callers are the 1.x line of `@solana/web3.js` and the helpers around it, which call `Buffer.from(data, 'base64')` or `readBigUInt64LE`. `@solana/kit` 8.6.0 moves bytes as `Uint8Array` and signs with Web Crypto, so a Worker built on it, with your own byte code written the same way, needs no polyfill.

- Turn on `nodejs_compat` in the Wrangler config. Workers then get a global `Buffer`. This is the quick fix when a dependency you do not control needs it.
- Keep the code free of `Buffer`. Decode base64 with `getBase64Encoder()` from `@solana/kit` and read numbers with `DataView`. The file below takes this path.

## What the Worker does

The file exports a Worker `fetch` handler and one function, `read`, that the handler calls. A request such as `GET /?address=<a>&address=<b>` carries one to 20 addresses. The handler makes one `getMultipleAccounts` call for all of them and answers with JSON: the slot the answer reflects, and for each address its lamports, its owner program, the length of its data and, for an account exactly 82 bytes long, the token supply read out of that data.

The same file runs under Node 24 as a check before you deploy. `node main.ts <address> <address>` prints the same JSON for the addresses on the command line. That branch runs only when `process.argv[1]` ends in `main.ts`, so a Worker skips it, and it is also the only code in the file that touches `process`.

Lamports and supply are `bigint` values in `@solana/kit`, and `JSON.stringify` refuses a `bigint`. The file turns them into decimal strings first, so a caller never loses precision to a JSON number.

## The Solana side: one call, bytes without Buffer

`getMultipleAccounts` takes an array of addresses and returns one entry per address, in order, with `null` for an account that does not exist. The file asks for `base64` encoding, which returns the raw account data as a base64 string.

`getBase64Encoder().encode(text)` turns that string into a `Uint8Array`. An SPL token mint is 82 bytes: a 4 byte option tag for the mint authority, the authority's 32 bytes, then the supply as an unsigned 64 bit little-endian integer at offset 36. `DataView.getBigUint64(36, true)` reads it, which is what `Buffer.readBigUInt64LE(36)` does in Node.

The call leaves commitment out, and `@solana/kit` 8.6.0 then sends `confirmed`. The `slot` in the answer is the slot the read reflects.

## The Carbium side: key, URL and one client

The [RPC endpoint](https://carbium.sh/docs#endpoints) is `https://services.carbium.sh`, and the key goes in the [`x-api-key` header](https://carbium.sh/docs#auth). The file builds its client from `createDefaultRpcTransport` and `createSolanaRpcFromTransport` and passes the key as that header. A Worker should use the header, because URLs get logged.

In a Worker the key is a secret binding and the URL a plain variable. Both arrive in the `env` argument of `fetch`, and neither is in `process.env`. Create the key with `wrangler secret put CARBIUM_KEY` and set `CARBIUM_RPC_URL` under `[vars]` in the Wrangler config. The handler never logs either one.

The file keeps the client in a module variable. A Worker keeps module state for the life of its isolate, so busy traffic shares one client and a fresh isolate builds a new one.

## The file

Install with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. For the Worker, point `main` in the Wrangler config at `main.ts`; Wrangler bundles the TypeScript. For the local check, export `CARBIUM_KEY` and pass addresses as arguments.

`main.ts` (run: `node main.ts 11111111111111111111111111111111 EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v So11111111111111111111111111111111111111112`)

```ts
// I0007 · Edge worker RPC reads
// https://carbium.sh/library/integrate/edge-worker-rpc-reads
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import {
  address,
  createDefaultRpcTransport,
  createSolanaRpcFromTransport,
  getBase64Encoder,
  isAddress,
  isSolanaError,
  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,
} from "@solana/kit";

type Env = { CARBIUM_KEY: string; CARBIUM_RPC_URL: string };

// kit moves bytes as Uint8Array and calls fetch: no Buffer anywhere below.
const connect = (env: Env) =>
  createSolanaRpcFromTransport(
    createDefaultRpcTransport({ url: env.CARBIUM_RPC_URL, headers: { "x-api-key": env.CARBIUM_KEY } }),
  );
let rpc: ReturnType<typeof connect> | undefined; // one client per isolate

export async function read(env: Env, addresses: string[]) {
  rpc ??= connect(env);
  // commitment left out: kit 8.6.0 sends confirmed
  const { context, value } = await rpc
    .getMultipleAccounts(addresses.map((a) => address(a)), { encoding: "base64" })
    .send({ abortSignal: AbortSignal.timeout(5_000) });
  const accounts = value.map((a, i) => {
    if (!a) return { address: addresses[i], found: false };
    const bytes = Uint8Array.from(getBase64Encoder().encode(a.data[0]));
    // SPL mint: u64 supply, little-endian, at offset 36 of 82 bytes. DataView, not Buffer.
    const supply = bytes.length === 82 ? new DataView(bytes.buffer).getBigUint64(36, true).toString() : undefined;
    return { address: addresses[i], found: true, lamports: a.lamports.toString(), owner: a.owner, dataBytes: bytes.length, supply };
  });
  return { slot: context.slot.toString(), accounts };
}

// The Worker entry: GET /?address=<a>&address=<b>, up to 20.
export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const list = new URL(req.url).searchParams.getAll("address");
    if (list.length < 1 || list.length > 20 || !list.every((a) => isAddress(a)))
      return Response.json({ error: "send 1 to 20 valid address parameters" }, { status: 400 });
    try {
      return Response.json(await read(env, list));
    } catch (e) {
      if (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && e.context.statusCode === 429)
        return Response.json({ error: "rate limited" }, { status: 429, headers: { "retry-after": e.context.headers.get("retry-after") ?? "1" } });
      return Response.json({ error: "read failed" }, { status: 502 });
    }
  },
};

// Node check only: node main.ts <address> <address>. Never reached inside a Worker.
if (globalThis.process?.argv[1]?.endsWith("main.ts")) {
  const key = process.env.CARBIUM_KEY;
  if (!key) {
    console.error("Set CARBIUM_KEY.");
    process.exit(1);
  }
  const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
  const out = await read({ CARBIUM_KEY: key, CARBIUM_RPC_URL: url }, process.argv.slice(2));
  console.log(JSON.stringify(out, null, 1));
}
```

## What it costs against your limits

`getMultipleAccounts` charges 10 cells per pubkey and [takes up to 300 pubkeys](https://carbium.sh/docs#rpc), 100 below Pro. The handler caps a request at 20, so one call costs at most 200 cells. A single account read costs 10 cells, and the rate for that class is 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro.

[Limits are per account](https://carbium.sh/docs#limits), so every key on the account, the Worker's included, shares one budget. A call over its rate gets a 429 with a `retry-after` hint. The handler passes that 429 and hint to its own caller, so the caller backs off. For watching the rate, see [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts). For a token balance read of one wallet, see [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).

## Where it ends

- The Node check exercises the Carbium call. The Worker wrapper follows Cloudflare's documented behaviour and has not been exercised inside the Workers runtime, so run `wrangler dev` before you rely on it.
- Any 82-byte account is read as a mint. Real code should first check that `owner` is the token program. A mint with Token-2022 extensions is longer than 82 bytes and gets no `supply`.
- This file avoids `Buffer`. It cannot fix a dependency of yours that calls `Buffer`, and for that case `nodejs_compat` stays the answer.
- It makes one call per request. Carbium takes a JSON-RPC batch of up to 100 calls, and this file does not send one.
- Nothing is cached, so every request spends Carbium cells. Add a short cache in front if the same addresses are read often.
- It reads current state on demand and holds no WebSocket subscription.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| `Buffer is not defined` still shows in the Worker log after the move to `@solana/kit`. | Another dependency calls `Buffer`. Bundle with `wrangler deploy --dry-run --outdir dist`, search the output for `Buffer`, and replace that package or turn on `nodejs_compat`. |
| `process is not defined` at start-up. | Code outside the Node branch reads `process.env`. In a Worker read the `env` argument of `fetch` instead. In this file only the Node branch touches `process`, so keep new reads inside `fetch`. |
| The Worker answers 502 with `read failed`. | The Carbium call failed with something other than a 429. Check that the secret exists on the deployed Worker with `wrangler secret list`, that it holds the key itself, and that `CARBIUM_RPC_URL` is set under `[vars]`. The key travels in `x-api-key`. |
| The Worker answers 429 with a `retry-after` header. | The account's rate for account reads is spent, often by other keys on the same account. Send fewer addresses per call, cache answers for a few seconds, or move to a plan with a higher rate. |
| The log shows -32601 for a method. | Carbium does not serve that method. `getTokenLargestAccounts` is one, and `getProgramAccountsV2` is another. -32601 means method not found, so [do not retry](https://carbium.sh/docs#errors). Read the data with `getMultipleAccounts` or another served method. |
| An address comes back with `found: false`, or with no `supply`. | A `null` entry means the account does not exist at the commitment the call used. An account whose data is not 82 bytes long has no `supply` field by design. |

## Questions

### Do I need the `nodejs_compat` flag for this file?

No. The file uses `fetch`, `Uint8Array`, `DataView` and `AbortSignal`, which a Worker has. Turn the flag on only when another dependency needs Node APIs.

### Why read the supply with DataView?

`Buffer.readBigUInt64LE` is a Node method, while `DataView` ships with every JavaScript runtime. The same lines then run in Node and in a Worker.

### Is it safe to keep the Carbium key in a Worker?

Yes, as a secret binding, since it never reaches a browser. Put your own check in front of the route, because anyone who can call the Worker spends your account's budget.

### Can one call read more than 20 accounts?

Yes. `getMultipleAccounts` takes up to 300 pubkeys on Pro and 100 below it, at 10 cells each. Raise the cap in the handler to what your plan's rate allows.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
