library / How to use Solana / SPL tokens / HS0129
Missing token account detection
One TypeScript file derives a wallet's associated token account for the classic and Token-2022 programs, reads both in one call, and reports which exists. It sends no transaction and creates nothing.
Why the error appears
TokenAccountNotFoundError means the token client looked for a token account at an address and found nothing there. After a create call, the usual causes are a read against the other token program, or a read sent before the creating transaction is visible. The address is the part to check, and it can be checked without sending a transaction.
A wallet's associated token account for one mint is a program derived address. Its seeds are the wallet, the token program id and the mint, under the associated token program. Deriving it is arithmetic inside your process. The check here derives that address for both token programs, reads both in one call, and reports which account exists. It builds, signs and sends nothing, so it can run against any wallet.
Token-2022 mints keep their own program id, so the same wallet and mint derive one address under each program. The account lives under one of the two programs, and the other address reads as missing. Checking both removes the guess about which program a mint uses.
When no wallet argument is given, the file picks one from the chain: the fee payer of the newest successful transaction on the classic token program. That gives a live wallet for the run. The pick is a sample for the demo. Do not rely on it in an application.
The code
Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24. The first argument is the wallet and the second is the mint, which defaults to USDC. Both reads pass commitment: 'confirmed', so the two addresses are compared at one level.
// HS0129 · Missing token account detection// https://carbium.sh/library/howsolana/missing-token-account-detection// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport type { Address } from '@solana/kit';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 TOKEN = address('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');const TOKEN_2022 = address('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');const ATA_PROGRAM = address('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');const USDC = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');const [walletArg, mintArg] = process.argv.slice(2);const mint = mintArg ? address(mintArg) : USDC;const enc = getAddressEncoder();async function ataFor(owner: Address, program: Address): Promise<Address> { const [pda] = await getProgramDerivedAddress({ programAddress: ATA_PROGRAM, seeds: [enc.encode(owner), enc.encode(program), enc.encode(mint)], }); return pda;}// Picker: the fee payer of the newest successful token-program transaction.async function newestWallet(): Promise<Address> { const sigs = await rpc .getSignaturesForAddress(TOKEN, { limit: 10, commitment: 'confirmed' }) .send(); for (const s of sigs) { if (s.err !== null) continue; const tx = await rpc .getTransaction(s.signature, { encoding: 'json', maxSupportedTransactionVersion: 1, commitment: 'confirmed', }) .send(); const msg = (tx?.transaction as unknown as { message?: { accountKeys?: string[] } } | undefined)?.message; const first = msg?.accountKeys?.[0]; if (first) return address(first); } throw new Error('No recent successful token transaction to pick a wallet from.');}type ParsedToken = { mint: string; owner: string; tokenAmount: { uiAmountString: string } };function parsedInfo(data: unknown): ParsedToken | undefined { if (typeof data !== 'object' || data === null || !('parsed' in data)) return undefined; return (data as { parsed?: { info?: ParsedToken } }).parsed?.info;}const owner = walletArg ? address(walletArg) : await newestWallet();console.log(`wallet ${owner}, mint ${mint}`);const candidates = [ { name: 'spl-token', ata: await ataFor(owner, TOKEN) }, { name: 'token-2022', ata: await ataFor(owner, TOKEN_2022) },];const { value } = await rpc .getMultipleAccounts(candidates.map((c) => c.ata), { encoding: 'jsonParsed', commitment: 'confirmed' }) .send();let found = 0;value.forEach((acct, i) => { const { name, ata } = candidates[i]; const info = parsedInfo(acct?.data); if (!info) { console.log(`${name}: no token account at ${ata}`); return; } found += 1; console.log(`${name}: ${ata} mint=${info.mint} owner=${info.owner} uiAmountString=${info.tokenAmount.uiAmountString}`);});if (found === 0) { console.log('missing: no associated token account for either program. This file sends nothing.');}
run: node main.ts [wallet-address] [mint-address]
Both addresses go into one getMultipleAccounts call with jsonParsed encoding, so the token data arrives decoded. The file reads mint and owner from the parsed info and does not trust the address alone. The picker's getTransaction sets maxSupportedTransactionVersion to 1, because a v1 transaction among the newest results would otherwise fail the call.
The check does not stop at the first hit. Both candidates are always read, so a wallet holding the mint under the other program is still reported. The output lines are plain text, so a script can match on the leading program name.
Reading the answer
| Printed line | Meaning | Next step |
|---|---|---|
| spl-token: <address> ... | The wallet has an associated account for this mint under the classic program. | Transfer to that address. |
| token-2022: <address> ... | The mint lives under Token-2022, and this is the account to use. | Use the Token-2022 address in the transfer. |
| missing: ... | Neither program has an associated account for this wallet and mint. | Create it in a transaction the wallet signs, then read again. |
| An account whose mint differs | Not possible for a derived associated address. A seed mismatch would show here. | Check the mint argument and the program ids. |
Presence is the answer a transfer needs. An existing account with a zero balance is still present, so the transfer does not have to create it. The uiAmountString value is text that keeps every digit, so compare it as text or convert it to BigInt instead of to a float.
Calls and cost
The address read is an account read at 10 cells per pubkey, so the two-address call costs 20 cells. Account reads run at 0.5 per second on Free, 15 on Dev, 50 on Business and 400 on Pro. The wallet pick costs more because it is a list and a transaction: getSignaturesForAddress is 50 cells, and getTransaction is 50 cells. In the usual case the pick spends 100 cells before the 20-cell read. The limits page holds the per-plan budgets.
A batch is a different job. Below Pro, the 1024-cell burst caps a getMultipleAccounts call at 100 pubkeys, so 50 wallets with two addresses each fill one call. On Pro the same method takes up to 300 pubkeys.
Where it ends
A null answer proves that no account exists at the derived address, and nothing more. A closed associated account reads the same as one that was never created. A wallet can also hold a token account for the same mint at an address that is not the associated one. This file checks only the associated address. To cover the other accounts, see deposit ATA coverage and associated address lookup.
The read is a snapshot at the level you ask for. A read sent right after the creating transaction may still see the old state, so read again once that signature has confirmed. The picker's signatures come from the address index, which keeps 30 days, and getTransaction can answer null for an older signature because the validator's ledger no longer holds it. The picker moves to the next signature when one comes back null.
The file knows two token programs. Any other program that owns token accounts falls outside this check.
A clean result here says nothing about the balance on the other side of a transfer. Read the amount separately when a transfer needs a minimum number of tokens, and set that threshold in your own code.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| missing for a wallet that holds the token. | Check the mint argument first. A Token-2022 mint prints on its own line when that program owns the account. If neither line appears, the wallet may hold a non-associated account for the mint, so look its accounts up by owner. Confirm the wallet argument is the owner address, not a token account, because the derivation uses it as the owner seed. |
| Error -32015 from the wallet pick. | Set maxSupportedTransactionVersion to 1 on getTransaction and getBlock. Without it the node answers -32015 for a v1 transaction. The error codes page lists it. |
| missing straight after getOrCreateAssociatedTokenAccount returned. | Wait for the creating signature to reach confirmed, then read again. Read with the same token program the create used, and let the two-program check settle which one holds the account. |
| Null for the picked signature. | This is expected for an older signature that the ledger no longer holds. Take the next signature. Do not retry the same one. |
| The send path fails with TokenAccountNotFoundError after this check printed a present account. | The send path derives a different address, most often with the wrong token program id in its seeds. Pass the address this check printed into the transfer. |
Questions
Should this file create the account when it reports missing?
No. Creating an associated token account is a transaction the wallet's key signs, and this entry sends nothing. Run the check first, then create only the accounts it reports as missing.
Why check two token programs for one mint?
A Token-2022 mint has its own program id, and that id is one of the three seeds of its associated address. A classic-only derivation reports a missing account for a wallet that holds the token.
Is a null answer the same as a zero balance?
No. Null means no account exists at that address. A zero balance means the account exists and holds nothing, so it does not need creating.