---
id: HS0031
title: "Compute unit limit from simulation"
url: https://carbium.sh/library/howsolana/compute-unit-limit-from-simulation
collection: How to use Solana
category: Priority fees and compute
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Compute unit limit from simulation

One TypeScript file reads the compute units that recent transactions on a program consumed, adds a margin and prints the compute-unit limit to set. It only reads: no keypair, no signature, no transaction sent.

## What the simulated number is

Every transaction runs under a compute-unit budget. Without a compute budget instruction the runtime grants 200,000 units for each non-builtin instruction, and a transaction can ask for at most 1,400,000 in total. A `SetComputeUnitLimit` instruction replaces the default with a number you choose. If the program burns past that number, the transaction fails with an exceeded-meter error and the fee is still charged.

The right number is the one the transaction will actually use, plus room. The usual way to find it is to simulate, and the figure that comes back is the "simulated compute unit" people ask about.

1. Build the transaction with the limit set to the 1,400,000 maximum and send it to `simulateTransaction` with `replaceRecentBlockhash` on and `sigVerify` off.
2. Read `unitsConsumed` from the result.
3. Add the margin and clamp the sum to 1,400,000, as the file below does with landed numbers.
4. Rebuild the transaction with the limit and price instructions at the front and the new limit in place.

A simulation and a landed transaction report the same quantity. A landed transaction records it in its metadata as `computeUnitsConsumed`. That makes a landed transaction a way to see the number without sending anything of your own, and it is what the file below reads.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips the types on load. The first argument is an address, usually a program, and the second is how many recent signatures to sample. The file lists them, fetches each transaction and prints the units it consumed with a limit that adds a 10 percent margin.

`main.ts` (run: `node main.ts [address] [sample-size]`)

```ts
// HS0031 · Compute unit limit from simulation
// https://carbium.sh/library/howsolana/compute-unit-limit-from-simulation
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import {
  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);
}
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url, headers: { "x-api-key": key } }),
);

// Usage: node main.ts [address] [sample-size]
const [addrArg = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4", sizeArg = "8"] = process.argv.slice(2);
const MAX_LIMIT = BigInt(1_400_000);

// Newest signatures first. Both calls leave commitment out, so kit fills in confirmed.
const sigs = await rpc.getSignaturesForAddress(address(addrArg), { limit: Number(sizeArg) }).send();
const landed = sigs.filter((s) => s.err === null);
if (landed.length === 0) {
  console.error("No successful signatures for that address in the index.");
  process.exit(1);
}

const results = await Promise.allSettled(
  landed.map((s) =>
    rpc.getTransaction(s.signature, { maxSupportedTransactionVersion: 1, encoding: "json" }).send(),
  ),
);

const limits: bigint[] = [];
results.forEach((r, i) => {
  const sig = landed[i].signature.slice(0, 12);
  if (r.status === "rejected") {
    console.log(`${sig}  failed: ${String(r.reason)}`);
    return;
  }
  const used = r.value?.meta?.computeUnitsConsumed;
  if (used === undefined) {
    console.log(`${sig}  no computeUnitsConsumed (transaction null or older than the node keeps)`);
    return;
  }
  // Margin of 10 percent, rounded up, never above the 1,400,000 ceiling.
  const withMargin = (used * BigInt(110) + BigInt(99)) / BigInt(100);
  const limit = withMargin > MAX_LIMIT ? MAX_LIMIT : withMargin;
  limits.push(limit);
  console.log(`${sig}  used ${String(used).padStart(9)}  limit ${String(limit).padStart(9)}`);
});

if (limits.length > 0) {
  const top = limits.reduce((a, b) => (a > b ? a : b));
  console.log(`${limits.length} transactions read; largest limit to set: ${top}`);
}
```

The list call and the fetches go to `https://services.carbium.sh` through one `rpc` object. Neither call sets a commitment, so `@solana/kit` fills in `confirmed`, where the JSON-RPC server alone would use `finalized`. Each fetch is settled on its own, so one failed lookup is printed and the rest still count.

All arithmetic stays in `bigint`. The margin is applied as `used * 110 / 100`, rounded up, and the result is clamped to the 1,400,000 ceiling, because a larger request is not accepted by the runtime.

## Reading the output

Each line holds a signature prefix, the units that transaction consumed and the limit the margin gives. The last line is the largest of them, which is the number to use if your transaction can take any of the sampled paths.

| Consumed | With 10 percent margin | Limit to set |
|---|---|---|
| 45,000 | 49,500 | 49,500 |
| 120,000 | 132,000 | 132,000 |
| 1,300,000 | 1,430,000 | 1,400,000 |

A program with one fixed path, such as a transfer, gives nearly the same figure on every line. A router or a lending program gives a spread, because the units depend on how many accounts and steps a particular call touches. Read the spread before you pick: a limit taken from the smallest line fails the heavy calls.

> Sampling a busy program mixes different calls, so the printed maximum describes the program in general. For your own transaction, use your own signature or your own simulation, since only that one has your exact accounts.

## Setting the limit and the fee

Put `getSetComputeUnitLimitInstruction` and `getSetComputeUnitPriceInstruction` from `@solana-program/compute-budget` at the front of the message. Each of those two instructions costs about 150 units itself, which the simulation already includes when they are present in the simulated message, so simulate the final instruction list with both of them in it.

The priority fee is charged on the limit you request, whatever the program burns. A limit of 1,400,000 where 50,000 would do pays for 28 times the units. That is the reason to simulate at all, and the reason the price from [priority fee per compute unit](https://carbium.sh/library/howsolana/priority-fee-per-compute-unit) always travels with a measured limit.

A margin of 10 percent is a starting point. State can move between the simulation and the landing: an account that exists by then skips a creation step, a pool crosses a tick boundary, a route changes. A transaction whose path is stable can run a tighter margin, and one that touches changing state wants more. If a landed transaction reports `computeUnitsConsumed` close to its limit, raise the margin.

## On Carbium

The file calls two methods. [`getSignaturesForAddress`](https://carbium.sh/docs#rpc) and `getTransaction` cost 50 cells each. Sampling 8 signatures is at most 9 calls, so keep the sample small and cache the result for a program instead of reading it on every send.

`getSignaturesForAddress` is served from an address index that keeps up to 30 days, and its pages reach below the validator's ledger floor. For a very old signature `getTransaction` can answer null, so the file treats null as a skipped line. Sampling the newest signatures avoids it.

Mainnet carries v1 transactions. A `getTransaction` call without `maxSupportedTransactionVersion` set to 1 answers -32015 for one of them, which is why the file passes it. The failure is walked through in [transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015). [Limits](https://carbium.sh/docs#limits) are per account, so all keys on your account draw on one budget.

## Where it ends

The file reads a landed number and does not simulate your own transaction. It cannot know the units of a transaction you have not built. For that, call `simulateTransaction` from your sender with the final message and take `unitsConsumed` from its result, then apply the same margin and clamp shown here.

A landed transaction's `computeUnitsConsumed` is for one run under the state of that slot. Another run of the same instruction list can use more or fewer units. The margin covers ordinary drift, and it does not cover a program that changes path on large inputs.

Units used by a failed transaction are still recorded, but a failure usually stops early and reads low. The file skips transactions that carry an error for that reason, so a program that mostly fails on chain shows a thin sample.

The file prints a limit only. The price comes from sampling recent prioritization fees, and the 5,000 lamport base fee per signature is charged on top of both.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Every line says no computeUnitsConsumed. | The transaction came back without metadata, or it was null because it is older than the node keeps. Sample the newest signatures, which this file does by default, and check the address has recent activity. |
| Error -32015 on getTransaction. | The transaction is v1 and the call left `maxSupportedTransactionVersion` out or set it to 0. Pass 1 as the file does. |
| The sample is empty. | The address has no signatures in the index window, or you passed a wallet that is idle. Use a program with recent traffic; history older than the 30-day address index is not served. |
| The sent transaction fails with an exceeded compute units error. | The limit was below what the program used on that run. Raise the margin, or take the limit from the largest sampled value instead of the typical one. |
| Every sampled line clamps at 1,400,000. | The program's calls run near the ceiling, so the margin pushes each one past it and the clamp holds them at the maximum. Read the consumed figure itself, use a smaller margin for that program, or split the work across transactions. |

## Questions

### Is the simulated compute unit the same as the compute-unit limit?

No. The simulated figure is what the transaction used, and the limit is the ceiling you request. You set the limit a little above the simulated figure.

### Why simulate with 1,400,000 first?

A low limit would make the simulation itself fail partway and report only the units used before the failure. The maximum lets it run to the end, so the figure is complete.

### Does a lower limit lower the fee?

Yes. The priority fee is the limit times the price per compute unit, divided by 1,000,000 and rounded up, so every unit you do not request is a unit you do not pay for.

### Do I need a private key to run the file?

No. It lists signatures and reads transactions that already landed. The Carbium key only identifies your account to the RPC.

### Should every transaction set a compute-unit limit?

Yes, for any transaction you build yourself. Without one the runtime grants 200,000 units per non-builtin instruction, and a measured limit keeps the priority fee close to what the transaction uses.

## Related

- [Priority fee per compute unit](https://carbium.sh/library/howsolana/priority-fee-per-compute-unit) (How to use Solana, HS0015)
- [Transaction explainer](https://carbium.sh/library/blockchainideas/transaction-explainer) (Blockchain ideas, BI0003)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
