library / Blockchain ideas / BI0055
Stream tip overlay
A tip feed for a streamer's overlay: it polls a wallet and its USDC token account on Carbium, turns each new transaction into one line with amount, sender and memo, and keeps a top-tippers tally, with a runnable main.ts.
What the overlay needs
A streamer shows a wallet address on screen. A viewer sends USDC or SOL to it, and a moment later the broadcast draws a line with the amount, who sent it and a short message. Streamers, podcasters and writers with a tip page all want that line. The overlay software draws from a feed with one record per tip.
main.ts polls the tip wallet and the wallet's USDC token accounts, turns each new transaction into one line and keeps a tally of the top tippers. The message is the memo the viewer attached to the transfer. A hackathon team can run it against a wallet of their own, send themselves a tip with a memo and watch the line print.
Why two addresses
A SOL tip changes the wallet's own balance, so the transaction appears in the wallet's signature list. A USDC tip lands in a token account, and the wallet only owns that account.
A transfer into a token account that already exists lists the sender's token account, the receiving token account and the sender's authority. The receiving wallet is in none of them, so the wallet's signature list never shows that tip. The tip that creates the wallet's USDC account lists the wallet as owner, and so does any transfer that carries an idempotent create instruction; a plain transfer into the existing account does not.
A feed that polls only the wallet therefore looks fine in a first test and goes quiet afterwards. The code asks getTokenAccountsByOwner for the wallet's accounts on the USDC mint at the start of each cycle and polls each one. A wallet can own more than one token account for a mint, which is why the code takes the list from the chain instead of deriving a single address. The first tip can show up under the wallet and under the new token account at once, so signatures go into a set before any lookup.
The cursor in SQLite
For each address the code stores the newest signature it has fully processed. The next poll passes it as until to getSignaturesForAddress, which then returns only newer signatures, newest first. An address with no stored signature starts from its latest five, so the first run shows a few recent tips and does not replay a whole history.
The cursor moves only after every signature from the cycle has been looked up. A failed lookup is tried again in the same cycle, for up to three passes, and a cycle that still has failures leaves the cursor where it was. The next poll then fetches the same page again. The tips table has a primary key on signature and unit, so a transaction seen a second time inserts nothing and prints nothing. Signature history pagination covers the paging in more detail.
From transaction to line
Each new signature gets one getTransaction call with jsonParsed encoding and maxSupportedTransactionVersion: 1. A call that leaves the version out gets -32015 for a v1 transaction. The call sits in a try, so one failing signature goes back on the queue and the loop carries on. The signature pages and lookups leave commitment out, so @solana/kit fills in confirmed and a tip shows at confirmed commitment. Only discover(), which runs when you pass no wallet, reads getSlot and getBlock at finalized.
- A null result is skipped. A result with err set is skipped too: a failed transaction moved nothing into the tip wallet, because the fee payer is still charged the fee and nothing else changes hands.
- The tip is a positive change. For SOL it is the wallet's balance after minus before. For USDC it is the change on every token account of the USDC mint that the wallet owns.
- The sender is the account whose balance of the same unit fell furthest in that transaction. For USDC the code reports the owner of that token account.
- The message is the text of an spl-memo instruction, cut to 80 characters.
| Field | Where it comes from | Example |
|---|---|---|
| Amount | balance after minus before, kept as a bigint until it is printed | 1500000000 lamports prints as 1.5 SOL |
| Sender | largest fall of the same unit in the transaction | the address that paid, or the owner of the paying token account |
| Message | the memo instruction's text | thanks for the stream |
| Unit | SOL, or USDC for the mint the code watches | USDC with 6 decimals |
// BI0055 · Stream tip overlay// https://carbium.sh/library/blockchainideas/stream-tip-overlay// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { DatabaseSync } from "node:sqlite";import { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import type { Address, Signature } 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 rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const GAP_MS = Number(process.env.GAP_MS ?? 1000); // 4200 on Free, where getTransaction runs at 0.24 req/sconst POLL_MS = Number(process.env.POLL_MS ?? 15000);const db = new DatabaseSync(process.env.TIP_DB ?? "tips.db");db.exec("CREATE TABLE IF NOT EXISTS cursor (addr TEXT PRIMARY KEY, sig TEXT); CREATE TABLE IF NOT EXISTS tips (sig TEXT, unit TEXT, amount INTEGER, sender TEXT, memo TEXT, PRIMARY KEY (sig, unit))");const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));const paced = async <T>(f: () => Promise<T>): Promise<T> => { await sleep(GAP_MS); return f(); };const fmt = (unit: string, n: number | bigint) => `${Number(n) / (unit === "SOL" ? 1e9 : 1e6)} ${unit}`;async function discover(): Promise<string> { // with no argument: first account whose balance rose in a recent block const slot = await rpc.getSlot({ commitment: "finalized" }).send(); for (let i = 0; i < 5; i++) { try { const block: any = await paced(() => rpc.getBlock((slot - BigInt(i)) as typeof slot, { transactionDetails: "accounts", rewards: false, commitment: "finalized", maxSupportedTransactionVersion: 1 } as any).send()); for (const t of block.transactions) { const n = t.meta.err ? -1 : t.meta.postBalances.findIndex((p: number, j: number) => j > 0 && p > t.meta.preBalances[j]); if (n > 0) return t.transaction.accountKeys[n].pubkey; } } catch (e) { console.error("block read failed:", msg(e)); } } throw new Error("no account with a rising balance in the newest blocks");}async function lookup(sig: string, wallet: string): Promise<number> { const tx: any = await paced(() => rpc.getTransaction(sig as Signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()); if (!tx?.meta || tx.meta.err) return 0; // null: the signature is older than the ledger floor const m = tx.meta; const keys: string[] = tx.transaction.message.accountKeys.map((k: { pubkey: string }) => k.pubkey); const memo: string = tx.transaction.message.instructions.find((ix: { program?: string }) => ix.program === "spl-memo")?.parsed ?? ""; const moves = keys.map((k, i) => ({ unit: "SOL", acct: k, who: k, d: BigInt(m.postBalances[i]) - BigInt(m.preBalances[i]) })); for (const b of (m.postTokenBalances ?? []).filter((x: { mint: string }) => x.mint === USDC)) { const pre = m.preTokenBalances?.find((p: { accountIndex: number }) => p.accountIndex === b.accountIndex)?.uiTokenAmount.amount ?? "0"; moves.push({ unit: "USDC", acct: keys[b.accountIndex], who: b.owner, d: BigInt(b.uiTokenAmount.amount) - BigInt(pre) }); } let added = 0; for (const t of moves.filter((x) => x.d > 0 && (x.unit === "SOL" ? x.acct === wallet : x.who === wallet))) { const from = moves.filter((x) => x.unit === t.unit && x.d < 0).sort((a, b) => (a.d < b.d ? -1 : 1))[0]?.who ?? "unknown"; if (!db.prepare("INSERT OR IGNORE INTO tips VALUES (?, ?, ?, ?, ?)").run(sig, t.unit, t.d, from, memo.slice(0, 80)).changes) continue; added++; console.log(`TIP +${fmt(t.unit, t.d)} from ${from.slice(0, 6)}${memo ? ` ${JSON.stringify(memo.slice(0, 80))}` : ""}`); } return added;}function tally(): void { for (const unit of ["SOL", "USDC"]) { const rows = db.prepare("SELECT sender, SUM(amount) AS total FROM tips WHERE unit = ? GROUP BY sender ORDER BY total DESC LIMIT 3").all(unit) as any[]; if (rows.length) console.log(`TOP ${unit}: ${rows.map((r) => `${r.sender.slice(0, 6)} ${fmt(unit, r.total)}`).join(", ")}`); }}async function cycle(wallet: string): Promise<void> { const owned = await paced(() => rpc.getTokenAccountsByOwner(wallet as Address, { mint: USDC as Address }, { encoding: "jsonParsed" }).send()); const todo = new Set<string>(), newest = new Map<string, string>(); for (const a of [wallet, ...owned.value.map((v) => v.pubkey as string)]) { const row: any = db.prepare("SELECT sig FROM cursor WHERE addr = ?").get(a); const page = await paced(() => rpc.getSignaturesForAddress(a as Address, { limit: row ? 100 : 5, until: row?.sig as Signature | undefined }).send()); if (page.length) newest.set(a, page[0].signature); for (const s of page) if (!s.err) todo.add(s.signature); } let queue = [...todo].reverse(), fresh = 0; for (let pass = 0; pass < 3 && queue.length; pass++) { const failed: string[] = []; for (const sig of queue) { try { fresh += await lookup(sig, wallet); } catch (e) { failed.push(sig); console.error(`lookup ${sig.slice(0, 8)} failed, requeued:`, msg(e)); } } queue = failed; } if (!queue.length) for (const [a, sig] of newest) db.prepare("INSERT OR REPLACE INTO cursor VALUES (?, ?)").run(a, sig); if (fresh) tally();}async function main(): Promise<void> { const wallet = process.argv[2] ?? (await discover()); console.log(`watching ${wallet}`); for (;;) { try { await cycle(wallet); } catch (e) { console.error("cycle failed:", msg(e)); } await sleep(POLL_MS); }}main().catch((e) => { console.error(msg(e)); process.exit(1); });
run: CARBIUM_KEY=<YOUR_KEY> node main.ts [wallet]
A fee payer's fall includes the fee, so a SOL sender who pays their own fee shows a few thousand lamports more than they sent. The tip amount is read from the wallet's side and stays exact.
Pace, tally and what your server pushes
After any cycle that inserted a tip, the code sums the tips table by sender and prints the top three for SOL and for USDC. The two units sit in separate lists because SOL and USDC are different assets, so their amounts cannot be added together.
main.ts prints one deduplicated line per signature and unit for your server to push, because the code has no browser feed of its own. A small HTTP server can read those lines, or the tips table, and send each new row to the overlay page over server-sent events or a WebSocket of yours. The browser source in streaming software loads that page and draws the animation.
Every lookup and every signature page costs 50 cells, and the code spaces its calls by GAP_MS. The gap has to fit getSignaturesForAddress and getTransaction, the two methods in the table.
| Plan | getSignaturesForAddress req/s | getTransaction req/s | GAP_MS |
|---|---|---|---|
| Free ($0) | 0.24 | 0.24 | 4200 |
| Dev ($20) | 1.2 | 1.2 | 1000, the default |
| Business ($250) | 100 | 5 | 200 |
| Pro ($500) | 500 | 25 | 40 |
Limits are per account, so other tools on the same keys draw on the same budget. A cycle with two addresses makes at least three calls before any lookup and then sleeps POLL_MS, 15000 ms by default. On Free the three calls take about 13 seconds at the 4200 ms gap. A tip that lands just after a poll waits out the 15-second sleep, those 13 seconds and one 4.2-second lookup, so the overlay lags it by about 32 seconds in the worst case. That is acceptable for a tip line and slow for a live reaction.
On Dev the same sum is 3 seconds of calls, a 1-second lookup and the sleep: about 20 seconds in the worst case and about 10 on average. Lowering POLL_MS is what shortens it.
Where it ends
- The feed is a poll, so a tip appears after the next cycle plus the gaps. A logsSubscribe with a mentions filter on the wallet hears its transactions as they land, but a plain SOL wallet gets nothing from accountSubscribe, and a transfer into an existing token account never mentions the wallet, so a socket has to subscribe to the token accounts as well. Multi-address deposit monitor builds that pattern.
- Only SOL and the USDC mint are read. A tip in another token produces no line. Change the mint and the decimals in the code to watch another one.
- Amounts are net per transaction. A viewer who sends from an exchange shows the exchange's address as the sender, and the message is empty unless the sender added a memo instruction at the top level.
- The memo is text a stranger wrote. Escape it before it goes into a page, and cap its length on your server as well.
- History reaches back 30 days at most, and the first run reads only the latest five signatures per address. A later poll reads at most 100 new signatures per address and the cursor then jumps to the newest, so a burst of more than 100 between polls drops the older ones.
- With no wallet argument the code picks an account whose balance rose in a recent block, so a demo run prints any incoming SOL as a tip.
- The code runs in a loop and prints. It has no sound, no alert queue and no moderation step, and it does not refund or hide a tip that looks abusive.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| USDC tips stop showing after the first one, while SOL tips keep appearing. | The feed is reading only the wallet. A transfer into an existing token account never lists the wallet, so the token account has to be polled. Check that getTokenAccountsByOwner returns the account for the USDC mint and that the cycle did not fail before the poll. |
| getTransaction answers -32015 for some signatures. | A v1 transaction needs maxSupportedTransactionVersion: 1 in the config. The code sets it. If you copy the call into your own server, keep it in the config object. |
| getTransaction returns null for a signature the page listed, so no line prints. | Signature pages reach below the validator's ledger floor, so an older signature can list and then answer null. The code skips it. Test on the newest signatures. |
| getTransaction is refused with 429 and the same signature keeps coming back. | The code requeues the signature. Raise GAP_MS to 4200 on Free and check what else on the account calls, since the limit is shared across its keys. |
| A tip prints with the sender unknown or an empty message. | The sender is the largest fall of the same unit, and a tip paid through a program can leave none. The memo is read from top-level instructions only, so a memo inside a program's inner call is not shown. |
Questions
Can I show who tipped by name instead of an address?
Ask the viewer to put a name in the memo, which the line already carries, or map known addresses to names in your own table. The chain holds nothing else about the sender.
Why does the code poll instead of subscribing?
Polling needs one cursor per address and no reconnect logic, which keeps the file short. A socket gives a faster line and costs a reconnect path, and it needs the token accounts subscribed as well.
How do I make it show tips in another token?
Swap the mint constant and the divisor in the formatting line, and rename the USDC unit label in lookup() and tally(), or the new token's lines still print as USDC. The token-balance code reads any mint you name, and the tally lists each unit separately.
What does the first run show on a wallet with no history?
Nothing past the watching line until a tip lands. Send a small transfer with a memo to the wallet and the line appears after the next cycle.