services
Get a key

library / AI and blockchain / SI0029

Token delegate exposure scan

A drain with no new signature starts with an old approval: a token delegate moves tokens on its own key, and the script lists every delegate and allowance on a wallet's Token and Token-2022 accounts.

By Carbium · Agent wallets and signing safety · SI0029 · updated 2026-11-22

01

How a drain skips the signature

The signature exists. It was given earlier, on a transaction that looked harmless. The SPL Token program has an Approve instruction: the owner of a token account signs it once and names a delegate address and an amount. From then on the delegate can move up to that amount out of the account with its own signature alone. The owner gets no prompt, and the wallet app has nothing to confirm.

That is how a drainer works against someone who signed nothing today. The approval came from a mint page, an airdrop claim or a "verify your wallet" button that asked for one signature. The transaction can carry an Approve next to other instructions, and a wallet preview that does not decode token instructions shows a vague summary. Weeks later the delegate calls Transfer, and the only signer on that transaction is the drainer's own key.

Nothing about this is hidden on chain. The delegate and its remaining allowance sit in plain fields on the token account, so a read-only call can list them.

02

What a delegate can do

AuthorityWhere it livesWhat it allowsOwner signs
Delegatedelegate and delegatedAmount on the token accountTransfer or burn up to the allowanceOnce, for the Approve; later moves need no owner signature
Account ownerowner on the token accountEverything on that account, including Approve and SetAuthorityEvery action
Close authoritycloseAuthority, when setClose the account at a zero balance; on a wrapped SOL account, close it at any balance and send the lamports to any addressNever
Permanent delegateAn extension on a Token-2022 mintTransfer or burn from any token account of that mint, any amountNever

A token account holds one delegate at a time, and a new Approve replaces the old one. The allowance drops as the delegate spends it. The amount can exceed the balance, so a delegate on an empty account keeps its allowance and the next deposit is exposed.

Native SOL has no delegate, but a signed System Program Assign does the same job: it hands the wallet account to another program, and that program can then move the SOL with no new owner signature. Short of an Assign, a SOL transfer needs the wallet's own signature, so losing SOL means a signature or a key was handed over. A wrapped SOL account is a token account and can carry a delegate like any other. It can also be emptied with no new owner signature when a close authority other than the owner is set on it, because a close of a wrapped SOL account does not need a zero balance.

03

Scan a wallet for delegates

The script takes a wallet address. With no argument it picks one: the fee payer of a successful transaction among the newest signatures of the USDC mint. That lookup costs one getSignaturesForAddress and up to ten getTransaction calls, at 50 cells each, and the transactions are read with maxSupportedTransactionVersion: 1 so a v1 transaction does not answer -32015. A call that fails prints its error, and the lookup moves on to the next signature.

The script then makes one getAccountInfo on the wallet to read which program owns it. After that it calls getTokenAccountsByOwner with jsonParsed encoding once for the Token program and once for Token-2022. The two reads are settled separately, so a failure on one shows up without hiding the other. The decoded fields save you from reading the account layout by hand: the base token account is 165 bytes, and Token-2022 accounts with extensions run longer. Every call leaves commitment out, so @solana/kit 8.6.0 fills in confirmed, while the JSON-RPC server's own default is finalized.

main.ts
// SI0029 · Token delegate exposure scan// https://carbium.sh/library/si/token-delegate-exposure-scan// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// List token accounts that carry a delegate. Run: CARBIUM_KEY=... node main.ts [wallet]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } 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 PROGRAMS = {  "Token program": address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),  "Token-2022": address("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"),};const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");const SYSTEM = "11111111111111111111111111111111";type Row = {  pubkey: string;  account: { data: { parsed: { info: {    mint: string; state: string; isNative?: boolean; closeAuthority?: string; delegate?: string;    delegatedAmount?: { amount: string; decimals: number }; tokenAmount: { amount: string; decimals: number };  } } } };};const why = (error: unknown) => (error instanceof Error ? error.message : String(error));// No argument: take the fee payer of a recent successful USDC transaction.async function findWallet(): Promise<string | undefined> {  try {    const sigs = await rpc.getSignaturesForAddress(USDC, { limit: 10 }).send();    for (const { signature, err } of sigs) {      if (err) continue;      try {        const tx = await rpc.getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send();        const keys = tx?.transaction.message.accountKeys as unknown as { pubkey: string }[] | undefined;        if (keys?.[0]) return keys[0].pubkey;      } catch (error) {        console.log(`getTransaction ${signature} failed: ${why(error)}`);      }    }  } catch (error) {    console.log(`getSignaturesForAddress failed: ${why(error)}`);  }  return undefined;}const owner = process.argv[2] ?? (await findWallet());if (!owner) {  console.error("no wallet found; pass one as an argument");  process.exit(1);}console.log(`wallet ${owner}`);// A wallet assigned to another program can be emptied by that program with no new owner signature.try {  const acct = await rpc.getAccountInfo(address(owner), { encoding: "base64" }).send();  if (acct.value && acct.value.owner !== SYSTEM) console.log(`OWNER ${acct.value.owner} is not the System Program`);} catch (error) {  console.log(`getAccountInfo failed: ${why(error)}`);}let found = 0;for (const [name, programId] of Object.entries(PROGRAMS)) {  try {    const res = await rpc.getTokenAccountsByOwner(address(owner), { programId }, { encoding: "jsonParsed" }).send();    const rows = res.value as unknown as Row[];    const withDelegate = rows.filter((row) => row.account.data.parsed.info.delegate);    console.log(`${name}: ${rows.length} token accounts, ${withDelegate.length} with a delegate`);    for (const { pubkey, account } of withDelegate) {      const info = account.data.parsed.info;      const allowance = info.delegatedAmount?.amount ?? "0";      console.log(        `DELEGATE ${pubkey} mint ${info.mint} delegate ${info.delegate} allowance ${allowance} balance ${info.tokenAmount.amount} decimals ${info.tokenAmount.decimals} state ${info.state}`,      );    }    found += withDelegate.length;    for (const { pubkey, account } of rows) {      const info = account.data.parsed.info;      if (info.closeAuthority && info.closeAuthority !== owner) {        console.log(          `CLOSE AUTHORITY ${pubkey} mint ${info.mint} closeAuthority ${info.closeAuthority} balance ${info.tokenAmount.amount} decimals ${info.tokenAmount.decimals} wrapped SOL ${info.isNative ? "yes" : "no"}`,        );      }    }  } catch (error) {    console.log(`${name}: read failed: ${why(error)}`);  }}console.log(found ? `${found} delegate(s) found` : "no delegate set on any scanned token account");

run: node main.ts

Run node main.ts <wallet> with CARBIUM_KEY set. A wallet whose owner is not the System Program prints an OWNER line with the program that owns it. Each token program prints a count line, and each account with a delegate prints a DELEGATE line with the token account, the mint, the delegate, the allowance and the balance. An account whose closeAuthority is an address other than the owner prints a CLOSE AUTHORITY line with the balance and whether the account is wrapped SOL. Amounts print in base units with the mint's decimals beside them. The script reads and prints; it signs and sends nothing.

04

Reading the result

  • Check who the delegate is. Some programs use a delegate for an order you placed on purpose, so a hit starts a look at the delegate, with its recent history from getSignaturesForAddress on the delegate address.
  • Compare the allowance with the balance. An allowance as large as the balance, or larger, lets the delegate empty the account in one transfer.
  • Look at the mint. A delegate on a stablecoin account you hold matters more than one on a token you forgot.
  • Treat an empty account with a delegate as live. The allowance survives the balance.

An account with no delegate gets no DELEGATE line and shows up only in its program's count line. A delegate count of zero on both programs means no token account carries a delegate right now, and it says nothing about transfers that already happened.

05

Guarding an agent wallet

An agent that holds a signing key faces the same trap, with the added risk that it signs fast. Decode every instruction of a transaction before signing it. Refuse Approve and SetAuthority unless the task named them, and sign only for program ids on a short list you wrote. A transaction with five instructions can hide one approval in the middle.

Run the scan on the agent's wallet on a schedule and alert on any new DELEGATE line. Agent wallet watcher watches an agent wallet's activity, and the scan adds the standing approvals that activity watching does not show. Token authority screening covers screening the authorities on a token's mint.

To remove a delegate, the owner signs a Revoke instruction from a wallet app or a revoke tool. Keep that signature a human step. If the owner key itself was exposed, a revoke does little; move the funds to a fresh wallet first.

06

Where it ends

  • The scan misses a permanent delegate. That extension lives on the Token-2022 mint, so no token account shows it. Read the mint's extensions before holding a Token-2022 token you do not know.
  • It shows state now. A delegate that spent its allowance down to zero leaves no DELEGATE line, and the scan cannot tell you it was ever there. The drain transaction is the record, and getTransaction reads it.
  • After a SetAuthority that changed an account's owner, the account no longer belongs to the wallet and getTokenAccountsByOwner does not list it.
  • A wallet with thousands of token accounts returns one large answer, so the run takes longer and the output runs long. Filter the printout to the DELEGATE lines.
  • Direct theft by a signed transfer, or by a leaked key or seed phrase, leaves no delegate to find. So does a transaction signed earlier against a durable nonce, which the holder can submit whenever it likes.
07

When it goes wrong

what goes wrongwhat to do
The scan shows no delegate on a wallet that was drained.Read the drain transaction with getTransaction and look at its signers and instruction types. A signed transfer, a changed owner or a spent allowance leaves nothing for this scan to list.
Reading the drain transaction answers -32015.Pass maxSupportedTransactionVersion: 1 with an encoding. Mainnet carries v1 transactions, and an absent or 0 value gets the error for them.
getTransaction returns null for a signature that getSignaturesForAddress listed.The address index reaches below the validator's ledger floor, so an older signature can list and read as null. Handle null, and prove the code on the newest signatures.
Only Token program accounts get scanned and Token-2022 accounts stay unread.Query both program ids, as the script does, and settle each call so one failure prints without dropping the other.
A delegate on an empty account gets ignored.Revoke it. The allowance outlives the balance and applies to the next deposit.
An agent signs a transaction with an approval buried among other instructions.Decode every instruction before signing, refuse Approve and SetAuthority unless the task named them, and sign only for listed program ids.
08

Questions

Can a drainer take SOL without a signature?

Not without an earlier one. A System Program Assign, signed once like an Approve, hands the wallet account to the drainer's program, and that program can then take its SOL with no new owner signature. Token balances, including wrapped SOL in a token account, can also sit behind a delegate.

Does the scan sign or change anything?

No. It makes read calls and prints. Revoking a delegate takes a signed Revoke from the owner, which the script never does.

Why use jsonParsed encoding?

It returns delegate, delegatedAmount and tokenAmount as named fields. The raw form is the 165-byte base token account layout, longer on Token-2022 accounts with extensions, and you would decode it by hand.

Is the delegate a person's wallet?

Usually a fresh address made for the job, and it can also be a program-derived address. Pull its recent signatures to see whether it only ever moves tokens out of other people's accounts.

Which calls does the no-argument run make?

One getSignaturesForAddress on the USDC mint, up to ten getTransaction calls to find a fee payer, one getAccountInfo on that wallet, then two getTokenAccountsByOwner reads.