---
id: I0159
title: "MySQL user balance reconciliation"
url: https://carbium.sh/library/integrate/mysql-user-balance-reconciliation
collection: Integrations
category: Relational databases
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# MySQL user balance reconciliation

A Node script reads up to 100 wallet addresses per call from Carbium, reads their SOL balances at confirmed commitment, and prints the difference from the ledger value your MySQL user table holds.

## What the job does

Two records hold the same money: your MySQL user table and the chain. The table keeps each user's balance as a count of lamports, the smallest unit of SOL, where 1 SOL is 1,000,000,000 lamports. The chain holds the SOL in each wallet the user controls. This script reads the chain side for a list of addresses and prints, for each one, its SOL balance and the difference from the ledger value you pass in.

It is one Node process, and `@solana/kit` is its only dependency. It takes addresses from the command line, each optionally followed by `=` and a ledger value, sends them to Carbium in groups of 100, and prints one line per address. It writes no file, holds no signing key and sends no transaction.

| Line | Meaning |
|---|---|
| `match` | The chain balance equals the ledger value. |
| `DIFF n lamports` | The chain holds n more lamports than the ledger when n is positive, and fewer when it is negative. |
| `call n: slot s` | The slot Carbium answered at for that group of addresses. |
| `call n failed` | The group got no answer, so its addresses are not printed. |

## One call for up to 100 addresses

The usual approach calls `getBalance` once per address, which is one request per user. [SOL balances for many accounts](https://carbium.sh/library/howsolana/sol-balances-for-many-accounts) covers that read on its own. Here `getMultipleAccounts` takes a list of addresses and answers all of them in one response, in the same order. Each entry is the account, or `null` when the address has no account on chain. For a plain wallet with no account, zero SOL is the right reading, so the script prints 0 and does not treat the null as an error.

Carbium serves the call on its [RPC endpoint](https://carbium.sh/docs/endpoints), with the key in the [`x-api-key` header](https://carbium.sh/docs/auth). Each pubkey costs 10 cells, so a 100-address call is 1000 cells and fits the 1024-cell burst that a rate class absorbs. A call with a body over 4 KiB costs 1001 cells for the same 100 pubkeys, so the script asks for zero bytes of account data with `dataSlice`, which keeps the response to the balance and owner.

The script asks for `confirmed` in the call. The @solana/kit default is also `confirmed`, but writing it out lets the reader see which level the balances come from: a level that a supermajority of stake has voted on.

## Feeding it the MySQL ledger

The script does not connect to MySQL, so your application runs the read and passes the rows in. A query such as `SELECT wallet_address, balance_lamports FROM user_wallets WHERE active = 1` returns the two columns. Keep `balance_lamports` as a BIGINT count of the smallest unit. A decimal SOL column loses digits in a float, and a diff of one lamport then looks like a bug in the chain read.

Pass each row as `wallet_address=balance_lamports` in the argument list. A shell has a size limit on arguments, so a list of thousands belongs in your job runner, which splits it into several runs of this script.

Balances in MySQL and on chain are read at different moments. Each output line reports the slot of its call, so store that slot with the ledger snapshot if a later diff needs to be traced.

## The script

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. Set `CARBIUM_KEY` to your key. `CARBIUM_RPC_URL` is optional and defaults to the Carbium RPC endpoint.

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

```ts
// I0159 · MySQL user balance reconciliation
// https://carbium.sh/library/integrate/mysql-user-balance-reconciliation
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import {
  address,
  createDefaultRpcTransport,
  createSolanaRpcFromTransport,
  type Address,
} from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium key.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

// Each argument is an address, optionally followed by =<ledger lamports>.
let rows: { addr: Address; expected: bigint | null }[];
try {
  rows = process.argv.slice(2).map((arg) => {
    const [text = "", ledger] = arg.split("=");
    return { addr: address(text), expected: ledger === undefined ? null : BigInt(ledger) };
  });
} catch (err) {
  console.error("Bad argument:", err instanceof Error ? err.message : err);
  process.exit(1);
}
if (rows.length === 0) {
  console.error("Usage: node main.ts <address>[=<ledger lamports>] ...");
  process.exit(1);
}

const CHUNK = 100; // below Pro, the 1024-cell burst caps a call at 100 pubkeys
const chunks: (typeof rows)[] = [];
for (let i = 0; i < rows.length; i += CHUNK) chunks.push(rows.slice(i, i + CHUNK));

const SOL = 1_000_000_000n;
let failed = 0;
let differ = 0;
for (let c = 0; c < chunks.length; c++) {
  const group = chunks[c];
  try {
    const { context, value } = await rpc
      .getMultipleAccounts(group.map((r) => r.addr), {
        commitment: "confirmed",
        encoding: "base64",
        dataSlice: { offset: 0, length: 0 }, // lamports and owner only, no data bytes
      })
      .send({ abortSignal: AbortSignal.timeout(10_000) });
    console.log(`call ${c + 1}: slot ${context.slot}`);
    value.forEach((acct, i) => {
      const row = group[i];
      if (!row) return;
      // A null account has no lamports on chain, so it reads as 0.
      const lamports = acct ? BigInt(acct.lamports) : 0n;
      let verdict = "";
      if (row.expected !== null) {
        const diff = lamports - row.expected;
        if (diff !== 0n) differ++;
        verdict = diff === 0n ? " match" : ` DIFF ${diff} lamports`;
      }
      const sol = `${lamports / SOL}.${(lamports % SOL).toString().padStart(9, "0")} SOL`;
      console.log(`${row.addr} ${lamports} lamports (${sol})${verdict}`);
    });
  } catch (err) {
    failed++;
    console.error(`call ${c + 1} failed:`, err instanceof Error ? err.message : err);
  }
}
if (failed > 0 || differ > 0) process.exitCode = 1;
```

## Run it against real accounts

The example run uses three public mainnet accounts: the wrapped SOL mint, the SPL Token program and the System program. Each holds SOL on chain, so the output shows real numbers. None of them needs a ledger value, so the first run prints balances and no `match` or `DIFF` lines.

Then add one of your own wallets with its ledger value, in the form `WALLET=LEDGER_LAMPORTS`. A `DIFF` line gives the difference in lamports at the slot printed on its call. The script sets its exit code to 1 when a call failed or a row differs, so a scheduler can alert on the exit code alone.

## What it costs against your limits

A 100-address call costs 1000 cells. [Account reads](https://carbium.sh/docs/rpc) of this kind are capped per second: 0.5 calls 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 shares one budget, and an app that already reads accounts spends from the same budget this script does.

The script sends its groups one after another, so a long list does not add a burst of its own. On Free, a second group can arrive before the rate refills, which is the case the failures section covers.

## Where it ends

- It reads native SOL balances only. SPL token balances sit in token accounts, and a wallet can own more than one token account for one mint, so they need their own reads.
- It reads balances now, at confirmed commitment. It does not return a balance at an earlier moment.
- A null reads as zero. An address typo and a closed account look the same, so check the address list before a diff is trusted.
- It writes nothing to MySQL. Any correction to the ledger is a separate step in your application.
- Each call sees one slot, but the groups run in turn, so two groups in one run can report different slots.
- It reads only the addresses it is given. A user with several wallets needs each wallet in the list, and the sum belongs in your ledger query.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Every call answers 401 with UNKNOWN_KEY, and the log shows `call 1 failed:` with the status. | The key is wrong or cut short. Attach the whole key in the `x-api-key` header, then run again. |
| A group answers 429, and its addresses are missing from the output with the call marked as failed. | A call over its rate waits once if its cells refill within 1 s, then gets 429 with a retry-after hint. Wait the hinted time and rerun only the addresses in the failed group, or move the key to a plan whose rate for this class fits the run: 15 req/s on Dev, 50 on Business, 400 on Pro. |
| Every row shows a DIFF about a billion times too large. | The ledger value was stored in SOL. Store `balance_lamports` as a BIGINT count of lamports and pass integers after the `=`. |
| A user who funds a wallet shows 0 SOL and no account. | The address in your table is not the wallet the user funds. Check it against the wallet the user shows, since a null reads as zero by design. |
| A run on a plan below Pro fails on a list of 300 addresses. | Below Pro, the burst caps a call at 100 pubkeys, so keep `CHUNK` at 100 on those plans. Pro takes up to 300 pubkeys in one call, so `CHUNK` can be raised only on Pro. |
| Some addresses from the list never appear in the output. | The shell cut the argument list short. Split the list through your job runner, as the MySQL section describes, and check that the printed lines match the rows you sent. |

## Questions

### Why not call getBalance for each user?

Each getBalance call answers one address, so 10,000 users means 10,000 requests. This script sends one request for every 100 addresses, which cuts the request count by the same factor.

### What does a null mean for a user with no SOL?

The address has no account on chain, and for a plain wallet that means zero SOL. The script prints 0, so a ledger value of 0 matches.

### Does the slot printed match the time in MySQL?

No. The slot is the one Carbium answered at for that group, and MySQL keeps its own timestamp. Store the slot with your snapshot if a later DIFF has to be traced.

### Can this reconcile token balances too?

Not with this script, which reads native SOL balances only. Token balances need their own account reads, and a wallet can hold more than one token account for the same mint, so sum them per mint in your ledger query.

## Related

- [SOL balances for many accounts](https://carbium.sh/library/howsolana/sol-balances-for-many-accounts) (How to use Solana, HS0016)
- [Wallet balance reconciliation](https://carbium.sh/library/usecase/wallet-balance-reconciliation) (Use cases, UC0007)
- [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)
