---
id: UC0068
title: "Protocol TVL monitor"
url: https://carbium.sh/library/usecase/protocol-tvl-monitor
collection: Use cases
category: Analytics and research
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Protocol TVL monitor

A Node script reads every vault token account of a protocol in one getMultipleAccounts call, prices each mint, prints each vault and the total in dollars, and stores snapshots so a fall in the total raises an alert.

## What TVL counts

Total value locked is the dollar value of the assets a protocol's programs hold for their users. On Solana most of it sits in token accounts the protocol controls: the two vaults of a pool, the reserve account of a lending market, the account that receives deposits. A node returns an amount in base units for each of them and knows nothing about dollars. TVL is therefore three things you assemble: a list of vault accounts that you maintain, one read of their balances, and a price for each mint.

The script below reads the token accounts you pass as arguments, multiplies each amount by the price of its mint, prints every vault with its value, and prints the sum. With no arguments it builds a demo list so that it has something to read on a live chain: the token accounts holding the most wrapped SOL in the newest transactions that mention the wrapped SOL mint. The demo list changes on every run, so two demo runs against the same tvl.db can print an ALERT for a fall that is only a change in the list. For your own protocol, pass your own vaults.

## Keeping the vault list

The list is the part of this job that needs upkeep. A vault missing from it drops out of the total with no error, and the total just looks smaller. A vault that has been closed reads as null and adds nothing. Treat the list as configuration under review, and keep it in version control next to the script.

- The protocol's own deployment records, which name each pool and reserve.
- The pool or market account itself. Most programs store their vault addresses in the account data, and the program's layout says where.
- `getTokenAccountsByOwner` on the vault authority, usually a program derived address. It lists every token account that authority owns, which catches vaults created after your last review.
- The program's newest transactions, read for the ones that create pools, when the list has to follow a protocol that adds pools by itself.

The node cannot hand you the largest holders of a mint. `getTokenLargestAccounts` is one of the [methods that are not served](https://carbium.sh/docs#rpc) and answers -32601, so a ranking by balance comes from accounts you already know or from transactions you read. The script does the second for its demo list. One discovery run costs a `getSignaturesForAddress` call at 50 cells plus a `getTransaction` call at 50 cells for each of up to 8 signatures it reads, at most 450 cells. A lookup that answers null is skipped, and each lookup passes `maxSupportedTransactionVersion: 1` because mainnet carries v1 transactions and a lookup that omits it answers -32015.

## The batched balance read and its cell bill

`getMultipleAccounts` reads every vault in one request and one slot, so all the balances in a snapshot come from the same moment. The script asks for `jsonParsed` encoding, which returns the mint, the amount and the decimals of a token account as fields. It sends no commitment, so @solana/kit fills in confirmed. An account that is closed or missing comes back as null, and the script prints it as such.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY node main.ts [vault token account ...]`)

```ts
// UC0068 · Protocol TVL monitor
// https://carbium.sh/library/usecase/protocol-tvl-monitor
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only: prices the token accounts a protocol holds in one batched read, prints each vault and the total, and flags a fall.
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress } from "@solana/kit";
import { DatabaseSync } from "node:sqlite";

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 WSOL = "So11111111111111111111111111111111111111112";
const dropPct = Number(process.env.DROP_PCT ?? 10);
const why = (e: unknown) => (e instanceof Error ? e.message : String(e));
const MICRO = 1_000_000n;
const usd = (n: bigint) => `$${n / MICRO}.${String(n % MICRO).padStart(6, "0").slice(0, 2)}`;

type Bal = { accountIndex: number; mint: string; uiTokenAmount: { amount: string } };
type Tx = { meta: { postTokenBalances?: Bal[] } | null; transaction: { message: { accountKeys: { pubkey: string }[] } } };
type Parsed = { parsed?: { info?: { mint?: string; tokenAmount?: { amount: string; decimals: number } } } };

// Demo list: the wrapped SOL token accounts with the largest balances in the newest transactions that mention the mint.
async function discover(): Promise<string[]> {
  const sigs = (await rpc.getSignaturesForAddress(address(WSOL), { limit: 8 }).send()).filter((s) => !s.err);
  const txs = await Promise.allSettled(sigs.map((s) => rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()));
  const found = new Map<string, bigint>();
  for (const t of txs) {
    if (t.status === "rejected") { console.error("lookup failed:", why(t.reason)); continue; }
    const tx = t.value as unknown as Tx | null; // null: not readable yet
    if (!tx?.meta) continue;
    for (const b of tx.meta.postTokenBalances ?? [])
      if (b.mint === WSOL) found.set(tx.transaction.message.accountKeys[b.accountIndex]!.pubkey, BigInt(b.uiTokenAmount.amount));
  }
  return [...found].sort((a, b) => (b[1] > a[1] ? 1 : b[1] < a[1] ? -1 : 0)).slice(0, 5).map(([k]) => k);
}

// One prices call with no params; each row of the answer is a mint and its USD price.
async function prices(): Promise<Map<string, number>> {
  const res = await fetch(url, {
    method: "POST",
    headers: { "content-type": "application/json", "x-api-key": key! },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "prices", params: [] }),
  });
  const body = (await res.json().catch(() => ({}))) as { result?: { solUsd?: unknown; rows?: unknown[][] }; error?: unknown };
  if (!res.ok || body.error) throw new Error(`HTTP ${res.status} ${JSON.stringify(body.error ?? "")}`);
  const map = new Map<string, number>();
  for (const r of body.result?.rows ?? []) if (Number(r[1]) > 0) map.set(String(r[0]), Number(r[1]));
  if (!map.has(WSOL) && Number(body.result?.solUsd) > 0) map.set(WSOL, Number(body.result?.solUsd));
  return map;
}

const args = [...new Set(process.argv.slice(2))];
if (args.length > 100 || !args.every((a) => isAddress(a))) {
  console.error("Usage: node main.ts [vault token account ...] (up to 100 addresses; none = demo list)");
  process.exit(1);
}
const vaults = args.length ? args : await discover();
if (vaults.length === 0) { console.error("No vaults to read."); process.exit(1); }

const [accts, priced] = await Promise.allSettled([
  rpc.getMultipleAccounts(vaults.map((v) => address(v)), { encoding: "jsonParsed" }).send(),
  prices(),
]);
if (accts.status === "rejected") { console.error("balance read failed:", why(accts.reason)); process.exit(1); }
if (priced.status === "rejected") console.error("prices failed:", why(priced.reason));
const price = priced.status === "fulfilled" ? priced.value : new Map<string, number>();

let total = 0n;
vaults.forEach((v, i) => {
  const info = (accts.value.value[i]?.data as unknown as Parsed | undefined)?.parsed?.info;
  if (!info?.mint || !info.tokenAmount) return console.log(`${v}  not a token account, or closed`);
  const p = price.get(info.mint);
  if (p === undefined) return console.log(`${v}  unpriced mint ${info.mint.slice(0, 8)}..`);
  const value = (BigInt(info.tokenAmount.amount) * BigInt(Math.round(p * 1e6))) / 10n ** BigInt(info.tokenAmount.decimals);
  total += value;
  console.log(`${v}  ${usd(value)}  mint ${info.mint.slice(0, 8)}..`);
});
console.log(`slot ${accts.value.context.slot}  TVL ${usd(total)} across ${vaults.length} vaults`);

if (priced.status === "fulfilled") { // a total with no prices would log a fall that never happened
  const db = new DatabaseSync("tvl.db");
  db.exec("CREATE TABLE IF NOT EXISTS tvl (at TEXT, slot TEXT, micro TEXT)");
  const last = db.prepare("SELECT micro FROM tvl ORDER BY rowid DESC LIMIT 1").get() as { micro: string } | undefined;
  db.prepare("INSERT INTO tvl VALUES (?, ?, ?)").run(new Date().toISOString(), String(accts.value.context.slot), String(total));
  const prev = last ? BigInt(last.micro) : 0n;
  if (prev > 0n) {
    const fall = Number(((prev - total) * 10000n) / prev) / 100;
    console.log(`previous ${usd(prev)}, change ${(-fall).toFixed(2)}%`);
    if (fall >= dropPct) console.log(`ALERT total fell ${fall}% since the last snapshot`);
  }
}
```

At most 100 vaults go into one call, and the script prints a usage line above that. The call [charges 10 cells per pubkey](https://carbium.sh/docs#rpc): 1000 cells for 100 pubkeys, and 1001 when the request body passes 4 KiB, which 100 base58 addresses can do. A call takes up to 300 pubkeys on Pro, and below Pro the 1024-cell burst caps it at 100. A longer list goes out in slices of 100. A 100-pubkey call takes nearly all of the [burst](https://carbium.sh/docs#limits), so below Pro each further slice waits until the burst has refilled at 10 cells times the plan's account-read rate: about 200 s on Free, 7 s on Dev and 2 s on Business. A call that would wait more than 1 s for its cells gets a 429, so a slice sent straight after the last answer gets one too. On Pro the burst is larger and slices need no spacing.

| Plan | Account reads, req/s |
|---|---|
| Free | 0.5 |
| Dev | 15 |
| Business | 50 |
| Pro | 400 |

Each refresh costs 10 cells for every vault, so the bill is known before you schedule anything. A snapshot of 250 vaults is three calls: two of 100 pubkeys and one of 50.

## Pricing and double counting

Prices come from the [`prices` method](https://carbium.sh/docs#prices) on the same endpoint, next to `quote`, `swap` and `health`. The script makes one call with no params and looks the mint of each vault up in the answer. A mint with no price prints as unpriced and adds nothing to the total. The call needs a key with the [QUOTE scope](https://carbium.sh/docs#quote), and a key without it gets 401 with -32001. The quote plane spends no credits, because its plan is the meter.

Amounts stay integers. The base-unit amount is scaled by the mint's decimals with `BigInt`, the price is held as micro-dollars, and only the print step builds a decimal string. A float in a sum that someone later reconciles will drift by cents.

A total that adds up cleanly can still count the same value twice:

- The same vault listed twice. The script drops repeated arguments.
- Receipt and LP tokens. When your protocol holds another protocol's receipt tokens, the assets behind them already sit in that protocol's TVL. Keep them in a separate column or leave them out.
- The protocol's own token. A treasury full of the project's own token adds a slice of its market value to TVL, and many TVL tables leave it out. Choose a rule and write it down beside the number.
- Wrapped SOL. A wrapped SOL account holds lamports above its token amount to stay rent exempt. The script reads the token amount, which leaves that rent out.

## Alerting on a fall

A total means little on its own. The script stores each snapshot in `tvl.db`, a SQLite file in the working directory, with its time and slot. It compares the new total with the previous one, and a fall of `DROP_PCT` percent or more, 10 by default, prints an `ALERT` line. Run it from cron or a systemd timer and send that line wherever your team reads. The script skips the write when the price call failed, since a total built with no prices would record a fall that never happened.

The check sees the size of a change and says nothing of its cause. A price move, a wave of withdrawals and an exploit give the same fall. To split a price move from an outflow, store the amounts next to the dollars and compare the amounts. For one large withdrawal, [Protocol vault drain alert](https://carbium.sh/library/usecase/protocol-vault-drain-alert) watches a vault live and names the signers, programs and receivers of the transaction behind it. Run that for the cause, and this script for the total.

Keep the vault list the same between runs. After you add or remove a vault, the next total jumps or falls by that vault's value, so mark the change in your records or start a new `tvl.db`. For the amount of one token account on its own, see [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).

## Where it ends

- Token accounts only. SOL held in plain accounts, stake accounts and positions kept as state inside a program are outside this read. Native SOL needs its own `getBalance` read, added to the total.
- Available liquidity only. A lending market's reserve vault holds what was deposited minus what is lent out, so borrowed tokens are missing from it, and what is owed back sits in the market's own state.
- One price source at one moment. A thin token moves a total further than any balance read does, so print the price beside each figure when the number goes in a report. Two TVL dashboards can differ because they exclude different assets, and your figure matches your own rule.
- A snapshot at confirmed. Each run sees the chain at one slot. A withdrawal and a deposit between two runs leave no trace, so shorten the interval or add a watcher when that matters.
- History is what you stored. `getSignaturesForAddress` reaches back [30 days at most](https://carbium.sh/docs#migrate), from Carbium's own address index, and an empty page past that is the index's age limit. A TVL chart older than your first snapshot has to be rebuilt from transactions or taken from another source.
- Rate limits. Free allows account reads at 0.5 req/s, so a 100-pubkey slice there waits about 200 s after the last one. Keep one snapshot job per account, since limits are per account.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The total falls with no outflow, and one vault prints as unpriced. | The prices answer has no row for that mint, so its value left the sum. Add a price for the mint or take the vault out of the list, and compare the unpriced count between runs before you trust a fall. |
| A vault prints as not a token account, or closed. | The read returned null or an account that is not a token account. The vault was closed or the address is wrong. Take it off the list. |
| A 100-pubkey batch answers 429 when slices are sent in parallel or straight after one another. | Each call takes nearly the whole 1024-cell burst, so the next slice gets a 429 until the burst has refilled. Below Pro, space slices by that gap: about 200 s on Free, 7 s on Dev and 2 s on Business. |
| The price call answers 401 with -32001. | The key lacks the QUOTE scope. Give it the scope in your account and keep the balance reads on the same key. |
| Discovery finds no vaults and prints lookups that failed. | The newest transactions answered null or were refused. Rerun a moment later, or pass your vault addresses and skip discovery. |
| A lookup answers -32015. | Pass `maxSupportedTransactionVersion: 1` with an encoding. Absent or 0, a v1 transaction is refused. |

## Questions

### Is TVL just the sum of vault balances times price?

Yes for the token accounts you list. The decisions that change the number are which vaults count, which tokens to leave out, and where the prices come from, so write those rules down with the figure.

### How many vaults can one call read?

The script sends up to 100 pubkeys a call, the cap that applies below Pro. Pro takes up to 300 pubkeys, and the call costs 10 cells per pubkey either way.

### Does the price call spend credits?

No. The quote plane spends none, because its plan is the meter. The balance read spends credits as metered RPC work and is admitted at 10 cells per pubkey.

### Can I chart TVL for the last 90 days?

Only from snapshots you stored. The address signature index reaches back 30 days, so earlier history has to come from your own records or be rebuilt another way.

## Related

- [Protocol vault drain alert](https://carbium.sh/library/usecase/protocol-vault-drain-alert) (Use cases, UC0045)
- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#prices](https://carbium.sh/docs#prices)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#quote](https://carbium.sh/docs#quote)
