---
id: HS0044
title: "Full-balance swap quote"
url: https://carbium.sh/library/howsolana/full-balance-swap-quote
collection: How to use Solana
category: Swap API
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# 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.

## 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](https://carbium.sh/library/howsolana/spl-token-balance) shows the narrower read.

## 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` (run: `node main.ts <wallet-address> [mint-address] [cap-in-base-units]`)

```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: MIT

import {
  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;
}
```

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](https://carbium.sh/docs#quote) reference before you change them.

## Reading the output

| Step | Call | What it gives you |
|---|---|---|
| 1 | `getTokenAccountsByOwner` with a mint filter | Every token account the wallet holds for the mint. |
| 2 | Sum of `tokenAmount.amount` | The full balance as a `BigInt`, in base units. |
| 3 | `quote` with `amount_in` set to the balance or the cap | The 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.

## 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](https://carbium.sh/docs#quote) sets its quote rate.

| Quote plan | Price per month | Quotes per second |
|---|---|---|
| Free | $0 | 10 |
| Starter | $7 | 50 |
| Pro | $28 | 150 |
| Elite | $104 | 500 |

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

## 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.

## When it goes wrong

| What goes wrong | What 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. |

## 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.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Wallet token holdings](https://carbium.sh/library/usecase/wallet-token-holdings) (Use cases, UC0005)
- [carbium.sh/docs#quote](https://carbium.sh/docs#quote)
- [carbium.sh/docs#swap](https://carbium.sh/docs#swap)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
