---
id: HS0071
title: "Wallet and mint webhook filter"
url: https://carbium.sh/library/howsolana/wallet-and-mint-webhook-filter
collection: How to use Solana
category: Webhooks
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Wallet and mint webhook filter

One TypeScript function decides whether a transaction moved a chosen token in a chosen wallet. It matches owner plus mint on token balance records, so incoming transfers count, and it runs the same way on a live sample or inside a webhook receiver.

## Why wallet and mint must match together

A team that wants alerts when chosen wallets move chosen tokens has two filters to combine, and neither works alone. A wallet filter fires on every token the wallet touches, including spam dust and tokens nobody follows. A mint filter fires for every holder of that mint, which for a major stablecoin is a large share of the network. Only the pair, owner plus mint, narrows the stream to the movements the team asked about.

The pair also decides where to look. A token transfer into a token account that already exists lists the token accounts and the sender's authority. It never lists the receiving wallet. A check that asks whether a transaction mentions your wallet therefore sees the sends and misses the deposits, which are usually the events a team wants to hear about.

A wallet can also own more than one token account for one mint. Matching on a single token account address misses the balance held in another account of the same owner. Matching on owner and mint covers all of them at once.

## Where the pair lives in a transaction

`getTransaction` returns a `meta` object with two lists, `preTokenBalances` and `postTokenBalances`. Each record names the mint, the owner and the amount after the transaction or before it. The owner is the wallet that controls the token account, so the receiving wallet shows up here even when the instruction accounts leave it out.

| Field | Holds | Used for |
|---|---|---|
| `owner` | Wallet that controls the token account | The wallet side of the pair |
| `mint` | Address of the token | The mint side of the pair |
| `uiTokenAmount.amount` | Balance in base units, as a string | Delta, computed as a bigint |
| `uiTokenAmount.decimals` | Decimal places of the mint | Printing the delta for people |

The delta for one owner and mint is the sum of the post amounts minus the sum of the pre amounts across all of that owner's token accounts for the mint. An account created inside the transaction has no pre record and counts as 0. An account closed inside it has no post record. A failed transaction leaves balances where they were, so the code skips any signature whose `err` is set.

> Compare amounts as bigint base units. A float loses precision on large balances, and a delta of zero must read as no match.

## 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. With no arguments it lists the newest 20 signatures of the USDC mint, keeps the successful ones, reads the first five with `maxSupportedTransactionVersion: 1` at `confirmed` commitment and takes its wallet from the first transaction whose USDC balance changed. That way the run always has a subject with real activity. Pass a comma-separated list of wallets, and optionally of mints, to watch your own. The sample run still reads only the newest transactions of the first mint and filters those, so it shows a wallet only when that wallet appears among them.

`main.ts` (run: `node main.ts [wallets] [mints]`)

```ts
// HS0071 · Wallet and mint webhook filter
// https://carbium.sh/library/howsolana/wallet-and-mint-webhook-filter
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

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 USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
type Bal = { mint: string; owner?: string; uiTokenAmount: { amount: string; decimals: number } };
type Meta = { preTokenBalances?: readonly Bal[] | null; postTokenBalances?: readonly Bal[] | null };

// Net change per (owner, mint) for the watched sets, summed over all of an owner's token accounts.
function matches(meta: Meta | null, wallets: Set<string>, mints: Set<string>) {
  const net = new Map<string, { owner: string; mint: string; delta: bigint; decimals: number }>();
  const add = (list: readonly Bal[] | null | undefined, sign: bigint) => {
    for (const b of list ?? []) {
      if (!b.owner || !wallets.has(b.owner) || !mints.has(b.mint)) continue;
      const k = `${b.owner}:${b.mint}`;
      const cur = net.get(k) ?? { owner: b.owner, mint: b.mint, delta: 0n, decimals: b.uiTokenAmount.decimals };
      cur.delta += sign * BigInt(b.uiTokenAmount.amount);
      net.set(k, cur);
    }
  };
  add(meta?.postTokenBalances, 1n);
  add(meta?.preTokenBalances, -1n);
  return [...net.values()].filter((d) => d.delta !== 0n);
}

function fmt(delta: bigint, decimals: number): string {
  const s = (delta < 0n ? -delta : delta).toString().padStart(decimals + 1, "0");
  const sign = delta < 0n ? "-" : "+";
  return decimals === 0 ? sign + s : `${sign}${s.slice(0, -decimals)}.${s.slice(-decimals)}`;
}

const [walletArg, mintArg] = process.argv.slice(2);
const mints = new Set((mintArg ?? USDC).split(",").filter(Boolean));
let wallets = new Set((walletArg ?? "").split(",").filter(Boolean));

const sigs = await rpc
  .getSignaturesForAddress(address([...mints][0]), { limit: 20, commitment: "confirmed" })
  .send()
  .catch((e: unknown) => {
    console.log(`signature list failed: ${String(e).slice(0, 100)}`);
    return [];
  });
const picks = sigs.filter((s) => s.err === null).slice(0, 5);
if (picks.length === 0) console.log("No successful signatures to read; run again.");
const results = await Promise.allSettled(
  picks.map((s) =>
    rpc
      .getTransaction(s.signature, { commitment: "confirmed", encoding: "json", maxSupportedTransactionVersion: 1 })
      .send(),
  ),
);
const txs: { sig: string; meta: Meta | null }[] = [];
results.forEach((r, i) => {
  const sig = picks[i].signature;
  if (r.status === "rejected") console.log(`${sig.slice(0, 8)} read failed: ${String(r.reason).slice(0, 80)}`);
  else if (r.value === null) console.log(`${sig.slice(0, 8)} null (older than the ledger)`);
  else txs.push({ sig, meta: r.value.meta });
});

// No wallet given: take the first owner whose balance of a watched mint changed.
if (wallets.size === 0) {
  for (const t of txs) {
    const all = [...(t.meta?.preTokenBalances ?? []), ...(t.meta?.postTokenBalances ?? [])];
    const owners = new Set(all.flatMap((b) => (b.owner && mints.has(b.mint) ? [b.owner] : [])));
    const hit = matches(t.meta, owners, mints)[0];
    if (hit) {
      wallets = new Set([hit.owner]);
      console.log(`watching ${hit.owner} (first balance change in ${t.sig.slice(0, 8)})`);
      break;
    }
  }
}
if (wallets.size === 0) {
  console.log("No balance change for these mints in the transactions read; run again.");
  process.exit(0);
}

for (const t of txs) {
  const hits = matches(t.meta, wallets, mints);
  if (hits.length === 0) console.log(`${t.sig.slice(0, 8)} no match`);
  for (const h of hits) console.log(`${t.sig.slice(0, 8)} match ${h.owner} ${h.mint.slice(0, 6)} ${fmt(h.delta, h.decimals)}`);
}
```

`matches` takes the `meta` of a transaction and two sets. It returns one entry per owner and mint pair whose net change is not zero, and an empty list means no match. A positive delta is a deposit and a negative one is a send. A swap that moves two watched mints in one wallet returns two entries.

The five reads run under `Promise.allSettled`. A failing read prints its reason and the others still report, and a `null` answer prints as `null`. An empty search prints a message and the run ends with exit code 0.

## Using the function in a webhook receiver

A webhook tells you that something happened to an address. The receiver still has to decide whether it matters to the team. [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) covers setting one up. Once your receiver holds a transaction signature, it calls `getTransaction` with version 1, passes `meta` to the same `matches` function with your wallet and mint sets, and sends the alert only when the list is not empty.

A read that is not ready yet is the common hiccup at that step, and [Webhook-to-RPC fetch retries](https://carbium.sh/library/howsolana/webhook-to-rpc-fetch-retries) covers the retry. Webhook work and RPC calls both draw on your credits, and `getTransaction` costs 50 cells a call. Keep the sets in memory and let `matches` run on the response, so the filter itself adds no call.

For a team watching many wallets, [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor) shows the same idea over a polled list.

## Several wallets and mints

Both arguments are sets, so 40 wallets and 3 mints cost two set lookups per balance record, one for the wallet and one for the mint. The cost grows with the number of balance records in the transaction.

The two sets form a cross product. A deposit of mint Y into a wallet that you only watch for mint X still matches, because wallet and mint are each in their set. When every wallet has its own mint list, replace the two sets with a `Map` from owner to a set of mints and test `map.get(owner)?.has(mint)` in the loop.

The signature list call costs 50 cells and the five reads cost 250 cells. The two sit in different rate classes, and each fits inside its class's 1,024-cell burst.

## Where it ends

The discovery path reads the newest signatures that list the USDC mint. Those are mostly transfers made with `TransferChecked`, which names the mint among its accounts. A plain `Transfer` leaves the mint out, so the sample misses those transfers. A live monitor gets its signatures from a webhook or a stream and applies `matches` to each.

`getSignaturesForAddress` reads from an address index that keeps up to 30 days. An empty page past that is the index's age limit. Its pages reach below the validator's ledger floor, so `getTransaction` can answer `null` for an older signature that the list shows.

The delta is the net change inside one transaction. A wallet that receives and sends the same mint in one transaction nets to zero and returns no match, and so does a move between two token accounts of the same owner.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Every transaction prints no match for a wallet you know received tokens. | With wallets passed, the sample is still the newest 20 signatures of the first mint, and those rarely include your wallet. That is the likely cause. Feed the signatures of your own wallet to `matches`, or check that the wallet holds a mint you did not list and add it to the mint set. |
| Error -32015 on some reads. | Add `maxSupportedTransactionVersion: 1` and an `encoding` to the `getTransaction` config. A v1 transaction is refused without them. |
| A signature the list returned answers `null`. | The signature is older than the ledger the validator still holds. Skip it and treat it as a gap. |
| HTTP 429 with a retry-after hint. | Read fewer transactions per run or wait the hinted time. Transaction reads cost 50 cells each. |
| The run prints that no balance change was found and exits 0. | None of the five reads changed a balance for the mint. Run it again, since the newest signatures differ each time. |

## Questions

### Why match on owner and not on the token account address?

A wallet can hold several token accounts for one mint, and new ones appear without notice. The owner field ties every one of them to the wallet.

### Does a deposit show the receiving wallet in the instruction accounts?

Not when the destination token account already exists. The balance records still name the owner, which is why the filter reads them.

### Can I filter on a minimum amount?

Yes. The delta is a bigint in base units, so compare it with a threshold in base units inside the loop before you alert.

### Does this work for a Token-2022 mint?

The balance records use the same fields, so the match is the same. A transfer fee changes the amounts each side sees, which the delta then reflects.

## Related

- [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) (How to use Solana, HS0018)
- [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor) (Blockchain ideas, BI0006)
- [carbium.sh/docs/webhooks](https://carbium.sh/docs/webhooks)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/migrate](https://carbium.sh/docs/migrate)
