services
Get a key

library / How to use Solana / HS0046

BigInt lamport amounts

One TypeScript file reads a wallet's lamports and a mint's raw supply, prints each as a bigint beside its Number twin with the rounding gap and a safe-range verdict, and parses a raw JSON-RPC body to show where digits go missing.

By Carbium · Accounts and balances · HS0046 · updated 2026-11-22

01

Where a number stops

A JavaScript number is an IEEE 754 double. It holds every integer exactly up to 2^53 - 1, which is 9,007,199,254,740,991 and is available as Number.MAX_SAFE_INTEGER. Above that, the double skips integers, and any sum or parse lands on the nearest value it has.

A lamport is the smallest unit of SOL, and 1 SOL is 1,000,000,000 lamports. So 2^53 - 1 lamports is about 9,007,199 SOL. A wallet below that fits a number today, and code that stores lamports in one passes its tests until a treasury, an exchange account or a program vault holding more shows up.

Raw token amounts reach the limit sooner. On chain a token amount is a u64, up to 18,446,744,073,709,551,615. A mint with 9 decimals and a supply of ten million tokens already holds a raw 10^16, which is past the safe range. A mint with 5 decimals needs a supply near ninety billion tokens to get there.

!Number(raw) never throws on a large value. It rounds, and the wrong figure goes on looking like a plausible one.
02

What kit hands back

@solana/kit types a lamport value as a bigint, so getBalance already gives you the exact integer. Token amounts arrive as decimal strings, which carry every digit by construction.

CallFieldJavaScript typeExact
getBalancevaluebigintYes
getTokenSupplyvalue.amountstringYes
getTokenSupplyvalue.decimalsnumberYes, it is at most a few digits
getTokenSupplyvalue.uiAmountStringstringYes
getTokenSupplyvalue.uiAmountnumber or nullNo, a float

The loss starts when your own code converts. Number(balance), parseInt(amount), parseFloat(uiAmountString) and uiAmount each squeeze the value into a double. Keep the bigint or the string until the moment a person reads it.

03

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY, and run the file with Node 24, which strips the types itself. The first argument is a wallet. The optional second argument is a mint and defaults to BONK, whose raw supply is far past 2^53.

main.ts
// HS0046 · BigInt lamport amounts// https://carbium.sh/library/howsolana/bigint-lamport-amounts// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,} from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url, headers: { "x-api-key": key } }),);const BONK = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263";const [walletArg, mintArg = BONK] = process.argv.slice(2);if (!walletArg) {  console.error("Usage: node main.ts <wallet-address> [mint-address]");  process.exit(1);}const wallet = address(walletArg);const mint = address(mintArg);const commitment = "confirmed" as const;// Exact decimal text from a raw integer: pad with zeros, split at the decimals.function format(raw: bigint, decimals: number): string {  if (decimals === 0) return raw.toString();  const digits = raw.toString().padStart(decimals + 1, "0");  return `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`;}function compare(label: string, raw: bigint) {  const viaNumber = BigInt(Number(raw));  const safe = raw <= BigInt(Number.MAX_SAFE_INTEGER);  console.log(label);  console.log(`  bigint ${raw}`);  console.log(`  Number ${Number(raw)} (back to bigint: ${viaNumber})`);  console.log(`  lost   ${raw - viaNumber}`);  console.log(`  verdict: ${safe ? "safe in a number" : "outside the safe range"}`);}const [balance, supply, body] = await Promise.allSettled([  rpc.getBalance(wallet, { commitment }).send(),  rpc.getTokenSupply(mint, { commitment }).send(),  fetch(url, {    method: "POST",    headers: { "content-type": "application/json", "x-api-key": key },    body: JSON.stringify({      jsonrpc: "2.0",      id: 1,      method: "getBalance",      params: [walletArg, { commitment }],    }),  }).then((r) => r.text()),]);if (balance.status === "fulfilled") {  const lamports: bigint = balance.value.value;  compare(`lamports of ${wallet}`, lamports);  console.log(`  as SOL ${format(lamports, 9)}`);} else console.error("getBalance failed:", balance.reason);if (supply.status === "fulfilled") {  const { amount, decimals } = supply.value.value;  compare(`raw supply of mint ${mint}`, BigInt(amount));  console.log(`  as text ${format(BigInt(amount), decimals)} (decimals ${decimals})`);} else console.error("getTokenSupply failed:", supply.reason);if (body.status === "fulfilled") {  const text = body.value;  const parsed: number | undefined = JSON.parse(text).result?.value;  const wire = /"value":(\d+)/.exec(text)?.[1];  console.log(`raw body: JSON.parse gives ${parsed}, the text holds ${wire}`);} else console.error("raw fetch failed:", body.reason);

run: node main.ts <wallet-address> [mint-address]

Three reads run together, and each is settled on its own so one failure leaves the others printed. All of them ask for confirmed. The first two go through the kit client. The third is a raw fetch of getBalance against the same endpoint, kept as text so you can compare what JSON.parse returns with the digits that were on the wire.

For each amount the output shows the bigint, the Number of it, the bigint you get back from that number, the difference, and a verdict. A small wallet prints a difference of 0 and the verdict safe in a number. The BONK supply prints a nonzero difference in the last digits. The raw body line matches the text for a balance under the limit and can drift above it.

04

Arithmetic and display

Bigint arithmetic works with +, -, *, / and %, and division truncates toward zero. Mixing the two types throws, so balance + 1 is a TypeError. Write balance + 1n, and convert on purpose when a number comes in from outside. Comparisons between a bigint and a number do work, so balance > 0 is fine.

Multiply before you divide. A 25 basis point share of a balance is balance * 25n / 10_000n, and the order matters because the division drops the remainder. Decide where the dropped lamports go before the code ships, since the remainder is real money at scale.

Display is string work. The format function in the file pads the raw integer with zeros until it has at least one digit more than the decimals, then splits the string at the decimal point. For lamports that gives format(lamports, 9), and for a token it uses the decimals field from the reply. No float is involved at any step, so the text is exact.

Convert to a number only for something that tolerates rounding, such as a chart axis. Even there, divide first in bigint to get whole SOL, then convert the small result.

05

JSON and databases

JSON.stringify throws on a bigint with Do not know how to serialize a BigInt. Send amounts as strings, the way the RPC does for tokens, and call BigInt(text) on the other side. A replacer that maps bigint values to toString() does the same for a whole object.

JSON.parse has the opposite problem. A JSON number token becomes a double, so a raw lamport figure above 2^53 - 1 is rounded before your code sees it. The kit client parses responses with this in mind. A raw fetch against the RPC endpoint does not, and the third read in the file shows it. Pull the digits out of the text with a pattern, or pass a reviver to JSON.parse and read context.source, the original text of a number token, which Node 24 provides.

For storage, a signed 64-bit integer column tops out at 9,223,372,036,854,775,807. Lamports for any account sit far below that, so a bigint column in Postgres holds them. A u64 token amount can exceed it, so use numeric(20,0) or a text column for raw token amounts. In node:sqlite, an INTEGER column is read back as a number unless the statement calls setReadBigInts(true), so turn that on or store the amount as text. A cache that goes through JSON follows the same rule: strings in, BigInt out.

06

Where it ends

The run checks the one wallet and the one mint you give it. A small wallet shows safe in a number and says nothing about the next one, so the check is the habit to keep in code and the run is a demonstration. Nothing in the file can tell you that a number column is safe for a whole table.

The balance and the supply are separate reads at confirmed, so they can come from different slots. Compare two balances only when they come from one consistent read, as in consistent reads with minContextSlot. The supply of a mint also moves when tokens are minted or burned, so a printed figure is a snapshot.

uiAmount is a float and stays one. It rounds once the raw amount passes 2^53 - 1, it is null for a mint with 20 or more decimals, and uiAmountString is the field to read. This file does not convert prices or fiat values, which need their own decimal handling.

07

When it goes wrong

what goes wrongwhat to do
TypeError: Cannot mix BigInt and other types, use explicit conversions.Put an n on the literal (balance + 1n) or convert the other operand with BigInt(value). Convert a number to bigint only when it is a whole integer.
JSON.stringify throws TypeError: Do not know how to serialize a BigInt.Send the amount as a string with toString(), or give JSON.stringify a replacer that does it. Read it back with BigInt(text).
A lamport figure from a raw fetch ends in zeros or is off by a few lamports.JSON.parse turned the number token into a double. Read the digits from the response text, or use a reviver and context.source, and build the bigint from that.
Token totals differ from the chain in the last digits.The sum used uiAmount or a parsed float. Add BigInt(amount) values and format with decimals at the end.
A database read returns a rounded amount although the stored column holds the right digits.The driver returned the column as a number. Ask it for bigint reads, as setReadBigInts(true) does in node:sqlite, or store the amount as text or numeric(20,0).
HTTP 401 with UNKNOWN_KEY.The key did not reach the door whole. Check that CARBIUM_KEY holds the complete key and goes in the x-api-key header.
08

Questions

At what balance does a number lose lamports?

Above 2^53 - 1 lamports, about 9,007,199 SOL, some values round. Every integer up to that is exact, but a total over many accounts can cross the line even when no single account does.

Is uiAmount safe to store?

No. It is a float, it rounds once the raw amount passes 2^53 - 1, and it is null for a mint with 20 or more decimals. Store amount as a string or bigint and keep uiAmountString for display.

Does the kit client ever give me a number for lamports?

No. getBalance types its value as a bigint. A number appears when your own code calls Number, parseInt or JSON.parse on a raw body.

Which column type holds a raw token amount?

A u64 can pass the signed 64-bit maximum, so use numeric(20,0) in Postgres or a text column. A plain bigint column fits lamports.