Soldev

Estimate compute units

Last updated:

We can estimate the compute units for our transactions. A good estimate will increase the likelihood of our transactions landing.

import { getSetComputeUnitLimitInstruction } from "@solana-program/compute-budget";
import { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from "@solana/kit";

// Create an estimator function.
const rpc = createSolanaRpc("http://127.0.0.1:8899");
const getComputeUnitEstimateForTransactionMessage = getComputeUnitEstimateForTransactionMessageFactory({
    rpc,
});

// Create your transaction message.
const transactionMessage = pipe(
    createTransactionMessage({ version: "legacy" }),
    /* ... */
);

// Request an estimate of the actual compute units this message will consume. This is done by
// simulating the transaction and grabbing the estimated compute units from the result.
const computeUnitsEstimate = await getComputeUnitEstimateForTransactionMessage(transactionMessage);

// Set the transaction message"s compute unit budget.
const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(
    getSetComputeUnitLimitInstruction({ units: computeUnitsEstimate }),
    transactionMessage,
);

This works because validators are incentivized to pack as many transactions inside each block as possible. If you do not provide an estimate validators will assume 200k. The lower you can estimate the more likely its going to be picked up and packed in.