library / How to use Solana / HS0047
Transfer vs TransferChecked decoder
One TypeScript file pulls recent transactions from Carbium RPC, finds every SPL Token and Token-2022 transfer in the outer and inner instructions, and prints which kind it is, the amount, the decimals when present and the accounts involved.
Two layouts, side by side
Both instructions move tokens between two token accounts, and both live in the same program. They differ in what the caller must say. Transfer states the amount. TransferChecked states the amount and also names the mint and the number of decimals the caller believes that mint has. The program compares those claims with the chain and fails the instruction when they are wrong.
On the wire the first byte of the instruction data picks the instruction. Transfer is tag 3 and TransferChecked is tag 12. The amount is an unsigned 64-bit integer in little-endian order starting at byte 1 in both. The checked form adds one more byte after it.
| Part | Transfer | TransferChecked |
|---|---|---|
| Tag byte | 3 | 12 |
| Data length | 9 bytes | 10 bytes |
| Amount | u64 at bytes 1 to 8 | u64 at bytes 1 to 8 |
| Decimals | not in the data | one byte at index 9 |
| Accounts in order | source, destination, authority | source, mint, destination, authority |
| Token-2022 mint with a transfer fee or hook | refused | accepted |
The amount is in base units. A tag 3 instruction carrying 1500000 against a mint with 6 decimals moves 1.5 tokens, and the instruction itself never says that, because it has no decimals field.
Either form can end with extra accounts. When the authority is a multisig, its signer accounts follow the authority. A Token-2022 mint with a transfer hook adds the hook's own accounts after the authority in a checked transfer. The decoder below reads the fixed positions and leaves the tail alone.
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. Pass an address, or pass nothing and it uses the SPL Token program. It lists the newest signatures for that address at confirmed commitment, drops the failed ones, fetches up to eight transactions at once and prints every transfer it finds.
// HS0047 · Transfer vs TransferChecked decoder// https://carbium.sh/library/howsolana/transfer-vs-transferchecked-decoder// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport, getBase58Encoder, isAddress } from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (apiKey === undefined || apiKey === "") { console.error("CARBIUM_KEY is not set; export your Carbium API key first."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ headers: { "x-api-key": apiKey }, url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", }),);const TOKEN_PROGRAMS = new Set([ "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",]);const target = process.argv[2] ?? "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";if (!isAddress(target)) { console.error("Pass a base58 address, or nothing to read the SPL Token program."); process.exit(1);}type Ix = { programIdIndex: number; accounts: number[]; data: string };type Meta = { loadedAddresses?: { writable: string[]; readonly: string[] }; innerInstructions?: { instructions: Ix[] }[] };const base58 = getBase58Encoder();const short = (a: string | undefined): string => (a ?? "?").slice(0, 6);// Tag 3 is Transfer (9 bytes), tag 12 is TransferChecked (10 bytes); the amount is a u64 at byte 1.function decode(ix: Ix, keys: string[]): string | null { if (!TOKEN_PROGRAMS.has(keys[ix.programIdIndex] ?? "")) return null; const bytes = base58.encode(ix.data); const tag = bytes[0]; if (!((tag === 3 && bytes.length >= 9) || (tag === 12 && bytes.length >= 10))) return null; let amount = 0n; for (let i = 8; i >= 1; i--) amount = (amount << 8n) | BigInt(bytes[i]); const names = tag === 3 ? ["source", "destination", "authority"] : ["source", "mint", "destination", "authority"]; const accounts = names.map((n, i) => `${n}=${short(keys[ix.accounts[i]])}`).join(" "); const decimals = tag === 12 ? String(bytes[9]) : "none"; return `${tag === 3 ? "Transfer" : "TransferChecked"} amount=${amount} decimals=${decimals} ${accounts}`;}const page = await rpc.getSignaturesForAddress(target, { limit: 15, commitment: "confirmed" }).send();const sigs = page.filter((row) => row.err === null).slice(0, 8).map((row) => row.signature);const results = await Promise.allSettled( sigs.map((s) => rpc.getTransaction(s, { encoding: "json", maxSupportedTransactionVersion: 1, commitment: "confirmed" }).send(), ),);results.forEach((res, n) => { const sig = sigs[n].slice(0, 8); if (res.status === "rejected") { console.error(`${sig}: ${res.reason instanceof Error ? res.reason.message : String(res.reason)}`); return; } const tx = res.value; if (tx === null) { console.log(`${sig}: null (older than the ledger)`); return; } const message = tx.transaction.message as unknown as { accountKeys: string[]; instructions: Ix[] }; const meta = tx.meta as unknown as Meta | null; // Indexes run over the message keys, then loaded writable, then loaded readonly addresses. const keys = [ ...message.accountKeys, ...(meta?.loadedAddresses?.writable ?? []), ...(meta?.loadedAddresses?.readonly ?? []), ]; const all: [string, Ix][] = [ ...message.instructions.map((ix): [string, Ix] => ["outer", ix]), ...(meta?.innerInstructions ?? []).flatMap((g) => g.instructions.map((ix): [string, Ix] => ["inner", ix])), ]; const lines = all.flatMap(([where, ix]) => { const line = decode(ix, keys); return line === null ? [] : [` ${where} ${line}`]; }); console.log(`${sig}: ${lines.length} token transfers`); lines.forEach((line) => console.log(line));});
run: node main.ts [address]
The transactions are requested with encoding: "json". That keeps the instructions raw: each one is a program index, a list of account indexes and base58 data, which is the form you decode by hand. The jsonParsed encoding would hand back named fields and hide the raw bytes the decoder reads.
The account indexes in an instruction point into one combined list. It starts with the message's accountKeys, continues with meta.loadedAddresses.writable and ends with meta.loadedAddresses.readonly. A transaction that uses lookup tables leaves part of its accounts out of the message, so the file builds the full list before resolving anything. The same list serves outer instructions and the groups under meta.innerInstructions, which is where aggregators and routers make most of their token moves.
maxSupportedTransactionVersion: 1 is set on the call, so a version 1 transaction is read instead of refused, as covered in Transaction version error -32015. Each fetch is settled on its own: a call that fails prints its message and the others still report. A null answer means the signature is listed but no longer readable, and the file says so.
Why the checked form exists
A plain Transfer trusts the caller about everything except the two token accounts. The program does confirm that source and destination hold the same mint, but nothing in the instruction says which mint the caller meant. A wallet or program that builds the instruction from stale data can move the wrong asset, or compute an amount with the wrong decimal shift, and the chain accepts it.
TransferChecked closes that gap with two checks the program runs before it moves anything.
- The mint account passed in must be the mint of the source token account. A different mint fails the instruction.
- The decimals byte must equal the decimals stored in the mint. A caller that scaled an amount for 6 decimals against a 9 decimal mint fails instead of moving a thousand times too little.
There is a second reason, specific to Token-2022. A mint can carry extensions such as a transfer fee or a transfer hook. Those need the mint account in the instruction, since the program reads the fee schedule and the hook address from it. Token-2022 therefore refuses a plain Transfer for such mints. The fee itself is covered in Transfer fee calculator.
Reading the accounts
Every address in a transfer is a token account, apart from the authority and, in the checked form, the mint. The source is the sender's token account and the destination is the receiver's token account. The authority is the owner of the source account, or its approved delegate, and it is the account that signed.
The receiving wallet appears nowhere in the instruction. A transfer to an existing token account lists the token accounts and the sender's authority only. To name the wallet, read the destination account's owner field with Token account layout decoder, or take the owner of the matching entry in meta.postTokenBalances.
The same lookup answers the decimals question for a plain Transfer. The uiTokenAmount objects in meta.preTokenBalances and meta.postTokenBalances carry decimals for each token account in the transaction, so a tag 3 amount can be scaled without a separate mint read. A wallet can also own several token accounts for one mint, so two transfers to the same wallet may show two different destinations.
Cost on Carbium
getTransaction and getSignaturesForAddress each cost 50 cells. A rate class absorbs bursts up to 1,024 cells, so one listing plus eight fetches comes to 450 cells and fits in a burst on any plan. A Free key sustains 0.24 req/s on both calls. getTransaction runs at 0.24 req/s on Free, 1.2 on Dev, 5 on Business and 25 on Pro. For a sustained scan of many signatures, a paid plan fits better.
Where it ends
The file decodes two instructions of two programs. It does not read Burn, MintTo, Approve or the Token-2022 extension instructions, and it does not follow transfers that a program makes through its own custom logic, such as a vault that rewrites balances without an SPL transfer.
Listing an address with getSignaturesForAddress on Carbium reaches back 30 days at most, from its own address index. Its pages go below the validator's ledger floor, so getTransaction can answer null for an older signature it lists. The file prints that case and moves on.
The amount is in base units and stays so in the output. A transfer fee deducted by Token-2022 is not in the instruction, so the received amount differs from the printed one. For the nested view of who called whom, see Inner instruction tree.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTransaction answers -32015 for a signature that exists. | Set maxSupportedTransactionVersion: 1 in the config object. With it absent or 0, a version 1 transaction is refused. |
| The output shows account addresses that do not match the transaction in Explorer. | The lookup table accounts were left out. Append loadedAddresses.writable and then readonly after accountKeys before resolving any index. |
| A tag 3 line prints as a transfer but the program is not a token program. | Check the program id first. Other programs use tag 3 for their own instructions, so match the tag only after the program id is one of the two token programs. |
| getTransaction answers null for a signature the listing returned. | The address index reaches below the ledger floor, so an older signature can be listed and unreadable. Run it on the newest signatures. |
| The decoded amount looks a thousand times too large or too small. | Amounts are base units. Divide by ten to the power of the mint's decimals, taken from the checked instruction's byte or from the token balance entries in meta. |
Questions
Which one should my program send?
Send TransferChecked whenever you know the mint and its decimals. It costs one more account and one more byte, and it fails loudly on a wrong mint or a wrong decimal shift. Token-2022 refuses a plain Transfer for mints with fees or hooks.
Does Token-2022 use different tag numbers?
No. Token-2022 keeps tag 3 for Transfer and tag 12 for TransferChecked. Only the program id differs, which is why the file checks both program addresses.
Why does a swap transaction show transfers nowhere at the top level?
The router calls the token program through cross-program calls, so those transfers sit in meta.innerInstructions. The file walks both lists for that reason.
Can I find the receiving wallet from the instruction alone?
No. The instruction names the destination token account. Read that account's owner, or match it against meta.postTokenBalances, to get the wallet.