---
id: UC0016
title: "DeFi position dashboard"
url: https://carbium.sh/library/usecase/defi-position-dashboard
collection: Use cases
category: DeFi front ends and position monitors
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# DeFi position dashboard

Build the data layer of a Solana DeFi dashboard: read position token accounts in one batched call, follow changes over a WebSocket, page activity history, and size the request budget, with a Node script that does the read and the live part.

## What a position is on chain

A position dashboard answers one question per row: what does this user hold in this protocol right now. A fungible LP token or a vault share is a plain SPL token account owned by the user. Its mint names the position and its amount is an integer in base units. Ask for the `jsonParsed` encoding and one read returns the mint, the owner, the amount and the decimals.

Other positions are not plain token accounts. A concentrated-liquidity position is an NFT of amount 1 plus a protocol position account, and most lending positions sit in a protocol-owned obligation account. The token read covers the first kind and the protocol accounts carry the rest.

That gives the backend a simple shape. It keeps a list of position account addresses per user, reads them as one batch, and keeps them fresh from a subscription. What a token account does not carry, such as a pool's reserves or a loan's health, lives in the protocol's own accounts. You read those with the same call and decode them with the protocol's layout.

Amounts stay integers. The script keeps the base-unit amount as a string and applies the mint's decimals only when it prints. Floats lose digits on large balances.

> Keep the key on your server. The page talks to your backend, and the backend talks to Carbium with the key in the `x-api-key` [request header](https://carbium.sh/docs#auth) on RPC and as `?api-key=` in the URL on the WebSocket. Every key on an account draws on one shared [budget](https://carbium.sh/docs#limits), so a key scraped from a browser spends your account's budget.

## One batched read for a screen

The snapshot is `getMultipleAccounts`. It takes up to 300 pubkeys in one call and [charges 10 cells per pubkey](https://carbium.sh/docs#rpc). The 1024-cell burst caps a call at 100 pubkeys below Pro, so Free, Dev and Business readers size batches at 100. It shares the account-read class with `getAccountInfo` and `getTokenAccountBalance`.

| Class | Cells per call | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|
| Account reads | 10 | 0.5 | 15 | 50 | 400 |

Fifty positions read with `getAccountInfo` are 50 requests and 500 cells. The same fifty through one `getMultipleAccounts` are one request and the same 500 cells. Batching cuts requests and round trips and leaves the cells unchanged, so size the budget on cells. A call of N pubkeys is billed as N account reads. A JSON-RPC POST can also carry a batch of [up to 100 calls](https://carbium.sh/docs#rpc), which helps when a screen mixes several methods.

The snapshot leaves commitment out, so @solana/kit 8.6.0 fills in `confirmed`, and the subscription asks for `confirmed` explicitly.

## The dashboard in one file

The script takes up to 100 position token-account addresses on the command line. With no arguments it checks up to the 5 newest signatures on the USDC mint and takes up to 5 token accounts from the first transaction that lists any: `getSignaturesForAddress` lists the signatures and `getTransaction` opens them, as plain JSON-RPC over `fetch` to the same RPC URL at the server's default commitment, finalized. It reads `CARBIUM_KEY` and the optional `CARBIUM_RPC_URL` and `CARBIUM_WS_URL`, whose [defaults](https://carbium.sh/docs#endpoints) are `https://services.carbium.sh` and `wss://services.carbium.sh`.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY node main.ts`)

```ts
// UC0016 · DeFi position dashboard
// https://carbium.sh/library/usecase/defi-position-dashboard
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only DeFi position dashboard: one batched snapshot of token accounts, then live changes over one WebSocket.
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder } 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";
// At most 100 pubkeys per getMultipleAccounts call, the most a plan below Pro admits.
const accounts: string[] = process.argv.slice(2, 102);
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": key } }));
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);
const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
type Parsed = { parsed?: { info?: { mint: string; tokenAmount?: { amount: string; decimals: number } } } };
type Acct = { lamports: bigint | number; data: unknown } | null;
type Tok = { mint: string; amount: string; decimals: number };
// Decimals come from the snapshot's parsed read; live notifications carry raw account bytes.
const decimals = new Map<string, number>();
// Token state from a parsed account, or from the SPL token layout: mint at bytes 0 to 32, amount u64 LE at byte 64.
function token(a: string, v: Acct): Tok | null {
  if (!v || Number(v.lamports) === 0) return null;
  const d = v.data as Parsed | [string, string];
  if (Array.isArray(d)) {
    const dec = decimals.get(a), b = Buffer.from(d[0], "base64");
    if (dec === undefined || b.length < 72) return null;
    return { mint: getAddressDecoder().decode(b.subarray(0, 32)), amount: b.readBigUInt64LE(64).toString(), decimals: dec };
  }
  // A mint, nonce or stake account parses with info but has no tokenAmount.
  const t = d?.parsed?.info, ta = t?.tokenAmount;
  if (!t || !ta) return null;
  decimals.set(a, ta.decimals);
  return { mint: t.mint, ...ta };
}
// Amounts stay integer base units; decimals are applied only to print.
const show = (a: string, t: Tok | null, slot: bigint | number) => {
  if (!t) return console.log(`slot ${slot}  ${a.slice(0, 8)}  closed or not a token account`);
  const s = t.amount.padStart(t.decimals + 1, "0"), cut = s.length - t.decimals;
  const text = t.decimals ? `${s.slice(0, cut)}.${s.slice(cut)}` : s;
  console.log(`slot ${slot}  ${a.slice(0, 8)}  mint ${t.mint.slice(0, 8)}  ${text} (${t.amount} base units, ${t.decimals} decimals)`);
};
// One getMultipleAccounts call for the whole screen; commitment left out, so kit uses confirmed.
async function snapshot() {
  const { context, value } = await rpc.getMultipleAccounts(accounts.map((a) => address(a)), { encoding: "jsonParsed" }).send();
  value.forEach((acc, i) => show(accounts[i]!, token(accounts[i]!, acc), context.slot));
}
// A failed snapshot is logged and never blocks the socket.
const safeSnapshot = () => snapshot().catch((e) => console.error("snapshot failed:", e instanceof Error ? e.message : e));
// Plain JSON-RPC over fetch to the same RPC URL, for the discovery calls below.
const call = async (method: string, params: unknown[]) => {
  const r = (await (await fetch(rpcUrl, { method: "POST", headers: { "x-api-key": key, "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) })).json()) as { result?: any; error?: { message: string } };
  if (r.error) throw new Error(`${method}: ${r.error.message}`);
  return r.result;
};
// No arguments: take token accounts from the newest USDC mint transaction that lists any.
async function discover(): Promise<string[]> {
  const sigs: { signature: string }[] = await call("getSignaturesForAddress", [USDC, { limit: 5 }]);
  for (const { signature } of sigs) {
    const tx = await call("getTransaction", [signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }]).catch(() => null);
    const keys: ({ pubkey: string } | string)[] = tx?.transaction.message.accountKeys ?? [];
    const found = new Set<string>();
    for (const b of tx?.meta?.postTokenBalances ?? []) { const k = keys[b.accountIndex]; if (k) found.add(typeof k === "string" ? k : k.pubkey); }
    if (found.size) return [...found].slice(0, 5);
  }
  return [];
}
// After a drop: reconnect; onopen re-subscribes and then reads the snapshot again.
const retry = () => setTimeout(() => follow(true), 2000);
// One socket, one accountSubscribe per account.
function follow(reconnect = false) {
  const ws = new WebSocket(wsUrl);
  const subs = new Map<number, string>();
  ws.onopen = () => {
    accounts.forEach((a, i) => ws.send(JSON.stringify({ jsonrpc: "2.0", id: i, method: "accountSubscribe", params: [a, { encoding: "base64", commitment: "confirmed" }] })));
    if (reconnect) safeSnapshot();
  };
  ws.onmessage = (ev) => {
    const m = JSON.parse(String(ev.data));
    if (m.error) console.error("subscribe failed:", m.error.message);
    else if (typeof m.result === "number") subs.set(m.result, accounts[m.id]!);
    else if (m.method === "accountNotification") {
      const { subscription, result } = m.params;
      const a = subs.get(subscription) ?? "unknown";
      show(a, token(a, result.value), result.context.slot);
    }
  };
  ws.onclose = retry;
}
if (!accounts.length) accounts.push(...await discover().catch((e) => { console.error("discovery failed:", e instanceof Error ? e.message : e); return []; }));
if (!accounts.length) { console.error("No position accounts: pass token-account addresses as arguments."); process.exit(1); }
await safeSnapshot();
follow();
```

The snapshot prints one line per account: the slot of the read, the first characters of the address and the mint, and the amount formatted with its decimals, followed by the base-unit amount. A closed account, or one that is not a token account, prints as such. Then the script opens one socket, subscribes to every account on it with the `base64` encoding and prints a line for each change. It reads the mint from bytes 0 to 32 of the account data and the amount as a little-endian u64 at byte 64, keeps the decimals from the snapshot, and treats an account with 0 lamports as closed. When the socket closes it waits 2 seconds and reconnects. On a reconnect the script re-subscribes and then reads the snapshot again, because changes sent while it was down are not replayed. A snapshot that fails is logged and the subscriptions stay up.

It is read-only. It signs nothing, sends nothing and holds no private key. It does not retry a 429.

## Following changes over a WebSocket

[Credits](https://carbium.sh/docs#limits) meter RPC and WebSocket work alike, so polling and subscriptions both draw on the account's credits. Polling also spends cells on every pass, 10 per pubkey, against the account-read class's [per-second rate](https://carbium.sh/docs#rpc) for the plan. A subscription costs 5, 25 or 200 credits to open by filter weight, with an account subscription in the middle at 25, and after that 20 credits per MiB sent. A [refused subscription](https://carbium.sh/docs#limits) is free. So the usual shape is one snapshot when the page loads and after a reconnect, and a subscription for every account on screen in between.

`accountSubscribe` sends an `accountNotification` on change for [accounts the stream carries](https://carbium.sh/docs#websocket). Connection and subscription counts are capped per account by tier, and Free carries 5 sockets. A socket per user reaches that cap early. Open one socket from your backend, subscribe to the union of your users' position accounts, and fan the changes out to browsers over your own channel.

A plain SOL wallet stays silent on `accountSubscribe`. For a native SOL row, use `logsSubscribe` with a mention of the wallet, which streams the transaction logs that touch it, and call `getBalance` when one arrives. `signatureSubscribe` sends one confirmation for a signature and then the subscription ends. That fits a pending row: your front end sends a transaction, the dashboard marks the row pending, and the confirmation clears it.

## Activity history per position

Most dashboards add a feed under each position. `getSignaturesForAddress` lists signatures for an address and `getTransaction` opens one. Both [cost 50 cells](https://carbium.sh/docs#rpc).

| Method | Cells per call | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|
| getSignaturesForAddress | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | 50 | 0.24 | 1.2 | 5 | 25 |

On Business the list call allows 100 req/s and `getTransaction` allows 5, so list signatures when the user opens a position and fetch a transaction only when they open its row. A finalized transaction does not change, so cache each result by signature.

The pages come from Carbium's own address index, which keeps up to 30 days. An empty page past that is the index's age limit and says nothing about the address's first transaction. Label the feed as the last 30 days.

## Buttons next to a position

A dashboard usually gets an exit or a rebalance button. The [quote plane](https://carbium.sh/docs#quote) answers on the same RPC endpoint with four methods: `quote`, `swap`, `health` and `prices`. `swap` returns [one unsigned transaction](https://carbium.sh/docs#swap) for a quote, and your software signs and sends it. A quote's `platformFee` is 5 bps (0.05%), an on-chain fee inside the transaction your software signs.

Quote plans are per account: Free at $0 with 10 quotes/s, Starter at $7 with 50/s, Pro at $28 with 150/s and Elite at $104 with 500/s. The `prices` method is one place to look when you want values beside balances; read [prices](https://carbium.sh/docs#prices) for its shape. The script uses none of these methods.

## Where it ends

- The script reads token accounts. A position that lives in a protocol's own accounts needs that protocol's layout and its account address, and the script prints raw token state only.
- Finding the addresses is your job; [Wallet token holdings](https://carbium.sh/library/usecase/wallet-token-holdings) shows how to find a wallet's token accounts. Eight methods are not served and answer [-32601](https://carbium.sh/docs#errors), among them `getProgramAccountsV2` and `getTokenLargestAccounts`. Keep each user's position addresses in your own store.
- It shows amounts and no values. Value needs a price per mint, and the script has none.
- A SOL wallet row needs `logsSubscribe` plus `getBalance`, because `accountSubscribe` stays silent for it.
- The activity feed reaches back 30 days at most.
- The [credit allowance](https://carbium.sh/docs#limits) depends on the plan: Free $0 with 500K credits once at sign-up, Dev $20 with 10M, Business $250 with 50M, Pro $500 with 200M.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A position row keeps its old amount or throws after the user closed the account. | A closed token account no longer exists, so the batched read returns null for it. Treat null as closed and drop the address from the user's list. A fully withdrawn account that is still open comes back with an amount of 0. |
| The service opens one socket per user and hits the account's socket cap. | Open one socket from the backend, subscribe to the union of position accounts and fan out to browsers yourself. |
| The native SOL row never updates. | accountSubscribe stays silent for a plain SOL wallet. Subscribe with logsSubscribe and a mention of the wallet, and call getBalance on each notification. |
| A refresh loop over every user gets 429s. | Push updates from subscriptions and keep the polling for the snapshot. Read each batch with getMultipleAccounts, and remember that N pubkeys bill as N account reads. |
| The activity feed is empty for an address that has older transactions. | The address index keeps up to 30 days. Label the feed as the last 30 days instead of showing an empty page. |
| Rows go stale after the socket drops. | After each reconnect, re-subscribe and then read the snapshot again, as the script does, because changes sent while the socket was down are not replayed. |

## Questions

### Why not one getAccountInfo per position?

The cells are the same at 10 per account, so a screen of fifty positions costs 500 cells either way. One getMultipleAccounts call makes it one request instead of fifty.

### Should I subscribe or poll?

Read a snapshot when the page loads and subscribe to the accounts on screen. Polling draws on the account's credits and also spends the account-read class's cells on every pass, 10 per pubkey, against its per-second rate for the plan. An account subscription costs 25 credits to open and then 20 per MiB sent.

### Can the browser call Carbium directly?

Keep the key on your server. All keys on an account share one budget, so a key copied out of a page spends the same budget your backend uses.

### Which commitment do these reads use?

The snapshot leaves commitment out, and @solana/kit 8.6.0 fills in confirmed. The subscription asks for confirmed explicitly. Pass finalized when you want settled numbers.

## Related

- [Wallet token holdings](https://carbium.sh/library/usecase/wallet-token-holdings) (Use cases, UC0005)
- [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#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#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#quote](https://carbium.sh/docs#quote)
- [carbium.sh/docs#swap](https://carbium.sh/docs#swap)
- [carbium.sh/docs#prices](https://carbium.sh/docs#prices)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
