services
Get a key

library / Blockchain ideas / BI0042

Max sendable SOL calculator

A wallet can send everything or keep its account open, and nothing in between. You get the two maximums computed from balance, fee and rent minimum, a recipient check for new addresses, and a main.ts that prints all of it from live reads.

By Carbium · Payment tools · BI0042 · updated 2026-11-22

01

What the error means

The runtime checks every account a transaction touched once it has run. Each one has to end in one of two states: zero lamports, or at least the rent-exempt minimum for its data size. Anything from 1 lamport up to just under the minimum is refused, and the whole transaction fails.

The error text names an account by index: Transaction results in an account (0) with insufficient funds for rent. Index 0 is the fee payer, which is the sender in a plain transfer. Index 1 is the recipient. The index tells you which side to fix, and the two fixes are different.

A max button trips index 0 when it works from a rounded or stale balance, or reserves a fee different from the one the network charges. The sender ends with a small remainder such as 5,000 lamports, and the check refuses it.

$A system account that ends at zero lamports stops existing. That is why ending at exactly zero is allowed: nothing is left to be underfunded.
02

The three numbers

Everything follows from three amounts in lamports. One SOL is 1,000,000,000 lamports.

NumberWhat it isCall
BalanceLamports the sender holds nowgetBalance
FeeCost of this exact message: 5,000 lamports per signature plus any priority feegetFeeForMessage
Rent minimumWhat an account with no data must hold to stay opengetMinimumBalanceForRentExemption with 0 bytes

On mainnet the node reports 650,240 lamports for a zero-byte account. The rate is a cluster setting, so read it live. Rent-exempt minimum calculator covers accounts that hold data.

The fee comes from pricing the real message. Build the transfer unsigned, compile it against a recent blockhash, and ask the node what it costs. A transfer has one signature, so the base fee is 5,000 lamports. A compute unit price instruction adds to that, and the node's answer includes it, which a fixed 5,000 would miss.

03

Send everything or keep the account

The sender has exactly two valid ways to finish, and each gives one maximum.

ChoiceAmount sentSender ends with
DrainBalance minus fee0 lamports, the account closes
Keep openBalance minus fee minus rent minimumExactly the rent minimum

Take a wallet holding 2,000,000 lamports, a fee of 5,000 and a minimum of 650,240. Draining sends 1,995,000. Keeping the account open sends 1,344,760, and the sender keeps 650,240.

Every amount between those two fails. Sending 1,990,000 leaves 5,000 after the fee. That is above zero and below 650,240, so the check refuses it on account 0.

Which maximum a product shows is a design choice. Drain suits a payout or a wallet closing for good. Keep-open suits a user who will send again, since an emptied wallet needs funding before it can pay a fee. When balance minus fee is below the minimum, keep-open has no positive answer and the calculator prints 0.

04

The recipient check

The recipient follows one rule: after the transfer its balance must be zero or at least the minimum. A wallet that already holds the minimum accepts any amount, even 1 lamport. An address that has never been funded starts at zero, so its first transfer has to be at least the minimum.

Sending 500,000 lamports to an unfunded address fails on account 1 with the same message. The sender did nothing wrong, and its own arithmetic was right.

This catches the drain case too. A sender with 600,000 lamports can drain 595,000, which is a legal end state for the sender and still too small for a new address. The wallet has to refuse and say what the recipient needs: the rent minimum, read from the node.

The calculator reads the recipient's balance and prints a verdict for each maximum, naming the account index that would fail. With no recipient given it generates an address that has never held anything, so the new-address rule shows up in the first run.

05

The build

One file, @solana/kit and what Node 24 ships. It is read-only: nothing is signed and nothing is sent.

  1. Take a sender and a recipient from the command line. With no sender, read a recent block and use the fee payer of its first transaction.
  2. Settle four reads together: sender balance, rent minimum for 0 bytes, latest blockhash and recipient balance. A failed read prints its error and stops the run before any arithmetic.
  3. Build a transfer message with a placeholder amount, compile it, and send its bytes to getFeeForMessage.
  4. Print balance, fee, the maximum for drain, the maximum for keep-open and a rent verdict for each.
main.ts
// BI0042 · Max sendable SOL calculator// https://carbium.sh/library/blockchainideas/max-sendable-sol-calculator// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  AccountRole, address, appendTransactionMessageInstruction, compileTransaction, createDefaultRpcTransport,  createSolanaRpcFromTransport, createTransactionMessage, getAddressDecoder, getBase64Decoder, pipe,  setTransactionMessageFeePayer, setTransactionMessageLifetimeUsingBlockhash, type Address,} from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (!apiKey) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": apiKey },  }),);// With no sender given, take the fee payer of a transaction in a recent block.async function recentFeePayer(): Promise<Address> {  const slot = await rpc.getSlot().send();  for (let back = 2n; back < 12n; back++) {    try {      const block = await rpc        .getBlock(slot - back, { transactionDetails: "accounts", rewards: false, maxSupportedTransactionVersion: 1 })        .send();      const txs = (block?.transactions ?? []) as unknown as { transaction: { accountKeys: { pubkey: string }[] } }[];      if (txs[0]) return address(txs[0].transaction.accountKeys[0].pubkey);    } catch {      // a skipped slot has no block: try the one before    }  }  throw new Error("no recent block with a transaction found");}// Price a one-signature transfer: built unsigned, compiled, sized by the node.async function transferFee(from: Address, to: Address, lifetime: Parameters<typeof setTransactionMessageLifetimeUsingBlockhash>[0]) {  const data = new Uint8Array(12);  const view = new DataView(data.buffer);  view.setUint32(0, 2, true); // System Program: transfer  view.setBigUint64(4, 1n, true); // the amount does not change the fee  const accounts = [{ address: from, role: AccountRole.WRITABLE_SIGNER }, { address: to, role: AccountRole.WRITABLE }];  const instruction = { programAddress: address("11111111111111111111111111111111"), accounts, data };  const message = pipe(    createTransactionMessage({ version: 0 }),    (m) => setTransactionMessageFeePayer(from, m),    (m) => setTransactionMessageLifetimeUsingBlockhash(lifetime, m),    (m) => appendTransactionMessageInstruction(instruction, m),  );  const encoded = getBase64Decoder().decode(compileTransaction(message).messageBytes);  const fee = await rpc.getFeeForMessage(encoded as Parameters<typeof rpc.getFeeForMessage>[0]).send();  return fee.value;}const sender = process.argv[2] ? address(process.argv[2]) : await recentFeePayer();const recipient = process.argv[3] ? address(process.argv[3]) : getAddressDecoder().decode(crypto.getRandomValues(new Uint8Array(32)));const [balance, minimum, latest, target] = await Promise.allSettled([  rpc.getBalance(sender).send(),  rpc.getMinimumBalanceForRentExemption(0n).send(),  rpc.getLatestBlockhash().send(),  rpc.getBalance(recipient).send(),]);if (balance.status !== "fulfilled" || minimum.status !== "fulfilled" || latest.status !== "fulfilled" || target.status !== "fulfilled") {  for (const r of [balance, minimum, latest, target]) if (r.status === "rejected") console.error(`call failed: ${r.reason}`);  process.exit(1);}const fee = await transferFee(sender, recipient, latest.value.value);if (fee === null) {  console.error("getFeeForMessage returned null: the node does not know the blockhash.");  process.exit(1);}const cost: bigint = fee;const have: bigint = balance.value.value;const rent: bigint = minimum.value;const recipientHas: bigint = target.value.value;const drain = have > cost ? have - cost : 0n;const keepOpen = have >= cost + rent ? have - cost - rent : 0n;function verdict(amount: bigint): string {  if (amount === 0n) return "nothing to send";  const left = have - cost - amount;  const bad = [left !== 0n && left < rent && "sender (account 0)", recipientHas + amount < rent && "recipient (account 1)"].filter(Boolean);  return bad.length ? `fails the rent check on ${bad.join(" and ")}` : "passes";}console.log(`sender ${sender} balance ${have} lamports`);console.log(`recipient ${recipient} balance ${recipientHas} lamports`);console.log(`fee ${cost} lamports, rent minimum for 0 bytes ${rent} lamports`);console.log(`max for drain     ${drain} lamports: ${verdict(drain)}`);console.log(`max for keep-open ${keepOpen} lamports: ${verdict(keepOpen)}`);

run: CARBIUM_KEY=<YOUR_KEY> node main.ts [SENDER] [RECIPIENT]

The transfer instruction is built by hand so that only kit is needed: the System Program address, an instruction index of 2 as a little-endian u32, then the amount as a little-endian u64. The amount does not change the fee, so a placeholder of 1 lamport prices the real one.

The reads leave commitment out, so kit fills in confirmed. getBlock takes maxSupportedTransactionVersion: 1, because mainnet carries v1 transactions and a block holding one answers -32015 without it. Slots can be skipped, so the code tries the slots just behind the head until one has a block.

06

Priority fees and what stays behind

A transaction that adds a compute unit price costs more than 5,000 lamports. Price the message with that instruction included, because both maximums shrink by the difference. Priority fee per compute unit shows how to choose a price.

If another account pays the fee, the sender is no longer account 0 and keeps no reserve for it. Its drain amount is the full balance.

Draining the SOL leaves token accounts untouched. Each one is owned by the token program and holds its own rent deposit, which stays locked until the account is closed. They do not block the transfer. The wallet can end with no SOL to pay for closing them, though, so a send-all button should warn when the wallet holds any. Rent reclaim scanner finds them.

07

Where it ends

  • The figures hold for the moment of the read. A balance can change before the send, so a wallet rebuilds the numbers right before it asks for a signature.
  • The blockhash it prices with expires. A signed message built from old numbers can still fail.
  • It covers a plain SOL transfer from a system account. A transaction with other instructions that move lamports changes the arithmetic.
  • A recipient that is not a system account, or that holds data, has its own minimum, and a transfer into it follows that minimum.
  • It signs and sends nothing, so it never shows the landed result. Read the transaction back with Transaction status check once your wallet sends it.
08

When it goes wrong

what goes wrongwhat to do
Every call answers 401.The key is unknown at the door. Attach the whole key in CARBIUM_KEY, with no prefix cut off and no trailing space.
The fee comes back null.The node no longer knows the blockhash the message was built on. Fetch a fresh blockhash and price the message again.
getBlock answers -32015 when finding a sender.The block holds a v1 transaction and the call did not allow it. Pass maxSupportedTransactionVersion: 1 as the code does.
The send still fails on account 0 after the calculator said it passes.The real transaction carries a compute unit price the priced message did not have. Add that instruction to the priced message and rerun.
The automatically chosen sender shows a balance of 0.That payer emptied its account after the block was read. Rerun, or pass an address you hold.
The drain verdict fails on account 1 for a new address.Balance minus fee is below the rent minimum, so the recipient cannot end with a legal balance. Send to a funded address or add funds first.
09

Questions

Can I send my whole balance?

Yes, if you send balance minus the fee, which leaves the sender at zero. The recipient must still end at zero or at least the rent minimum, so an empty address needs the minimum or more.

Why does a 1 lamport transfer work to some addresses and fail to others?

An address that already holds the rent minimum stays above it after any deposit. An address with no balance would end with 1 lamport, which sits between zero and the minimum, so the check refuses it.

Does the amount change the fee?

No. The base fee depends on the number of signatures, and a compute unit price adds to it. The lamports moved do not.

How do I watch a wallet's balance so the maximum stays current?

On Carbium an accountSubscribe sends nothing for a plain SOL wallet. Use logsSubscribe with a mention of the address and call getBalance when a log arrives. See the WebSocket methods.

Does the calculator need a funded wallet?

No. It reads balances and a fee and signs nothing, so it needs your Carbium key and a sender address, or it picks one from a recent block.