---
id: SI0010
title: "Wallet anomaly alerts"
url: https://carbium.sh/library/si/wallet-anomaly-alerts
collection: AI and blockchain
category: Anomaly detection
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Wallet anomaly alerts

You get a script that reads a wallet's last 100 signatures, works out its normal pace and failure rate, flags a burst, a failure spike or silence in the newest ten, then flags failed transactions and bursts in the live log stream.

## What counts as an anomaly

On a single wallet, an anomaly is a break from that wallet's own habit. A detector that needs a trained model also needs labelled history, and most teams do not have that for one treasury wallet or one deposit address. Three numbers from one RPC call catch most breaks in a steady wallet's habit: how far apart its transactions usually fall, what share of them fail, and how long it has been since the last one.

The script compares the newest 10 signatures with the 90 before them and raises one alert for each rule that trips.

- `burst`: the median gap between the newest 10 is under a fifth of the baseline median gap, and the baseline gap is at least 10 s.
- `failure spike`: at least half of the newest 10 failed while fewer than 10% of the older ones did.
- `silent`: the newest signature is older than ten times the baseline gap, with a floor of 60 s on that gap.

Each rule is a plain threshold, so you can explain an alert in an incident review and change a number without retraining anything. They suit wallets whose normal is steady, such as a treasury, a program's fee payer or a deposit address. The same three numbers can later go into a model as inputs, and [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) shows how to hand a model read-only tools without letting it send anything.

## One signature page as the baseline

`getSignaturesForAddress` returns signatures newest first, with `blockTime` in whole seconds and `err` set when the transaction failed. The script asks for 100 at `confirmed` commitment and nothing else. The call costs 50 cells, which is 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro. One call per refresh is the whole read cost of the baseline.

The pages come from Carbium's own address index, which keeps up to 30 days. A busy wallet fills 100 signatures in seconds to minutes, so its baseline describes the last few seconds or minutes. A quiet one can stretch across weeks. The script prints `sampled` and the baseline gap so you can see which kind of wallet you are watching. An empty page past 30 days is the index's age limit and says nothing about the wallet's first transaction.

| Number | Taken from | Used by |
|---|---|---|
| Median gap, older 90 | differences between `blockTime` values | burst, silence |
| Rate, older 90 | signatures over the seconds they span, when that span is at least 10 s | live burst limit |
| Failure share, older 90 | `err` is not null | failure spike |
| Median gap, newest 10 | differences between `blockTime` values | burst |
| Age of the newest signature | now minus its `blockTime` | silence |

## The watcher

One file on @solana/kit 8.6.0 and Node 24, which runs the TypeScript directly. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. `CARBIUM_RPC_URL` and `CARBIUM_WS_URL` override the endpoints, which default to `https://services.carbium.sh` and `wss://services.carbium.sh`. The first argument is the wallet and the second is how many seconds to keep the live feed open: 60 when left out, 0 for the baseline only. The wallet defaults to the SPL Token program, a busy public address that takes transactions all day, so a first run shows a real baseline and live lines. Pass your own wallet to watch it.

`main.ts` (run: `node main.ts`)

```ts
// SI0010 · Wallet anomaly alerts
// https://carbium.sh/library/si/wallet-anomaly-alerts
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Wallet anomaly alerts. Run: CARBIUM_KEY=... node main.ts [wallet] [watchSeconds]
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 rpcUrl = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const wsUrl = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";
// Default: the SPL Token program, a busy public address with steady traffic.
const wallet = process.argv[2] ?? "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const watchSeconds = Number(process.argv[3] ?? 60);
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": key } }));

const median = (xs: number[]) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)] ?? 0;
const gaps = (r: { t: number }[]) => r.slice(0, -1).map((x, i) => x.t - (r[i + 1]?.t ?? x.t));
const share = (r: { failed: boolean }[]) => (r.length ? r.filter((x) => x.failed).length / r.length : 0);

// Newest first. Commitment is named, not left to the client default. A failed read leaves the baseline empty.
let rows: { t: number; failed: boolean }[] = [];
let failure: string | undefined;
try {
  const page = await rpc.getSignaturesForAddress(address(wallet), { limit: 100, commitment: "confirmed" }).send();
  rows = page.filter((r) => r.blockTime !== null).map((r) => ({ t: Number(r.blockTime), failed: r.err !== null }));
} catch (e) {
  failure = `baseline read failed: ${e instanceof Error ? e.message : String(e)}`;
}
const recent = rows.slice(0, 10);
const older = rows.slice(10);
const baseGap = median(gaps(older));
const baseFail = share(older);
const note = failure ?? (rows.length < 20 ? `sample too small (${rows.length} signatures in the index), baseline rules skipped` : undefined);

// blockTime is whole seconds: a median gap reads 0 on busy wallets, so use signatures over the span they cover.
// Under 10 s the span is too coarse to give a rate, and the live burst rule stays off (null).
const span = (older[0]?.t ?? 0) - (older[older.length - 1]?.t ?? 0);
const burstLimit = !note && span >= 10 ? Math.max(5, Math.ceil((5 * 60 * (older.length - 1)) / span)) : null;

const alerts: string[] = [];
if (!note) {
  const age = Math.floor(Date.now() / 1000) - (recent[0]?.t ?? 0);
  if (baseGap >= 10 && median(gaps(recent)) * 5 < baseGap) alerts.push("burst");
  if (share(recent) >= 0.5 && baseFail < 0.1) alerts.push("failure spike");
  if (age > 10 * Math.max(baseGap, 60)) alerts.push(`silent for ${age} s`);
}
console.log(JSON.stringify({ wallet, sampled: rows.length, baseGapSeconds: baseGap, baseFailShare: baseFail, burstLimit, alerts, note }));

if (watchSeconds > 0) {
  const url = new URL(wsUrl);
  url.searchParams.set("api-key", key);
  const ws = new WebSocket(url);
  const seen: number[] = [];
  let okCount = 0;
  let lastMessage = Date.now();
  let finished = false;
  // Busy wallets would flood the output: print alerts as they come, and every 5 s the ok count or the idle time.
  setInterval(() => {
    const idle = Math.floor((Date.now() - lastMessage) / 1000);
    console.log(idle >= 10 ? `no notification for ${idle} s` : `ok so far: ${okCount}`);
  }, 5000);
  ws.onopen = () =>
    ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [wallet] }, { commitment: "confirmed" }] }));
  ws.onmessage = (ev) => {
    const msg = JSON.parse(String(ev.data));
    if (msg.error) console.error("subscription refused:", msg.error.message);
    const tx = msg.method === "logsNotification" ? msg.params.result.value : null;
    if (!tx) return;
    const now = Date.now();
    lastMessage = now;
    seen.push(now);
    while ((seen[0] ?? now) < now - 60_000) seen.shift();
    const burst = burstLimit !== null && seen.length > burstLimit;
    const flags = [tx.err ? "failed" : "", burst ? `burst, ${seen.length} in 60 s` : ""].filter(Boolean);
    if (flags.length) console.log(tx.signature, `ALERT ${flags.join(", ")}`);
    else okCount++;
  };
  ws.onerror = () => console.error("websocket error");
  // A socket that closes before the watch time ends, or after an error, is not a clean run.
  ws.onclose = () => process.exit(finished ? 0 : 1);
  setTimeout(() => {
    finished = true;
    ws.close();
  }, watchSeconds * 1000);
}
```

The first output line is a JSON object with the sample size, the baseline gap and failure share, the burst limit and any alerts from the baseline pass. With fewer than 20 signatures in the index it adds a `note` saying the sample is too small and skips the three baseline rules and the live burst rule; the live failure flag still runs. If the baseline read fails, the error message goes into the same `note` and the live feed still opens. After that, only transactions that raise an alert print a line, with the signature and the reasons. Every 5 seconds the script prints a running count of the ok ones, or `no notification for N s` once 10 seconds have passed without one, so a stalled socket does not look like a quiet wallet. The process exits with a non-zero code when the socket errors or closes before the watch time ends.

## Scoring the live feed

`logsSubscribe` streams transaction logs, all or by mention. The script uses the mention filter, so it hears only transactions that name the wallet, including a plain SOL wallet, where `accountSubscribe` sends nothing. Call `getBalance` in the alert path when an alert should carry the current balance.

Each notification carries the signature, `err` and the log lines. `err` is null for a success, so a failed transaction is one truthy check, and the script flags every failure whatever the baseline failure share was. A wallet that fails often prints an alert line for most of its transactions. The burst rule keeps the arrival times of the last 60 s and alerts when their count passes `burstLimit`, which is five times the baseline's per-minute rate. That rate is the older signatures divided by the span of seconds they cover. A median gap cannot give it for a busy wallet, because `blockTime` is in whole seconds and the median reads 0 when several transactions land in each second. When the older 90 span under 10 s, the rate is too coarse to read, `burstLimit` prints as null and the live burst rule stays off.

> A subscription opens at 5, 25 or 200 credits by filter weight and then costs 20 credits per MiB sent. A mentions filter is the middle weight, 25. A busy address sends a lot of log text, so the per-MiB part follows what the wallet does. A refused subscription is free, and the script prints the node's refusal message.

## Keys and limits

The script never prints the socket URL. It does print the node's refusal message and the baseline error text, so keep the URL and the headers out of any line you add to those.

Limits are per account, so an account's keys share one budget and a second watcher on the same account draws from the same cells.

Connection and subscription counts are capped per account by tier, and Free carries 5 sockets. One socket can carry several subscriptions, but each watched wallet is a subscription and counts against your plan's subscription cap. Past that cap, poll the signature page for the remaining wallets, within the plan's rate.

## Where it ends

- The baseline is one page of at most 100 signatures from an index that keeps up to 30 days. A wallet with fewer than 20 signatures there skips the three baseline rules and only the live failure flag runs, and older history is not served.
- The live burst rule needs the older 90 signatures to span at least 10 s. On a busier address whose page covers less, `blockTime` has no finer resolution, so the rule is off and only failed transactions print live.
- The rules see timing and failure. Amounts, counterparties and programs sit inside the transaction, and `getTransaction` costs 50 cells per call, so enrich only the signatures that raised an alert. A drain made of ordinary-looking transfers at a steady pace passes every rule here.
- The thresholds are fixed numbers. A wallet whose normal is bursts will alert constantly, so read your own wallets' baselines before you trust any of these.
- The `silent` rule runs once, on the baseline pass. While the feed is open, a quiet wallet shows only as a `no notification for N s` line and raises no alert until you add a timer.
- The script does not reconnect or backfill. After a dropped socket, read the signature page again to cover the gap and dedupe by signature.
- Alerts are printed. Delivery is yours, and [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) shows alerts going to Slack for slot lag.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A wallet that is normally bursty alerts on every run. | Raise the factor of 5, or build the baseline from several pages by passing `before` to the call, so quiet and busy periods both count. |
| A new wallet raises no baseline alerts. | Under 20 signatures the script skips the burst, failure spike and silent rules on purpose, while the live feed still flags failed transactions. Add a fixed limit of your own for such wallets until a baseline exists. |
| Burst alerts flood the output on a very busy address. | A limit set from a thin sample is too low for a busy address, so the script turns the live burst rule off when the older 90 span under 10 s. If you want it on, build the baseline from several pages with `before` or set a fixed limit of your own. |
| A 429 on the baseline read. | The error message goes into `note`, the baseline rules and the live burst rule are skipped, and the live feed still opens. |
| The key appears in a log line or an alert. | Never print the socket URL or request headers, and read the key from the environment in one place. |
| The same signature alerts twice after a reconnect. | Keep a set of seen signatures and skip repeats, including those you re-read from the signature page. |

## Questions

### Do I need a machine-learning model to detect wallet anomalies?

Not to start. Gap, failure share and age catch bursts, failure runs and silence from one RPC call. If you add a model later, those numbers are ready-made inputs, and every alert still has a rule you can read.

### Why does a very busy address print a null burst limit?

`blockTime` is in whole seconds, so when the older 90 signatures land inside a few seconds the per-minute rate cannot be read. The script then leaves the live burst rule off and still flags failed transactions.

### How far back does the baseline reach?

At most 30 days, from Carbium's own address index. An empty page past that is the index's age limit and says nothing about the wallet's first transaction.

### What does one baseline refresh cost?

One `getSignaturesForAddress` call at [50 cells](https://carbium.sh/docs#rpc). The script makes that one call per run.

### How do I get the alerts into Slack?

Replace the `console.log` in the alert path with a post to your webhook. [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) does that for slot lag.

## Related

- [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) (Integrations, I0001)
- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
