library / Blockchain ideas / BI0040
Network fee trend chart
Run one small sampler on a timer and own a fee series: base and priority fees from each block, per-transaction percentiles of what senders paid, stored in SQLite and drawn in buckets, with a runnable main.ts.
Two fees to chart
A Solana transaction pays two fees, and a fee chart has to say which one it draws. The base fee is 5,000 lamports for each signature the transaction carries. The priority fee is optional: the sender sets a price in micro-lamports per compute unit, and the transaction pays that price times the compute unit limit it asked for. The fee in a block's transaction metadata is the two added together.
The base fee per signature stays at 5,000 until the protocol changes it, so drawing it gives a flat line. Spend the chart on the priority side, which can be read two ways. Price per compute unit is what senders bid, the number Priority fee per compute unit sets on a transaction. Lamports paid is what the chain collected, the number a product team puts in a monthly total. A block carries lamports, so the sampler stores those: the block total and the median and 90th percentile of what each transaction paid. Because a transaction's lamports are its price times its limit, a large compute unit limit raises them at the same price.
You own the series. The chain hands out one block at a time and no ready fee history. So the chart is a small sampler on a timer plus the table it writes into, and the history starts with the first run.
What one run samples
A run names the newest finalized slot, reads that block, and writes one row. The block read needs the slot, so the two calls go one after the other.
- getSlot at finalized commitment names the newest slot to read. Finalized sits 0 to 1 slots behind processed, so the block is there and cannot end up skipped with a dropped fork.
- getBlock for that slot with full transaction details returns each transaction's signatures and meta.fee. The code counts 5,000 lamports for every signature as base and the rest of fee as priority, then takes the median and the 90th percentile of the priority lamports per transaction, zeros included.
- A slot can have no block because its leader never produced one, and the read then fails or answers null. The code steps back one slot and tries again, up to five slots.
- One row goes into fees.db in the working directory. The code prints it, then draws a text sparkline of the stored rows.
// BI0040 · Network fee trend chart// https://carbium.sh/library/blockchainideas/network-fee-trend-chart// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { DatabaseSync } from "node:sqlite";import { 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 rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const why = (e: unknown) => (e instanceof Error ? e.message : String(e));const pct = (xs: number[], p: number) => [...xs].sort((a, b) => a - b)[Math.floor(p * (xs.length - 1))] ?? 0;const newest = await rpc.getSlot({ commitment: "finalized" }).send().catch((e) => { console.error(`getSlot failed: ${why(e)}`); return process.exit(1);});// Newest finalized block; a slot its leader skipped has none, so step back a slot.let row: { slot: number; txs: number; base: number; priority: number; p50: number; p90: number } | undefined;for (let s = newest, tries = 0; !row && tries < 5; s--, tries++) { try { const block = await rpc .getBlock(s, { commitment: "finalized", encoding: "json", maxSupportedTransactionVersion: 1, rewards: false, transactionDetails: "full", }) .send(); if (!block) continue; let base = 0, priority = 0; const paid: number[] = []; // priority lamports of each transaction for (const t of block.transactions) { if (!t.meta) continue; const signatures = t.transaction.signatures.length; const extra = Number(t.meta.fee) - 5000 * signatures; // 5000 lamports per signature is base base += 5000 * signatures; priority += extra; paid.push(extra); } row = { slot: Number(s), txs: paid.length, base, priority, p50: pct(paid, 0.5), p90: pct(paid, 0.9) }; } catch (e) { console.error(`slot ${s} skipped: ${why(e)}`); }}if (!row) { console.error("no block read in five slots"); process.exit(1);}const db = new DatabaseSync("fees.db");db.exec("CREATE TABLE IF NOT EXISTS fees (slot INTEGER PRIMARY KEY, at INTEGER, txs INTEGER, base INTEGER, priority INTEGER, p50 INTEGER, p90 INTEGER)");db.prepare("INSERT OR REPLACE INTO fees VALUES (?, ?, ?, ?, ?, ?, ?)") .run(row.slot, Math.floor(Date.now() / 1000), row.txs, row.base, row.priority, row.p50, row.p90);const rows = db.prepare("SELECT priority FROM fees ORDER BY slot DESC LIMIT 48").all() as { priority: number }[];const series = rows.reverse().map((r) => r.priority);const hi = Math.max(...series, 1);console.log(JSON.stringify(row));console.log(`last ${series.length} rows, priority lamports per block: ${series.map((v) => "▁▂▃▄▅▆▇█"[Math.round((v / hi) * 7)]).join("")}`);db.close();
run: CARBIUM_KEY=<YOUR_KEY> node main.ts
A run makes two calls, getSlot and getBlock, plus one more getBlock for each slot it steps back. RPC work draws on your credits, and limits are per account, so a timer that fires once a minute is a small, steady draw beside whatever else uses the same keys.
The series and its bucket sizes
The table holds one row per sampled block: slot, unix time, transaction count, base lamports, priority lamports, and the median and 90th percentile of priority lamports per transaction in that block. The slot is the primary key, so two runs that land on the same block replace one row and add none.
One block is about 200 ms of chain time, so a chart of raw rows is jagged. Group them into buckets with a query on the time column, sum the priority lamports in each group and average the 90th percentile.
| Bucket | Group by | Good for |
|---|---|---|
| 5 minutes | at / 300 | The last day on a live panel |
| 1 hour | at / 3600 | A week or a month |
| 1 day | at / 86400 | Long trends once the table holds months |
Sums answer what the network collected. The percentile answers what a transaction near the top of a block paid. Each run reads one block, so a bucket's sum covers the blocks you sampled and no others. Divide by the row count in the bucket, or compare only buckets with the same count, before you read a rise as a rise in fees.
Drawing it
The script prints a sparkline of the stored rows so the first run already shows the series. A dashboard reads the same table through a small endpoint that runs the bucket query and returns the points as JSON.
Two series fit one chart: priority lamports per bucket as bars, and the 90th percentile as a line on a second axis, since a bucket's sum grows with the number of blocks and transactions behind it while the percentile describes one transaction. One congested minute can pay many times what a normal hour does, so use a log axis or clip the top of the bars. Teams that already run Grafana can point it at the table or at the same query, as in Grafana network metrics.
Where it ends
- History starts when the sampler starts. Each run adds one block, so a chart shows days only after days of running. It does not backfill old fees.
- A row is one node's view of one block. A block's sum swings with how many transactions landed in it, so compare buckets by their row counts.
- The percentiles cover every transaction in the block, so a block where most senders paid no priority fee reads a median of 0 and the 90th percentile shows what the paying ones sent.
- The base count uses each transaction's signatures. Precompile verifications (ed25519, secp256k1, secp256r1) also pay 5,000 lamports each but are not in that list, so their share lands in the priority column.
- Failed transactions pay fees too, and the block sums count them. A transaction dropped before it landed pays nothing and leaves no trace.
- A tip sent as a transfer inside a transaction is not in meta.fee, so the priority column undercounts what senders spent.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The median column reads 0. | Most transactions in that block paid no priority fee, so the middle one pays nothing. Chart the 90th percentile column or the block sum, which show the transactions that did pay. |
| The run prints a -32015 message and stores nothing. | The block holds a v1 transaction and the call left out maxSupportedTransactionVersion or set it to 0. Keep it at 1. |
| All five slots print as skipped. | Read the message on each line. A skipped slot has no block, so run again. If the lines show a rate limit, space the timer further apart. |
| Two runs back to back store one row. | Both read the same finalized slot, or one stepped back onto the block the other stored, and the slot is the primary key. Runs more than a slot or two apart store separate rows. |
| Every call answers 401. | The key is unknown at the door. Check that CARBIUM_KEY holds the whole key with nothing cut off. |
| The block read answers 429. | The call went over its rate. Wait for the retry-after hint, then run again, and lower how often the timer fires if it repeats. |
Questions
Can I chart fees from before I started sampling?
Not with this sampler. Each run adds one block, so the series begins at the first run. Reading old blocks one by one is a separate job that this file does not do.
Which number goes in a dashboard headline?
Priority lamports per hour says what senders paid in total, and the 90th percentile says what a transaction near the top of a block paid. Show the first as a total and the second as the current level.
How often should the timer fire?
Each run adds one block, so more runs give a bucket more samples. A run every minute gives 60 rows an hour, which is enough for a steady hourly line. Pick the interval from the row count you want per bucket.