---
id: I0004
title: "Flutter account reads"
url: https://carbium.sh/library/integrate/flutter-account-reads
collection: Integrations
category: Mobile and desktop
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Flutter account reads

A short Node service holds your Carbium key and answers one request for a list of addresses, returning lamports, owner and data from a single call. A Flutter app fetches that over HTTP and decodes it in Dart. Read-only, with a two-second shared cache.

## Why a service sits between the app and Carbium

A Flutter app is a binary on a phone or a bundle in a browser, and anyone can unpack it. A Carbium key placed in the Dart code ships to every user. So the key stays on a server you run, and the app calls that server. The server is one Node file that takes a list of addresses, reads them from Carbium in a single call, and returns JSON that the Dart side decodes in a few lines.

There are two hops. The app sends `GET /accounts?address=...` to your service. The service sends one `getMultipleAccounts` call to the [Carbium RPC endpoint](https://carbium.sh/docs#endpoints) at `https://services.carbium.sh`, carrying your key. Nothing in the app holds a Carbium URL or a key.

The service builds one RPC client when it starts and reuses it for every request, so a client is never created per call.

## The Solana side: one call, three kinds of answer

`getMultipleAccounts` returns the slot the read was served at and one entry per address, in the order you sent them. Each entry is an account or `null`. A `null` means no account exists at that address, which is what a wallet that never received SOL looks like. The app can show a balance of zero for it.

| Entry | What it holds | What the app does with it |
|---|---|---|
| Plain wallet | `lamports` is the SOL balance, `owner` is the System Program `11111111111111111111111111111111`, `data` is empty. | Divide lamports by 1,000,000,000 for SOL. |
| Token account | `owner` is a token program, `data` holds the mint, the holder and the amount. | Read the amount from the data bytes. |
| `null` | No account at that address. | Show zero. |

Lamports come back as a bigint in `@solana/kit`. JSON has no bigint, and a JavaScript number loses digits above 2^53, so the service sends `lamports`, `space` and `slot` as strings.

The call asks for `confirmed` commitment and base64 data, and the code names both. Use one commitment for every address on a screen, so the numbers on it come from the same view of the chain.

## The Flutter side

Add the `http` package with `flutter pub add http`. Build the URL with `Uri.https(host, "/accounts", {"address": [a, b]})`, where a list value repeats the `address` key. Call `http.get`, check `statusCode`, and pass `res.body` to `jsonDecode`. The decoded map has `slot` and `accounts`, and every number in it is a string.

- Parse `lamports` with `BigInt.parse`. On Flutter web an `int` is a JavaScript number, so it loses digits above 2^53, which is a little over 9 million SOL in lamports.
- Treat a `null` entry as an account that does not exist and show zero.
- `data` is base64. `base64Decode` from `dart:convert` gives the bytes. For a standard token account the amount is the little-endian u64 at bytes 64 to 72. Combine the eight bytes with `BigInt` arithmetic, which works on every Flutter target. The [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) entry covers the token side from Node.
- Read when a screen opens and on pull-to-refresh. A timer on every open screen multiplies calls by users.

Flutter web also needs a CORS header, so set `ALLOW_ORIGIN` on the service to your site's origin. Native Android and iOS builds ignore CORS.

## The service

Install the one dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. `CARBIUM_KEY` is required, and the file exits with a message when it is missing. `CARBIUM_RPC_URL`, `PORT` (default 8787) and `ALLOW_ORIGIN` are optional. Addresses given on the command line are read once at start and printed, which checks the key before you wire up the app.

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

```ts
// I0004 · Flutter account reads
// https://carbium.sh/library/integrate/flutter-account-reads
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createServer } from "node:http";
import {
  type Address,
  createDefaultRpcTransport,
  createSolanaRpcFromTransport,
  isAddress,
  isSolanaError,
  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,
} from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const allow = process.env.ALLOW_ORIGIN; // only needed for Flutter web
const MAX = 20; // addresses per request: our own cap
const TTL_MS = 2_000;

// One client for the life of the process; the key never leaves this file.
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const cache = new Map<string, { at: number; body: string }>();

async function read(addrs: Address[]): Promise<string> {
  const id = addrs.join(",");
  const hit = cache.get(id);
  if (hit && Date.now() - hit.at < TTL_MS) return hit.body;
  const { context, value } = await rpc
    .getMultipleAccounts(addrs, { commitment: "confirmed", encoding: "base64" })
    .send({ abortSignal: AbortSignal.timeout(5_000) });
  const body = JSON.stringify({
    slot: String(context.slot),
    accounts: value.map((a, i) =>
      a && { address: addrs[i], lamports: String(a.lamports), owner: a.owner, executable: a.executable, space: String(a.space), data: a.data[0] },
    ),
  });
  if (cache.size >= 500) cache.clear();
  cache.set(id, { at: Date.now(), body });
  return body;
}

const server = createServer(async (req, res) => {
  const send = (status: number, body: unknown, extra: Record<string, string> = {}) => {
    res.writeHead(status, { "content-type": "application/json", ...(allow ? { "access-control-allow-origin": allow } : {}), ...extra });
    res.end(typeof body === "string" ? body : JSON.stringify(body));
  };
  const url = new URL(req.url ?? "/", "http://localhost");
  const list = [...new Set(url.searchParams.getAll("address"))];
  const addrs = list.filter(isAddress);
  if (url.pathname !== "/accounts" || !list.length || list.length > MAX || addrs.length !== list.length) {
    return send(400, { error: `GET /accounts?address=A&address=B (1 to ${MAX} valid addresses)` });
  }
  try {
    send(200, await read(addrs));
  } catch (e) {
    if (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && e.context.statusCode === 429) {
      return send(429, { error: "busy" }, { "retry-after": e.context.headers.get("retry-after") ?? "1" });
    }
    console.error("read failed:", e instanceof Error ? e.message : e);
    send(502, { error: "upstream failed" });
  }
});

// Addresses on the command line are read once at start, to check the key.
const demo = process.argv.slice(2).filter(isAddress);
if (demo.length) {
  try {
    console.log(await read(demo));
  } catch (e) {
    console.error("first read failed:", e instanceof Error ? e.message : e);
    process.exit(1);
  }
}
const port = Number(process.env.PORT ?? 8787);
server.listen(port, "127.0.0.1", () => console.log(`reading accounts on http://127.0.0.1:${port}/accounts`));
```

It listens on 127.0.0.1. Put a reverse proxy with TLS in front of it, since iOS and Android block plain HTTP by default. Add your app's own sign-in at that proxy or in front of it.

## What it costs against your limits

[Account reads](https://carbium.sh/docs#rpc) cost 10 cells each, and `getMultipleAccounts` charges 10 cells per pubkey and takes up to 300 pubkeys (100 below Pro). The service caps a request at 20 addresses, so one call costs at most 200 cells. The rates for the account-read class, in requests per second:

| Plan | Account reads per second |
|---|---|
| Free | 0.5 |
| Dev | 15 |
| Business | 50 |
| Pro | 400 |

[Limits are per account](https://carbium.sh/docs#limits), so every key on the account shares one budget. A call over its rate gets a 429 with a `retry-after` hint, and the service hands that on to the app. The [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) entry shows how to watch for it.

The two-second cache keys on the exact list of addresses. Ten phones that open the same screen within two seconds cost one call. Two different lists are two calls.

## Where it ends

- It reads. It signs and sends nothing and holds no private key. Signing belongs to the user's wallet.
- Updates arrive at the next fetch. Carbium's WebSocket has `accountSubscribe`, but it stays silent for a plain SOL wallet, so a live balance needs a second service that holds a socket open.
- The service has no sign-in of its own. Anyone who can reach it spends your account's budget, and the 20 address cap and the cache only soften that.
- It returns raw account data. Decoding a program's own layout is the app's job.
- `getSignaturesForAddress` costs 50 cells and reaches back 30 days at most, from Carbium's own address index. An empty page past that marks the index's age limit, and the address may have older transactions. This service does not serve it.
- The cache lives in one process. Several instances each keep their own.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The app gets a 400 with the message `GET /accounts?address=A&address=B (1 to 20 valid addresses)`. | The list is empty, has more than 20 entries, or holds a string that is not a valid address. Send each address as its own repeated `address` key and check that none has stray spaces. |
| The app gets a 429 with a `retry-after` header. | Your account's budget for account reads is spent, often by traffic on other keys of the same account. Wait the number of seconds in the header, then read less often or move to a plan with a [higher rate](https://carbium.sh/docs#limits). |
| The service answers 502 and its log shows `read failed:` with an HTTP error. | Check that `CARBIUM_KEY` holds the key itself and that `CARBIUM_RPC_URL` is unset or points at Carbium. The key goes in the `x-api-key` header. |
| Flutter web shows a CORS error in the browser console, while the Android and iOS builds work. | Set `ALLOW_ORIGIN` to the exact origin of the page, with scheme and port, and restart the service. |
| A wallet that holds USDC shows only its SOL, or zero. | A token balance sits in a token account, and the wallet address holds the SOL. Pass the token account's address, as the Flutter list above describes. |
| A method you added to the service answers `-32601`. | That method is not served: `getTokenLargestAccounts`, `getProgramAccountsV2` and a few more answer -32601, which means [method not found](https://carbium.sh/docs#errors). Do not retry. |

## Questions

### Can the Flutter app call Carbium directly?

The call works from anywhere that has the key, but then the key ships inside every build. Keep it on a server you run.

### Can I send several different methods in one request?

Carbium takes a single call or a batch of up to 100 in one POST. This service sends one `getMultipleAccounts`, which already covers many addresses in one call.

### How do I get live balances in the app?

Open a WebSocket from a service you run, with the key as `?api-key=` on `wss://services.carbium.sh`. Use `logsSubscribe` with a mention for a SOL wallet and read the balance when it fires. The app then listens to your service.

### How stale is a balance in the response?

Up to two seconds from the cache, plus the confirmation lag of the commitment you chose. The response carries the `slot` it was read at, so the app can show it.

## 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#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
