services
Get a key

library / How to use Solana / HS0022

Associated token address lookup

You get the associated token account address for any wallet and mint, derived locally with the right token program, then confirmed against the chain with two read calls. A holder is picked from recent activity when you name none.

By Carbium · SPL tokens · HS0022 · updated 2026-11-22

01

What the address is

An associated token account is the token account a wallet is expected to use for one mint. No table on chain maps a wallet to it. The address is a program derived address, computed from three seeds under the associated token account program: the wallet that owns it, the token program that runs the mint, and the mint itself. Anyone holding those three values gets the same answer, offline, with no RPC call.

That makes the lookup a calculation first and a read second. Wallets, exchanges and indexers all compute the address, then ask the chain whether an account exists there. The script below does both. It derives the address, then asks Carbium for the account at that address and for every token account the owner has on that mint, and prints whether the derived address is among them.

The derivation takes these inputs, in this order:

  1. The owner wallet address, 32 bytes.
  2. The token program address, either the legacy Token program or Token-2022.
  3. The mint address.
  4. The associated token account program, ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL, as the program that the address is derived under.

The order of the three seeds matters. Swap any two and the result is a valid-looking address that no program ever created, so every later read of it comes back empty.

02

The script

The script takes a mint address as its first argument and defaults to USDC. A wallet address is an optional second argument. With no wallet, it reads the mint's ten newest signatures and fetches each transaction in turn with parsed token balances. It stops at the first holder whose balance sits in that owner's own associated token account, and falls back to the first wallet that appears in a balance for that mint. A token alone is therefore usually enough to get a real holder to check.

main.ts
// HS0022 · Associated token address lookup// https://carbium.sh/library/howsolana/associated-token-address-lookup// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  getAddressEncoder,  getProgramDerivedAddress,  type Address,} 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 rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);const ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";async function deriveAta(owner: Address, tokenProgram: Address, mint: Address) {  const enc = getAddressEncoder();  const [ata] = await getProgramDerivedAddress({    programAddress: ATA_PROGRAM,    seeds: [enc.encode(owner), enc.encode(tokenProgram), enc.encode(mint)],  });  return ata;}async function findHolder(mint: Address, tokenProgram: Address): Promise<Address | undefined> {  const sigs = await rpc.getSignaturesForAddress(mint, { limit: 10 }).send();  let fallback: Address | undefined;  for (const { signature } of sigs) {    try {      const tx = await rpc        .getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 })        .send();      const keys = (tx?.transaction.message.accountKeys ?? []) as unknown as readonly { pubkey: string }[];      const held = (tx?.meta?.postTokenBalances ?? []).filter((b) => b.mint === mint && b.owner);      for (const b of held) {        const owner = b.owner as Address;        if (String(keys[b.accountIndex]?.pubkey) === (await deriveAta(owner, tokenProgram, mint))) return owner;      }      fallback ??= held[0]?.owner;    } catch (err) {      console.error("skipped", signature, String(err));    }  }  return fallback;}const mint = address(process.argv[2] ?? USDC);const mintInfo = await rpc.getAccountInfo(mint, { encoding: "base64" }).send();if (!mintInfo.value) {  console.error("No account found for that mint.");  process.exit(1);}const tokenProgram = mintInfo.value.owner;const owner = process.argv[3] ? address(process.argv[3]) : await findHolder(mint, tokenProgram);if (!owner) {  console.error("No holder found in recent signatures; pass a wallet as the second argument.");  process.exit(1);}const ata = await deriveAta(owner, tokenProgram, mint);console.log(`owner ${owner}\nmint ${mint}\ntoken program ${tokenProgram}\nassociated address ${ata}`);const [acct, list] = await Promise.allSettled([  rpc.getAccountInfo(ata, { encoding: "base64" }).send(),  rpc.getTokenAccountsByOwner(owner, { mint }, { encoding: "jsonParsed" }).send(),]);if (acct.status === "fulfilled") {  const v = acct.value.value;  console.log(v ? `account exists, owned by ${v.owner}` : "no account at that address yet");} else {  console.log("getAccountInfo failed:", String(acct.reason));}if (list.status === "fulfilled") {  const keys = list.value.value.map((a) => String(a.pubkey));  console.log(`owner holds ${keys.length} token account(s) for this mint`);  console.log(keys.includes(ata) ? "derived address is one of them" : "derived address is not among them");} else {  console.log("getTokenAccountsByOwner failed:", String(list.reason));}

run: node main.ts

Run it with node main.ts and an optional mint and wallet. Node 24 strips the types on load, so there is no build step.

Two reads follow the derivation, and they run together. getAccountInfo on the derived address says whether an account exists there. getTokenAccountsByOwner with a mint filter lists every token account the wallet has for that mint. The script settles both, so one failing call prints its error and the other still reports.

03

Which token program to use

The token program is one of the three seeds, and a mint belongs to exactly one program. Deriving with the wrong token program gives a different address, and no account exists at it. A script that hardcodes the legacy program works for most mints and returns an empty address for a Token-2022 mint without raising any error.

The script avoids the guess. It reads the mint account first and takes its owner field, which is the token program that runs that mint. One extra read settles the question for every mint. Account reads cost 10 cells each and run at up to 15 calls a second on Dev and 400 on Pro. Holder discovery is the pricier part: it runs getSignaturesForAddress and up to ten getTransaction calls at 50 cells each, and passing a wallet skips all of them. The derivation itself is local and costs nothing.

Mint belongs toOwner of the mint accountAddress result
Legacy Token programTokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DADerive with Tokenkeg...
Token-2022TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEbDerive with Tokenz...
04

Reading the output

The script prints the owner, the mint, the token program and the derived address, then two verdicts. The first says whether an account exists at the derived address and which program owns it. The second says how many token accounts the owner holds for the mint and whether the derived address is one of them.

OutputWhat it tells you
account exists, owned by the token programThe wallet has created its associated token account for this mint.
no account at that address yetThe derivation is right and the wallet has no associated account for this mint. It may still hold the token in another account, or it closed the associated one.
derived address is one of themThe owner's token account list includes the associated address.
derived address is not among themWhen the owner holds 0 accounts for the mint, it holds none of that token. Otherwise its balance sits in another token account, such as one made from a fresh keypair.

A wallet can own more than one token account for one mint. The associated one is a convention, and nothing forces a program to use it. Pools keep tokens in accounts their own program derives or creates, and some older wallets used fresh keypairs, so the derivation will never find those. When you want every balance a wallet holds, list its accounts, as in SPL token balance or Wallet token holdings.

05

When the account is missing

Derivation always succeeds. It gives an address for a wallet that has never touched the token, and getAccountInfo answers with a null value there. That is the normal case for a first deposit, and it is the moment a sender adds an instruction that creates the account, using the idempotent create form so a second attempt does no harm.

The creator pays the rent deposit, which is 1,488,440 lamports for a 165-byte legacy token account at today's rate, and Token-2022 accounts with extensions are larger, so ask getMinimumBalanceForRentExemption for the size you need. This script sends nothing, so it only reports the gap.

06

Where it ends

The script reads and derives. It builds no transaction, signs nothing and never creates an account, so a missing associated account stays missing after a run.

The holder discovery relies on getSignaturesForAddress, which reaches back 30 days at most from its own address index. A quiet mint can have no signature in that window, and the script then asks you for a wallet. Pages also list signatures older than the validator's ledger floor, so getTransaction can answer null for one of them. The loop skips those and moves to the next signature. It asks for transaction version 1 so a v1 transaction in the list is returned instead of refused.

A closed account looks the same as one never opened, so an empty read says nothing about history. The script checks one mint per run. It does not scan a wallet, and it does not tell you the balance; a balance read on the found address is one more call to getTokenAccountBalance.

07

When it goes wrong

what goes wrongwhat to do
The derived address differs from the token account an explorer shows for the same wallet.Check the seed order: owner, token program, mint. Then check the token program. A Token-2022 mint needs its own program address, which the script reads from the mint account.
getAccountInfo returns a null value for the derived address.Nothing is wrong with the call. The wallet has not created the account, or it closed it. Create it before sending tokens there.
getTransaction answers -32015 while looking for a holder.Pass maxSupportedTransactionVersion: 1 with the encoding. Mainnet carries v1 transactions, and a lower value is refused for them.
getTransaction returns null for a signature the list just gave you.The list reaches below the validator's ledger floor, so an older signature can have no stored transaction. Skip it and use a newer one.
The request answers 401 with UNKNOWN_KEY.Send the whole key in the x-api-key header. A shortened or mistyped CARBIUM_KEY is read as an unknown key.
08

Questions

Is the associated token address the same on every cluster?

Yes. It depends only on the three addresses and the fixed associated token account program id, so any cluster running that program gives the same address for the same inputs.

Does deriving the address use any credits?

Derivation runs on your machine and costs nothing. Only the reads that follow it, such as getAccountInfo, are charged by cells and credits.

Can I use findAssociatedTokenPda from the token program package instead?

Yes, it applies the same seeds. This script limits itself to @solana/kit so the example has no extra dependency, and getProgramDerivedAddress does the same job in a few lines.

Can a wallet have more than one token account for the same mint?

It can. The associated account is the conventional one, and getTokenAccountsByOwner with a mint filter shows all of them.