services
Get a key

library / AI and blockchain / Swap assistants / SI0062

Swap preflight checks

You get a read-only script that lists every token account a wallet holds for the input mint, marks the associated one, then checks SOL and a quote together. It prints a verdict before the user signs.

By Carbium · Swap assistants · SI0062 · updated 2026-11-22

01

What the error means

A swap builder that reports input token account not found could not find a token account to take the input from. It derives the associated token address for the wallet and the input mint, looks there, and stops when nothing is found. One common cause is an empty or missing associated account while another account for the same mint holds the balance. A wallet can own several token accounts for one mint, and the associated address is only the one a program can work out without being told.

The causes a preflight can tell apart:

  • The associated account does not exist or holds 0, and a second account for the mint holds the tokens. Wallet apps, older tools and programs can create accounts at other addresses.
  • The builder derived the associated address with the wrong token program. A Token-2022 mint needs its own program as the seed, and a derivation with the classic program points at an address that holds nothing.
  • The wallet never held the mint, or sold everything and closed the account.
  • The balance moved between the check and the signature, so a check that passed a minute ago no longer holds.

Other preflight failures do not produce this error but still stop the swap. A frozen account cannot send, and a Token-2022 transfer fee changes what arrives.

An assistant that only hears the error text can guess. An assistant that lists the accounts first can name the one holding the tokens, or say that the wallet holds none, and ask the user before anything is signed.

02

The account table

The script asks getTokenAccountsByOwner for one wallet filtered by the input mint, in jsonParsed form, and prints one line per account: the address, the amount in base units and a flag. The associated address comes from getProgramDerivedAddress with the wallet, the token program and the mint as seeds. The script reads the mint with getAccountInfo and uses its owner as the token program, so a classic mint and a Token-2022 mint both derive the address a builder would pick. For a walkthrough of the call itself see Token accounts by owner, and for the derivation see Associated token address lookup.

LineMeaning
<address> 0 (associated)the account a builder derives exists and is empty
<address> 2500000another account for the mint, holding the balance
<address> 2500000 frozenthe account cannot send until its authority thaws it

Amounts stay in base units. A mint with 6 decimals shows 1000000 for one token, and the script compares integers only.

03

The preflight file

One file on @solana/kit and Node's own modules. Pass the input mint, an optional amount in base units (it defaults to 1000000) and an optional wallet. Without a wallet the file finds one. It checks your mint first, which prints ready for a wallet that holds enough. It then checks the PYUSD mint, a probe that belongs to the Token-2022 program, so that pass tests the program seed. When the finder picked a holder and also saw a fee payer holding none of your mint, a third pass checks your mint against that fee payer and prints the not-found verdict. A wallet given on the command line gets the first two passes.

main.ts
// SI0062 · Swap preflight checks// https://carbium.sh/library/si/swap-preflight-checks// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Swap preflight checks. Run: CARBIUM_KEY=... node main.ts <input-mint> [amount-base-units] [wallet]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress } 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 [mintArg, amountArg = "1000000", walletArg] = process.argv.slice(2);if (!mintArg) { console.error("Usage: node main.ts <input-mint> [amount-base-units] [wallet]"); process.exit(1); }const SOL_MINT = "So11111111111111111111111111111111111111112";const PROBE = "2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo"; // PYUSD, a Token-2022 mint that tests the program seedconst TOKEN = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"); // fallback when the mint read failsconst ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");const MIN_LAMPORTS = BigInt(2_100_000); // one fee plus the rent of one new associated accountconst listAccounts = (wallet: string, mint: string) =>  rpc.getTokenAccountsByOwner(address(wallet), { mint: address(mint) }, { encoding: "jsonParsed" }).send();async function find(mint: string) {  const sigs = await rpc.getSignaturesForAddress(address(mint), { limit: 10 }).send()    .catch((e) => { console.error(`signature read failed: ${e}`); return process.exit(1); });  const txs = await Promise.allSettled(sigs.map((s) =>    rpc.getTransaction(s.signature, { encoding: "json", maxSupportedTransactionVersion: 1 }).send()));  const payers = new Set<string>();  txs.forEach((t, i) => {    if (t.status === "rejected") console.log(`  getTransaction ${sigs[i].signature.slice(0, 8)} failed: ${t.reason}`);    else if (t.value) payers.add((t.value as any).transaction.message.accountKeys[0]);  });  const list = [...payers];  const reads = await Promise.allSettled(list.map((w) => listAccounts(w, mint)));  reads.forEach((r, i) => { if (r.status === "rejected") console.log(`  token read for ${list[i].slice(0, 8)} failed: ${r.reason}`); });  const i = reads.findIndex((r) => r.status === "fulfilled" && r.value.value.length > 0);  const none = reads.findIndex((r) => r.status === "fulfilled" && r.value.value.length === 0);  if (!list.length) throw new Error("no fee payer found");  return i >= 0 ? { wallet: list[i], kind: "holder of the mint", idle: none >= 0 ? list[none] : undefined }    : { wallet: list[0], kind: "fee payer, may hold none", idle: undefined };}async function check(mint: string, wallet: string, amount: bigint) {  const [accts, bal, quote, mintInfo] = await Promise.allSettled([    listAccounts(wallet, mint),    rpc.getBalance(address(wallet)).send(),    fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-api-key": key as string },      body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "quote",        params: [{ src_mint: mint, dst_mint: SOL_MINT, amount_in: Number(amount), slippage_bps: 50 }] }) })      .then(async (r) => (await r.json()) as { error?: { code: number; message: string } }),    rpc.getAccountInfo(address(mint), { encoding: "base64" }).send(),  ]);  const program = mintInfo.status === "fulfilled" && mintInfo.value.value ? mintInfo.value.value.owner : TOKEN;  const enc = getAddressEncoder();  const [ata] = await getProgramDerivedAddress({ programAddress: ATA_PROGRAM,    seeds: [enc.encode(address(wallet)), enc.encode(program), enc.encode(address(mint))] });  const verdicts: string[] = [];  if (mintInfo.status === "rejected") verdicts.push(`mint read failed: ${mintInfo.reason}`);  else if (!mintInfo.value.value) verdicts.push("mint account not found");  if (accts.status === "rejected") verdicts.push(`token accounts read failed: ${accts.reason}`);  else {    const rows = accts.value.value.map((a) => {      const info = (a.account.data as any).parsed.info;      return { addr: String(a.pubkey), amount: BigInt(info.tokenAmount.amount), state: String(info.state) };    });    for (const r of rows) console.log(`  ${r.addr} ${r.amount}${r.addr === ata ? " (associated)" : ""}${r.state === "initialized" ? "" : ` ${r.state}`}`);    const total = rows.reduce((n, r) => n + r.amount, BigInt(0));    const mine = rows.find((r) => r.addr === ata);    if (!rows.length) verdicts.push("NOT FOUND: wallet has no token account for this mint");    else if (total < amount) verdicts.push(`SHORT: holds ${total}, needs ${amount}`);    else if (!mine) verdicts.push(`NOTE: associated account ${ata} is not one of them`);    else if (mine.amount < amount) verdicts.push(`NOTE: associated account holds ${mine.amount}; tokens sit in another account`);    for (const r of rows) if (r.state === "frozen") verdicts.push(`NOTE: account ${r.addr} is frozen`);  }  if (bal.status === "rejected") verdicts.push(`balance read failed: ${bal.reason}`);  else if (bal.value.value < MIN_LAMPORTS) verdicts.push(`LOW SOL: ${bal.value.value} lamports`);  if (quote.status === "rejected") verdicts.push(`quote read failed: ${quote.reason}`);  else if (quote.value.error) verdicts.push(`quote refused: ${quote.value.error.code} ${quote.value.error.message}`);  for (const v of verdicts.length ? verdicts : ["ready"]) console.log(`  ${v}`);}let wallet = walletArg;let kind = "given";let idle: string | undefined;if (!wallet) ({ wallet, kind, idle } = await find(mintArg));console.log(`wallet ${wallet} (${kind})`);const amount = BigInt(amountArg);console.log(`mint ${mintArg}`);await check(mintArg, wallet, amount);console.log(`probe mint ${PROBE}`);await check(PROBE, wallet, amount);if (idle) {  console.log(`mint ${mintArg} for fee payer ${idle}, which held none`);  await check(mintArg, idle, amount);}

run: node main.ts EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v

04

Four reads sent together

The token accounts, the SOL balance, the mint account and the quote do not depend on each other, so check sends them with Promise.allSettled. The SHORT and NOTE checks use the token-account read, the LOW SOL check uses the getBalance read, and the derivation uses the mint read, so no extra call is sent. A rejected read prints its reason and becomes a verdict line, because a preflight that cannot read should say so instead of passing.

The three RPC reads leave commitment out, so @solana/kit fills in confirmed. The quote is a JSON-RPC quote call on the same endpoint and key, with src_mint, dst_mint, amount_in and slippage_bps as in Solana swap API quote. The destination is wrapped SOL, and the script only reads whether the reply carries an error. A quote spends no credits, since its plan is the meter, so asking before every swap adds nothing to the credit bill. The price of the swap itself is a separate matter, covered in Swap route breakdown.

Finding a wallet takes more calls. find() reads the ten newest signatures that mention the mint, then runs getTransaction on each with maxSupportedTransactionVersion: 1, so a v1 transaction does not answer -32015. A getTransaction call costs 50 cells and getSignaturesForAddress costs 50, so the signature and transaction reads come to 550 cells. On top of that the script sends one getTokenAccountsByOwner read per fee payer, up to ten, to ask which of them holds the mint. It returns the first holder together with its kind, and the first fee payer whose read came back empty for the third pass. When none holds it, find() returns the first fee payer and says fee payer, may hold none, and the third pass is skipped because the first pass already checks that wallet. A failed signature read prints its reason and ends the run, a getTransaction that is rejected prints its signature prefix and reason, and a null for an old signature is skipped.

05

Verdict lines

After the table the script prints zero or more verdict lines, or ready when there are none.

VerdictWhat to do
NOT FOUND: wallet has no token account for this minttell the user the wallet holds none, and stop
SHORT: holds <n>, needs <n>lower the amount, or tell the user the balance is short
NOTE: associated account <address> is not one of thempoint the builder at the listed address
NOTE: associated account holds <n>; tokens sit in another accountpoint the builder at the listed address, or move the tokens first
NOTE: account <address> is frozenthe swap cannot spend it
LOW SOL: <n> lamportsthe wallet may not cover the fee and the rent of a new account
quote refused: <code> <message>the route or the key needs attention, see the failures below

The SOL floor is a constant of 2100000 lamports. That covers a transaction fee and the 2039280 lamports of rent for one new associated account, which a swap into a fresh token needs. Tune it to the routes you build.

06

Where it ends

  • The script reads token amounts and account state. It does not read mint extensions, so a transfer fee on a Token-2022 mint is invisible to it.
  • A quote that answers without an error says a route exists at that moment. It does not reserve the route, and the balance can still change before the user signs.
  • The PYUSD pass tests the Token-2022 seed on whatever the wallet holds of that mint, and prints the not-found line when it holds none. The non-holder pass runs only when the finder saw a fee payer holding none of your mint next to a holder, and a wallet given on the command line skips it.
  • The wallet finder reads ten transactions, so a quiet mint may give few fee payers. Pass the wallet when you already know it.
07

When it goes wrong

what goes wrongwhat to do
Every read fails with 401 at the first call.The key is unknown at the door. Attach the whole key in CARBIUM_KEY, with nothing cut off.
quote refused: -32001 on the quote read while the RPC reads succeed.The key lacks the quote scope. Give it the QUOTE scope and run the check again.
The table shows the associated account at 0 and another account holding the balance.This is the case behind the error. Build the swap from the listed address, or move the tokens to the associated account first.
A line ends in frozen.The account cannot send. Tell the user, and do not build the swap until the account is thawed.
The wallet line says fee payer, may hold none and the verdict is NOT FOUND.None of the ten fee payers held the mint. Pass the wallet you mean as the third argument.
The check passes but the swap still fails after signing.The balance moved in between. Run the check again on the wallet just before the user signs, and compare the amount with the new total.
08

Questions

Why can a wallet hold several token accounts for one mint?

A token account can be created at any address, and wallet apps or programs sometimes do. The associated address is the one anyone can derive, so a builder uses it, and tokens sent elsewhere stay out of its sight.

Does an account holding 0 count as found?

Yes. The account exists and the table prints it with 0, so the verdict is SHORT or a NOTE about another account. NOT FOUND is printed only when the list is empty.

Why is the quote part of a preflight?

It tells the assistant whether a route exists for the amount before the user is asked to sign. When none does, the refusal code and message arrive as a verdict line the assistant can act on.

What does one run cost with a wallet given?

Eight calls, four for each of the two mints: the token accounts, the balance, the mint account and a quote. Leave the wallet out and the finder adds 550 cells of signature and transaction reads plus one token-account read per fee payer. A third pass for a non-holder then adds four more calls.