services
Get a key

library / How to use Solana / Priority fees and compute / HS0152

Program compute usage profile

The compute units a program uses change with each instruction, account set and branch it takes. This file takes a program address, reads its newest successful transactions and prints the spread of units the program used in each one.

By Carbium · Priority fees and compute · HS0152 · updated 2026-11-23

01

Why the count moves

A program has no fixed compute cost. The units one call uses depend on what the instruction asks for: how many accounts it reads, how long its data is, which branch the code takes and how many cross-program invocations it makes. Two calls to the same instruction can differ by a wide margin, so one number taken from one transaction says little about the program.

Solana reports this in two places. A transaction's metadata carries one total, computeUnitsConsumed, for the whole transaction. The program log lines split the same spend by program. Each invocation writes a line of the form Program <id> consumed <used> of <limit> compute units, where the limit is the budget the runtime gave that call. Summing the lines for one program id gives that program's spend in the transaction. A program that calls itself through a cross-program invocation writes more than one line, and the sum counts all of them.

The request sets the ceiling. A transaction that sends no compute budget instruction gets 200,000 units for each non-builtin instruction, up to 1.4 million in total. A transaction can set its own limit instead. The priority fee is the price per unit times the limit, so an oversized limit costs more whenever a priority price is set. The limit is a cap the program stays under or hits, and the consumed value is what it used.

This entry answers a narrow question: what does the program spend across its recent successful calls, so that you can set a budget that holds for most of them. It does not forecast a call that has not happened yet.

02

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types on its own. The program address is the first argument and the count is the second, with a default of 5 and a ceiling of 20. The file lists the newest signatures for the program, keeps the ones that did not fail and reads each transaction with maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and without that option JSON-RPC errors answers -32015 for them.

main.ts
// HS0152 · Program compute usage profile// https://carbium.sh/library/howsolana/program-compute-usage-profile// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport * as kit from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (apiKey === undefined || apiKey === "") {  console.error("CARBIUM_KEY is missing: export it, then run this file again.");  process.exit(1);}const endpoint = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const transport = kit.createDefaultRpcTransport({  url: endpoint,  headers: { "x-api-key": apiKey },});const rpc = kit.createSolanaRpcFromTransport(transport);const SAMPLE_CAP = 20;const PROGRAM_LINE = /^Program (\S+) consumed (\d+) of \d+ compute units/;const [programText, countText = "5"] = process.argv.slice(2);const programId = kit.address(programText ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");const count = Math.min(Math.max(Number(countText) || 5, 1), SAMPLE_CAP);const newest = await rpc  .getSignaturesForAddress(programId, { limit: count, commitment: "confirmed" })  .send();const succeeded = newest.filter((row) => row.err === null).map((row) => row.signature);console.log(`${programId}: ${succeeded.length} successful of ${newest.length} newest signatures`);const outcomes = await Promise.allSettled(  succeeded.map((signature) =>    rpc      .getTransaction(signature, {        encoding: "json",        maxSupportedTransactionVersion: 1,        commitment: "confirmed",      })      .send(),  ),);const unitsPerCall: number[] = [];let missing = 0;let rejected = 0;for (const outcome of outcomes) {  if (outcome.status === "rejected") {    rejected += 1;    console.log(`read failed: ${String(outcome.reason)}`);    continue;  }  const tx = outcome.value;  if (tx === null) {    missing += 1;    continue;  }  let sum = 0;  let matched = false;  for (const text of tx.meta?.logMessages ?? []) {    const hit = PROGRAM_LINE.exec(text);    if (hit !== null && hit[1] === programId) {      sum += Number(hit[2]);      matched = true;    }  }  if (matched) unitsPerCall.push(sum);}console.log(`null=${missing} failed=${rejected} with-program-logs=${unitsPerCall.length}`);if (unitsPerCall.length === 0) {  console.log("no transaction in the sample logged this program");  process.exit(0);}const ordered = [...unitsPerCall].sort((a, b) => a - b);const mid = ordered[Math.floor(ordered.length / 2)];console.log(`compute units: min=${ordered[0]} median=${mid} max=${ordered[ordered.length - 1]}`);console.log(`all: ${ordered.join(" ")}`);

run: node main.ts <program-address> [count]

Each getTransaction read costs 50 cells, and the signature list costs 50 more. A run at the cap of 20 therefore charges 1,050 cells at most. The reads are settled one by one with Promise.allSettled, so one failed read does not hide the others, and the file prints what failed. The address index behind the signature list is the subject of the section on sampling below.

03

Reading the summary

OutputMeaning
successful of newest signaturesHow many of the listed signatures are not failed transactions. Failed ones are left out so the sample shows calls that completed.
null=Transactions Carbium returned as null. They are left out of the spread.
with-program-logs=Transactions whose logs contain at least one line for this program id.
min, median, maxThe spread of the summed units over those transactions. The median is the middle value of the sorted list.
all:Each transaction's total, sorted, so the shape of the spread shows and not only its two ends.

A wide gap between min and max means the program's cost depends on its input. Read the median as the typical call and plan a budget from the upper end of the spread. Test that budget on a second run before you rely on it.

$The sample reads the newest transactions at one moment. Run the file again later and the list will have moved, so compare spreads from several runs over time.
04

Sampling the calls

The signature list is the only source of the sample. getSignaturesForAddress pages come from an address index that keeps up to 30 days, so the newest signatures are the ones this file reads with confidence. Each read is a separate call under the rate limits. A call over its rate waits once and is served if its cells refill within one second. Past that it gets 429 with a retry-after hint. The file does not retry on its own.

  • Keep the count small on a first run. Five transactions show whether the program's cost varies at all.
  • Raise the count only after the spread holds across two runs.
  • Pass a program address from your own code. Do not widen the list to every program on the network.
05

Where it ends

The sample holds the newest successful signatures, so it reflects recent calls only. A signature the index lists can still read as null, because the validator's ledger floor sits above some older transactions. The file counts those nulls and leaves them out of the spread. A null removes that transaction from the spread, and an empty sample says only that no logged reads came back.

Each invocation gives one total in its log line. The line does not split that total between the program's own instructions and the work of the programs it calls, so the figure reports the cost of the call and says nothing about its cause. For the cause, read the instruction data and the accounts of a high-spend transaction in full.

The sample cannot tell you the cost of a call you have not sent. A program's cost moves with its state, its accounts and the traffic on the network at the time. Use the spread as a planning range and refresh it when the program changes.

Failed transactions are not in the sample. A call that runs out of units and fails never reaches the summary, so the figures understate the spend that ends in a failure. Check the failed calls separately before you set a budget from these numbers.

!Do not set a budget from one transaction. A single read is one point in a spread, and the spread is what the budget has to cover.
06

When it goes wrong

what goes wrongwhat to do
Every transaction reads as null, or the summary shows zero transactions.Carbium lists the signatures but returns null for some of them, usually because they sit below the ledger floor. Pick a program address with recent activity so the newest signatures are current, then run again. A count of zero also means the program wrote no log line for itself in those transactions.
Error -32015 on the transaction read.The call dropped maxSupportedTransactionVersion: 1. Put the option back in the getTransaction call. Without it, Carbium answers -32015 for a v1 transaction, and that answer costs nothing.
HTTP 429 with a retry-after hint.Wait for the number of seconds in the header, then run again with a smaller count. The file does not retry on its own.
The sample median sits far from a simulation of the same instruction.A simulation runs the instruction against the current state, while the sample reads transactions that landed earlier. Compare the whole spread first, then check the accounts and data each sampled transaction used.
Error -32601 method not found.Check the method name in the code. Carbium does not serve some methods and answers -32601 for them, so do not retry that call. Compute unit limit from simulation covers how to size the limit for one call.
07

Questions

Why does the same instruction use different compute units?

The work inside the program depends on its data, its accounts and the branch it takes, and each cross-program call adds more. The runtime charges for what each call actually does, so one number cannot describe every call.

Is computeUnitsConsumed enough?

It gives one total for the whole transaction, including any other programs in it. The log lines give the share for each program id, and that is what this file sums.

How many transactions do I need to set a budget?

Start with five to see whether the cost varies at all. Use enough reads to see a stable median and maximum, and check the spread again on a second run before you rely on it.

Can this list every call a program has ever made?

No. It reads the newest signatures within the 30-day window of the address index, and older history is not served. Use it to plan a budget, not to count all activity.