services
Get a key

library / Blockchain ideas / BI0065

Lending liquidation dashboard

A feed of lending liquidations without polling: one WebSocket subscription by program mention, an instruction name read from each Anchor log line, and dashboard rows of time, signature, instruction and error, plus a short backfill from the signature index.

By Carbium · Dashboards and explorers · BI0065 · updated 2026-11-22

01

Why a push feed fits

A liquidation dashboard answers one question the moment it matters: which positions were just closed out, and did the call succeed. Polling a lending program for new signatures means asking again and again, and every ask is a call that costs cells and counts against a rate limit. A subscription turns that around. You open one socket, and each transaction that touches the program arrives as a message.

Carbium's WebSocket serves logsSubscribe, which streams transaction logs for all transactions or only for those that mention an address. Every deposit, borrow, repay and liquidation against a lending program mentions the program, so one subscription by mention covers all of its activity and your code sorts the events.

Swaps and mints work the same way. They are instructions of a swap program or a mint program, so the same subscription with another program id gives a swap feed or a mint feed. Liquidations make a clear example because the instruction name says what happened.

Readers of the board are an analytics team that tracks how often positions close out, a risk desk that watches collateral, and a protocol's support channel that needs to answer where a user's position went.

02

Subscribing by mention

The key goes in the URL as ?api-key= on wss://services.carbium.sh. Once the socket is open, one message starts the feed: {"method":"logsSubscribe","params":[{"mentions":["<program id>"]},{"commitment":"confirmed"}]}. The first reply carries the subscription id, or an error when the subscription is refused. A refused subscription costs nothing.

Each logsNotification holds a signature, an err that is null when the transaction succeeded, and the logs array. The slot arrives in the notification's context. Failed transactions arrive too, and the board wants them: a liquidation that reverted is still a row.

mentions takes one address. The program id works because every instruction that calls the program lists it among its accounts. A protocol that spreads liquidation over a second program needs a second subscription.

The code also calls getSignaturesForAddress once at start for a short backfill: the newest ten signatures on the mentioned address and how many of them failed. The call costs 50 cells and reads the address index, which keeps up to 30 days. It lists signatures with an error field and no instruction names. Names need the transaction's logs, which come from getTransaction at 50 cells, so the backfill counts and the live feed classifies.

03

Naming each event from its log

An Anchor program writes Program log: Instruction: <Name> at the start of each instruction handler, with the name in PascalCase. A lending program built with Anchor announces a name such as LiquidateObligationAndRedeemReserveCollateralV2 in its logs, and a check for the text Liquidat catches each variant the program uses.

One transaction logs more than the lending program. It calls the token program, which writes its own Instruction: Transfer lines. The code keeps a stack of invoke lines: Program <id> invoke [2] pushes, a success or failed line pops, and a name counts only when the program on top of the stack is the one you watch. Without the stack, token transfers would flood the tally.

The run listens for 20 seconds, prints a row for every name that contains Liquidat, and then prints the ten most frequent names it saw. A quiet window still prints the tally with zero liquidations, which shows the stream worked. Pass another program id as the first argument to watch a different program. An optional second argument sets the address to mention, so the stack still matches the program id while the subscription follows a narrower account.

main.ts
// BI0065 · Lending liquidation dashboard// https://carbium.sh/library/blockchainideas/lending-liquidation-dashboard// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { 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);}// A busy lending program by default. Argument 1 is the program id; optional argument 2 is the address to mention.const PROGRAM = process.argv[2] ?? "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD";const MENTION = process.argv[3] ?? PROGRAM;const WATCH_MS = 20_000;const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");wsUrl.searchParams.set("api-key", key);const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);const tally = new Map<string, number>();let bytes = 0;// Names the watched program logs itself; calls it makes into other programs are skipped.function instructionNames(logs: string[]): string[] {  const stack: string[] = [];  const names: string[] = [];  for (const line of logs) {    const invoke = /^Program (\S+) invoke \[\d+\]/.exec(line);    if (invoke) stack.push(invoke[1]!);    else if (/^Program \S+ (success|failed)/.test(line)) stack.pop();    else {      const ix = /^Program log: Instruction: (\w+)/.exec(line);      if (ix && stack[stack.length - 1] === PROGRAM) names.push(ix[1]!);    }  }  return names;}async function backfill(): Promise<void> {  const page = await rpc.getSignaturesForAddress(address(MENTION), { limit: 10, commitment: "confirmed" }).send();  console.log(`backfill: newest ${page.length} signatures, ${page.filter((s) => s.err !== null).length} failed`);}function watch(): Promise<void> {  return new Promise((done) => {    const ws = new WebSocket(wsUrl);    ws.onopen = () => ws.send(JSON.stringify({      jsonrpc: "2.0", id: 1, method: "logsSubscribe",      params: [{ mentions: [MENTION] }, { commitment: "confirmed" }],    }));    ws.onmessage = (ev) => {      const text = String(ev.data);      bytes += Buffer.byteLength(text);      const msg = JSON.parse(text);      if (msg.id === 1) {        console.log(msg.error ? `subscribe refused: ${msg.error.message}` : `subscribed, id ${msg.result}`);        return;      }      if (msg.method !== "logsNotification") return;      const { signature, err, logs } = msg.params.result.value as { signature: string; err: unknown; logs: string[] };      for (const name of instructionNames(logs)) {        tally.set(name, (tally.get(name) ?? 0) + 1);        if (name.includes("Liquidat")) {          console.log(`${new Date().toISOString().slice(11, 19)}Z ${signature} ${name} ${err === null ? "ok" : JSON.stringify(err)}`);        }      }    };    ws.onerror = () => console.error("socket error");    setTimeout(() => { ws.close(); done(); }, WATCH_MS);  });}async function main(): Promise<void> {  const results = await Promise.allSettled([backfill(), watch()]);  for (const r of results) if (r.status === "rejected") console.error("failed:", r.reason instanceof Error ? r.reason.message : r.reason);  const names = [...tally].sort((a, b) => b[1] - a[1]);  const liquidations = names.filter(([n]) => n.includes("Liquidat")).reduce((sum, [, c]) => sum + c, 0);  console.log(`tally after ${WATCH_MS / 1000} s, ${names.length} instruction names:`);  for (const [name, count] of names.slice(0, 10)) console.log(`  ${count} ${name}`);  console.log(`liquidation instructions: ${liquidations}`);  const mib = bytes / 2 ** 20;  console.log(`received ${mib.toFixed(3)} MiB, about ${(25 + 20 * mib).toFixed(1)} subscription credits`);  process.exit(0);}void main();

run: CARBIUM_KEY=<YOUR_KEY> node main.ts

The subscription asks for confirmed commitment, so a row appears once its transaction is confirmed. The sketch closes after 20 seconds. A service keeps the socket open and reconnects when it closes, as in WebSocket keepalive and reconnect.

04

The dashboard rows

Each liquidation instruction is one row. A transaction that holds two of them gives two rows with the same signature.

ColumnWhere it comes fromExample
Timethe moment your process received the notification14:03:22Z
Signaturevalue.signature in the logsNotificationthe id to paste into an explorer
Instructionthe name on the Instruction: line of the watched programLiquidateObligationAndRedeemReserveCollateralV2
Errorvalue.err, shown as ok when null{"InstructionError":[3,{"Custom":6016}]}

The notification carries no block time, so the time column is arrival time. The slot in the notification's context pins the row to the chain when you need that, and getBlockTime turns a slot into seconds.

Keep rows in a table keyed by signature and instruction name, so a transaction that arrives twice, for example from two subscriptions, lands once. The tally in the code is the first aggregate worth charting: names per minute, and the failed share of liquidation rows.

For amounts, pass a row's signature to Anchor instruction decoder, which reads instruction data against the program's IDL.

05

What it costs

A logs subscription by mention opens at 25 credits, then costs 20 credits per MiB sent. Every transaction that mentions the program is sent, whatever its instruction, so a busy lending program costs more than a quiet one. The run prints the MiB it received and the credits that implies, so you can scale the figure to the hours you plan to leave it on.

One MiB costs 20 credits, so 100 MiB costs 2,000. The Free plan's 500K credits come once, at sign-up, and cover about 25,000 MiB of notifications after the opening cost. Dev adds 10M credits a month, Business 50M and Pro 200M. Limits are per account, so other tools on the same keys draw on the same credits.

The backfill call is 50 cells, and on Free that class allows 0.24 req/s. One call at start fits.

06

Where it ends

  • Logs carry no amounts. A row says which instruction ran and whether it succeeded. The repaid and seized amounts sit in the instruction data and in the token balance changes, so a dollar figure needs getTransaction (50 cells, with maxSupportedTransactionVersion: 1) for the signatures you care about, then decoding.
  • The gRPC stream at https://services.carbium.sh:9443 filters on the server and opens on Dev, Business and Pro. Free is off. The logs feed over the WebSocket runs on every plan.
  • Free carries 5 sockets for the whole account, and the cap covers every other tool on the same keys. A watch list of many lending programs needs a plan that carries more.
  • The name check reads the program's own logs. A program that prints no instruction name leaves nothing to classify, and a transaction that hits the runtime's log size limit ends its logs with a Log truncated line, so a name can be missing in a very large transaction.
  • A push feed has no memory. Whatever lands while the socket is closed is missed, and the signature list reaches back 30 days at most and holds no names.
07

When it goes wrong

what goes wrongwhat to do
No subscribed line prints, or the reply is an error.Check CARBIUM_KEY: an unknown key gets 401 at the door, so attach the whole key. Then check the account's socket cap, 5 on Free. A refused subscription is free, so a retry costs nothing.
The tally is empty after 20 seconds while the subscription was accepted.Read the MiB line. Zero MiB means nothing mentioned the address in the window, often a mistyped program id. Run once with the default id to see the tally fill.
The tally is full of Transfer and other token names and no lending names.The stack matches the program id as given, so a copy that differs by a character never matches. Pass the exact base58 id the program's explorer page shows.
A liquidation row is missing its name.The transaction's logs were truncated. Keep the signature, note the row as unnamed, and read its instructions with getTransaction.
Credits fall faster than expected.The subscription is billed on every MiB sent, whether or not it holds a liquidation. Pass a narrower address as the second argument, such as one market's reserve account, and compare the MiB line before and after.
08

Questions

Can the same feed cover swaps and mints?

Yes. Change the program id to a swap program or a mint program and the tally shows its instruction names. Keep the filter on the names you want, as the code does with Liquidat.

Do I need the gRPC stream for this?

No. The logs feed runs over the WebSocket on every plan. The gRPC stream opens on Dev and above and filters on the server; it fits when you need more than logs.

How do I get the amount liquidated?

Fetch the transaction by its signature with getTransaction and read its token balance changes, or decode the instruction data with the program's IDL. The log lines carry the instruction name and no amount.

Will this run on the Free plan?

Yes. It uses one socket, opens at 25 credits and makes one 50-cell call at start. The credits you spend after that follow the MiB your program sends.