services
Get a key

library / How to use Solana / HS0044

Full-balance swap quote

One TypeScript file adds up a wallet's token accounts for one mint, then sends that total as the input amount of a Carbium swap quote. It reads and quotes only, so it needs no key pair.

By Carbium · Swap API · HS0044 · updated 2026-11-22

01

The balance becomes the amount

A swap quote asks for an input amount, and that amount is an integer in the token's smallest unit. For a full-balance swap the integer is whatever the wallet holds right now, so the quote request depends on a chain read that has to finish first. The job is two calls in order: read the balance, then put it into the quote request as the amount.

A wallet can own more than one token account for the same mint, so a single getTokenAccountBalance on the associated account can miss part of the holding. The file asks getTokenAccountsByOwner with a mint filter in jsonParsed encoding and adds up every tokenAmount.amount as a BigInt. The sum is the full balance in base units, which is the form the quote request takes.

A float such as uiAmount loses the last digits of a large balance, and a quote built from it asks for a slightly different amount than the wallet holds. Keep the amount as a string of digits from the node to the request. When you only need one known account, SPL token balance shows the narrower read.

02

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types on load. The wallet is the first argument. The mint is an optional second argument and defaults to USDC. An optional third argument is a cap in base units.

main.ts
// HS0044 · Full-balance swap quote// https://carbium.sh/library/howsolana/full-balance-swap-quote// 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 headers = { "x-api-key": key };const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers }));const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const WSOL = "So11111111111111111111111111111111111111112";const [ownerArg, mintArg = USDC, capArg] = process.argv.slice(2);if (!ownerArg) {  console.error("Usage: node main.ts <wallet-address> [mint-address] [cap-in-base-units]");  process.exit(1);}const owner = address(ownerArg);const mint = address(mintArg);type Held = {  account: { data: { parsed: { info: { tokenAmount: { amount: string; decimals: number } } } } };};// Step 1 and 2: every token account the wallet holds for this mint, summed in base units.const { value } = await rpc  .getTokenAccountsByOwner(owner, { mint }, { encoding: "jsonParsed", commitment: "confirmed" })  .send();const accounts = value as unknown as Held[];let balance = 0n;for (const a of accounts) balance += BigInt(a.account.data.parsed.info.tokenAmount.amount);const decimals = accounts[0]?.account.data.parsed.info.tokenAmount.decimals ?? 0;console.log(`${accounts.length} token account(s), balance ${balance} base units (decimals ${decimals})`);if (balance === 0n) {  console.log("Nothing held, so nothing to quote.");  process.exit(0);}// Step 3: the balance, or the cap when it is smaller, becomes the quote amount.const cap = capArg ? BigInt(capArg) : balance;const amountIn = balance < cap ? balance : cap;const dst = mint === WSOL ? USDC : WSOL;try {  const res = await fetch(url, {    method: "POST",    headers: { ...headers, "content-type": "application/json" },    body: JSON.stringify({      jsonrpc: "2.0",      id: 1,      method: "quote",      params: { src_mint: mint, dst_mint: dst, amount_in: amountIn.toString(), slippage_bps: 50 },    }),  });  const body = await res.text();  console.log(`quote HTTP ${res.status} for amount_in=${amountIn}`);  console.log(body.slice(0, 800));  if (!res.ok) process.exitCode = 1;} catch (e) {  console.error("quote failed:", e);  process.exitCode = 1;}

run: node main.ts <wallet-address> [mint-address] [cap-in-base-units]

The balance read runs at confirmed commitment. The cap exists because a full balance on a large wallet is rarely what you want to test with: the quote asks for the smaller of the balance and the cap.

@solana/kit has no quote method, so the quote goes out as a plain fetch POST of one JSON-RPC call to the same endpoint, with the same x-api-key header as the reads. amount_in is sent as a string because JSON.stringify refuses a BigInt, and a number would round once the balance passes 2^53. The output side is wrapped SOL, or USDC when the input mint is wrapped SOL. The request carries a slippage tolerance of 50 basis points, which is the file's own choice. Check the field names against the quote reference before you change them.

03

Reading the output

StepCallWhat it gives you
1getTokenAccountsByOwner with a mint filterEvery token account the wallet holds for the mint.
2Sum of tokenAmount.amountThe full balance as a BigInt, in base units.
3quote with amount_in set to the balance or the capThe route answer for exactly that amount.

The first line of output shows the account count next to the balance. A count above 1 is the case the sum exists for. The last lines show the HTTP status and the start of the quote body, so you can see which amount_in the quote was asked for.

A quote carries a router fee, platformFee, of 5 bps (0.05%), charged on chain in the transaction.

$The balance read and the quote each describe the chain at the moment it was taken, so a transfer in between makes the amount stale. Read the balance again right before you build the swap.
04

On Carbium

Quotes answer on the RPC endpoint as JSON-RPC, through four methods: quote, swap, health and prices. The balance read and the quote therefore share one URL and one key. The swap method builds an unsigned transaction that you sign and send through any RPC. This file stops one step earlier, at the quote, which is why it needs no signer.

A key must carry the QUOTE scope to call quote. A key without it can finish the balance read and still get 401 -32001 on the quote.

Each account's quote plan sets its quote rate.

Quote planPrice per monthQuotes per second
Free$010
Starter$750
Pro$28150
Elite$104500

Credits meter RPC work, so the balance read spends credits. The quote plane spends none, because its plan is the meter. A loop that quotes many wallets spends its plan's quote rate on the quotes and its credits on the balance reads.

05

Where it ends

The file quotes and does nothing else. It cannot move a token, and the swap you build afterwards is a new request against a newer state of the chain, so its amounts can differ from the quote.

It reads token accounts only. Native SOL is a lamport balance on the wallet itself, read with getBalance, and a wrapped SOL balance sits in a token account like any other mint. Swapping all of a native SOL balance leaves nothing for fees or rent, so subtract a reserve before the quote. The same subtraction works for a token if you want to leave some behind: reduce amountIn by the reserve in base units.

A wallet that holds none of the mint gets a zero total, and the file stops there without calling quote. A zero from the node can mean the wallet never received the mint or closed its accounts, and the read cannot tell which.

A very large balance can ask for more than a route can absorb in one go. The quote shows how that amount would fare. If the answer is poor, rerun with a lower cap and compare, or split the amount into several smaller quotes.

06

When it goes wrong

what goes wrongwhat to do
The file prints 0 token account(s) for a wallet that holds the token.Check the mint address, and check that the first argument is the wallet that owns the token accounts. The filter matches accounts whose owner is the wallet and whose mint is the one you gave.
The quote answers 401 with -32001 while the balance read worked.The key lacks the QUOTE scope. Give the key that scope in your account and run again.
The balance read (getTokenAccountsByOwner) throws an HTTP 401 UNKNOWN_KEY error before any quote is sent.The key is wrong or cut short. Attach the whole key in the x-api-key header.
TypeError: Do not know how to serialize a BigInt.A BigInt went into JSON.stringify as it is. Convert it with .toString() before it enters the request body.
HTTP 429 on the quote.The account is over its quote rate for its plan. Space the calls out, or move to a plan with a higher quotes per second.
07

Questions

Why sum token accounts instead of reading one?

A wallet can own several token accounts for one mint, and only the sum is its full balance. Reading the associated account alone can understate the holding.

Why does the quote amount use base units?

Base units are exact integers, so the amount you send is the amount the wallet holds. A decimal or float adds a rounding step that can change the last digits.

Does the quote use credits?

No. The quote plane spends no credits, since the quote plan is its meter. The balance read is RPC work and does spend credits.

Can this file send the swap?

No, and it holds no key to do so. The swap method builds an unsigned transaction, which you sign and send through any RPC.

How do I swap the balance minus a reserve?

Subtract the reserve in base units from the sum before building the request. The cap argument sets a ceiling and holds no reserve back, so to leave a reserve pass a cap of the balance minus the reserve.