library / Use cases / Exchanges, custodians and on-ramps / UC0107
Deposit sender attribution
Get the sender of every token credit to a Solana wallet. A Node script lists the wallet's token accounts, reads their recent transactions and prints, for each transfer, the source wallet, the signer, the mint and the amount.
Why the sender is not in the logs
The first instinct is to read the program's log lines, or the receiving wallet's history, and find the sender there. Neither holds it reliably. A token transfer is an instruction to the token program, and it names three accounts: the source token account, the destination token account and the authority that signed. The receiving wallet is not among them, and the sender's wallet is missing too whenever the authority is a delegate or a program address. The token program's own log lines name the instruction and carry no addresses.
The attribution is an off-chain read of the transaction as the ledger stores it. Three parts of one transaction answer it together.
- The parsed transfer and transferChecked instructions, at the top level or inside a program's inner instructions. They carry the source account, the destination account, the authority and the amount.
- The transaction's token balances. Each token account that the transaction touched appears with its owner wallet and its mint, so a token account maps to the wallet behind it.
- The fee payer, the first account key. When a program signs the transfer for the user, the payer is the nearest hint to who started the transaction.
Listing the wallet's own signatures misses most credits for the same reason. The transfer's account list holds token accounts, so the wallet address is absent from it. The script asks for the wallet's token accounts first and lists the signatures of those.
The attribution in one file
Pass a wallet address as the argument, or pass nothing. With no argument the script reads the newest 5 signatures of the USDC mint, takes the first wallet that received a transfer, and prints it before anything else, so the run always has a wallet with activity. ACCOUNTS (2) is how many of the wallet's token accounts it reads and PER_ACCOUNT (4) how many recent signatures it reads for each. CARBIUM_KEY is required, and RPC goes through @solana/kit to CARBIUM_RPC_URL, which is https://services.carbium.sh when unset, with the key in the x-api-key header.
// UC0107 · Deposit sender attribution// https://carbium.sh/library/usecase/deposit-sender-attribution// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: lists who sent tokens to a wallet, from its token accounts' transfer instructions and token balances.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } 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 LEVEL = "finalized" as const;const ACCOUNTS = 2, PER_ACCOUNT = 4; // token accounts read, signatures read per token accountconst USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];type Ix = { programId?: string; parsed?: { type?: string; info?: { source?: string; destination?: string; authority?: string; multisigAuthority?: string; mint?: string; amount?: string; tokenAmount?: { amount: string } } } };type Bal = { accountIndex: number; mint: string; owner?: string };type Tx = { slot: bigint; transaction: { message: { accountKeys: { pubkey: string }[]; instructions: Ix[] } }; meta: { err: unknown; innerInstructions?: { instructions: Ix[] }[]; preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } };let failed = 0;const tryit = async <T>(what: string, f: () => Promise<T>): Promise<T | undefined> => { try { return await f(); } catch (e) { failed++; console.error(`${what} failed: ${e instanceof Error ? e.message : e}`); } return undefined;};const fetchTx = async (sig: string): Promise<Tx> => { // version 1, so a v1 transaction reads instead of answering -32015 const tx = (await rpc.getTransaction(signature(sig), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: LEVEL }).send()) as unknown as (Tx | null); if (!tx?.meta) throw new Error(`transaction ${sig} not served`); return tx;};// Every token transfer in the transaction, top level and inner, with the wallets behind its token accounts.function transfers(tx: Tx) { const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey); const who = new Map<string, Bal>(); for (const b of [...(tx.meta.preTokenBalances ?? []), ...(tx.meta.postTokenBalances ?? [])]) who.set(keys[b.accountIndex]!, b); const ixs = [...tx.transaction.message.instructions, ...(tx.meta.innerInstructions ?? []).flatMap((n) => n.instructions)]; return ixs.flatMap((ix) => { const p = ix.parsed, i = p?.info; if (!p || !i?.source || !i.destination || !PROGRAMS.includes(ix.programId ?? "") || !/^transfer(Checked)?$/.test(p.type ?? "")) return []; return [{ payer: keys[0], from: who.get(i.source)?.owner, authority: i.authority ?? i.multisigAuthority, source: i.source, to: who.get(i.destination)?.owner, destination: i.destination, mint: i.mint ?? who.get(i.source)?.mint, amount: i.amount ?? i.tokenAmount?.amount }]; });}async function main() { let wallet: string | undefined = process.argv[2]; if (wallet) address(wallet); // throws on a malformed address else { const sigs = await tryit("USDC signatures", () => rpc.getSignaturesForAddress(address(USDC), { limit: 5, commitment: LEVEL }).send()); for (const s of sigs ?? []) { if (wallet || s.err) continue; const tx = await tryit("transaction", () => fetchTx(s.signature)); wallet = tx ? transfers(tx).find((t) => t.to)?.to : undefined; } } if (!wallet) { console.error("no wallet to read"); process.exit(1); } const owner = wallet; console.log(`wallet ${owner}`); const lookups = await Promise.all(PROGRAMS.map((p) => tryit(`token accounts under ${p.slice(0, 4)}`, () => rpc.getTokenAccountsByOwner(address(owner), { programId: address(p) }, { encoding: "jsonParsed", commitment: LEVEL }).send()))); const accounts = lookups.flatMap((r) => r?.value ?? []).slice(0, ACCOUNTS); const rows = []; for (const a of accounts) { const sigs = await tryit(`signatures of ${a.pubkey}`, () => rpc.getSignaturesForAddress(a.pubkey, { limit: PER_ACCOUNT, commitment: LEVEL }).send()); const txs = await Promise.all((sigs ?? []).filter((s) => !s.err).map(async (s) => ({ s, tx: await tryit("transaction", () => fetchTx(s.signature)) }))); for (const { s, tx } of txs) { if (!tx || tx.meta.err) continue; for (const t of transfers(tx)) if (t.to === owner) rows.push({ sig: s.signature, slot: String(tx.slot), ...t, delegated: t.authority !== t.from }); } } console.log(JSON.stringify({ wallet: owner, accounts: accounts.map((a) => a.pubkey), failed, received: rows }, null, 1));}main().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1); });
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [<wallet-address>]
transfers builds one map from token account to its balance entry, then walks the top-level and inner instructions. fetchTx asks for jsonParsed and sets maxSupportedTransactionVersion to 1, because a version 1 transaction answers -32015 when the setting is absent or 0. Every call names finalized: kit fills in confirmed for a call that leaves it out, and a credit should not post on a transaction that can still drop. A signature that lists but reads back null is counted and named on stderr.
A run prints one JSON object with the wallet, the token accounts it read, the number of failed calls and a received list. Each row names the token account the credit landed in as destination, so a wallet with several token accounts for one mint still reads as one wallet in to.
Reading a row
| Field | What it holds | Use it to |
|---|---|---|
| from | The wallet that owns the source token account | Name the sender when delegated is false |
| authority | The account that signed the transfer | See a delegate, a multisig or a program address |
| delegated | True when authority differs from from | Decide whether from or authority is your sender |
| payer | The transaction's fee payer | Find the user behind a program-signed transfer |
| source, destination | The two token accounts | Match the credit to a deposit account you issued |
| mint, amount | The mint and the raw amount in base units | Credit the right asset, scaled by the mint's decimals |
| sig, slot, to | The transaction, its slot and the receiving wallet | Book each credit once, keyed by signature and destination |
For a plain wallet-to-wallet send, from and authority are the same address and delegated is false. When a program moves the tokens through a call into the token program, the transfer sits in the inner instructions. The authority is then often an address the program controls, from is the owner of the account it spent from, and payer is the person who paid the fee. Which of the three you book as the sender is your own rule, and the three fields give you the evidence for it.
Token-2022 mints with a transfer fee credit the receiver less than amount. Transfer vs TransferChecked decoder covers the two instruction shapes and the decimals that transferChecked carries.
If you write the program
A program that has to attribute a deposit to a user takes the depositor as a signer account in the instruction. The transaction then carries that account in the instruction's account list, and an indexer reads it back like any other. If the program needs the answer on chain, it writes the depositor into an account it owns.
An event written with Anchor's emit! or with sol_log_data is a log line, and the node caps the log output of one transaction and cuts it off past the cap. Anchor's emit_cpi! puts the event in the data of a call the program makes to itself, so it sits in the inner instructions and is never cut. Treat log events as a convenience for live feeds and keep the account list or the inner instructions as the record. An exchange that issues one deposit address per customer, or asks for a memo, can attribute by the receiving account and never needs the sender at all. Exchange deposit alerts shows the feed that finds the credit and the ledger write that books it.
What a run costs
Two methods carry the work, and both cost 50 cells a call. The token-account lookup is a third call type, and the script makes two of it, one per token program.
| Call | Used for | Cells | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|---|
| getSignaturesForAddress | One list for each token account | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | One read for each signature | 50 | 0.24 | 1.2 | 5 | 25 |
With a wallet argument a run makes at most 2 signature lists and 8 transaction reads, which is 100 cells and 400 cells. Without one it adds a list of the USDC mint and up to 5 reads, for 650 cells on getTransaction at the most. Each method sits in its own rate class, and each total stays under the 1,024 cells a class absorbs as a burst. Cells are the admission charge per call.
The slower row sets the sustained pace, and that is getTransaction. At 8 reads a wallet, Dev at 1.2 req/s attributes about 9 wallets a minute, Business at 5 req/s about 37 and Pro at 25 req/s about 187. Free at 0.24 req/s fits a wallet every half minute or so. Keys on one account share one budget, so a second key adds no capacity.
Where it ends
- Tokens only. A SOL deposit is a system transfer, and its parsed instruction lists the source and destination wallets directly, so it needs a different and simpler filter.
- Recent history only. The script reads the latest 4 signatures of 2 token accounts. A busier account pushes an older credit out of that window, so raise PER_ACCOUNT or page back with before. getSignaturesForAddress reaches back 30 days from Carbium's own address index, and its pages go below the validator's ledger floor, so a listed signature can read back null.
- Token accounts come in the order the node returns them, classic token accounts before Token-2022 ones, and a wallet can own more than one for a mint. A credit to an account past the first ACCOUNTS never shows.
- Identity stops at the address. The script names the owner of the source account and the signer. Which customer or legal entity stands behind that address is in your own records.
- Two instruction shapes only. A mint, a burn, a confidential transfer and Token-2022's transferCheckedWithFee fall outside transfer and transferChecked.
- A swap or a pool relay shows the pool's vault as the sender. Attribute a routed credit by the payer, or skip transfers whose source owner is a known pool.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| received is empty for a wallet you know was paid. | The credit is older than the latest PER_ACCOUNT signatures, it went to a token account past ACCOUNTS, or it was SOL. Raise the two constants, or pass the signature you have to fetchTx and call transfers on it directly. |
| A row has no from. | The source token account is missing from the transaction's token balances, so no owner is recorded for it. Read the account with getAccountInfo while it exists and store its owner then. After the account closes, that owner is gone. |
| A read stops with -32015. | A version 1 transaction was read with maxSupportedTransactionVersion absent or 0. Set it to 1, as fetchTx does, and keep it in any config object you build elsewhere. |
| stderr says a transaction was not served. | The signature sits below the ledger floor, though the address index listed it. A second run will not change that. Credit from your own stored record of the transaction, or read the signatures that are newer. |
| Calls come back 429. | The plan's rate for that method ran out. Wait for the retry-after hint, lower PER_ACCOUNT, or spread the wallets out. Free keys can also hit their network's shared budget. |
Questions
Can the program's logs tell me who sent the tokens?
Only if the program prints the sender, and the node caps and can cut a transaction's logs. The instruction's account list is always on the ledger, so read the sender from there.
Why list the token accounts and not the wallet's signatures?
The transfer instruction names token accounts, so the wallet address is not in the transaction's keys. The wallet's own history misses the credit, and the token account's history holds it.
Is `from` always the person who sent the tokens?
It is the owner of the account the tokens left. When delegated is true, a different account signed, and you decide with authority and payer in front of you.
Does this read SOL deposits too?
No. A system transfer's parsed instruction carries both wallets as source and destination. Filter the system program's transfer type and read those two fields.