All of the program clients are now autogenerated (using Codama) and are available in the @solana-program
namespace. You'll want to use @solana-program/compute-budget
and @solana-program/system
.
import {
getSetComputeUnitLimitInstruction,
getSetComputeUnitPriceInstruction,
} from '@solana-program/compute-budget';
import { getTransferSolInstruction } from '@solana-program/system';
const message = pipe(
createTransactionMessage({ version: 0 }),
// ...other message transforms
m => appendTransactionMessageInstructions(
[
getSetComputeUnitLimitInstruction({ units: 1000000 }),
getSetComputeUnitPriceInstruction({ microLamports: 1 }),
getTransferSolInstruction({
amount: lamports(10000000n),
source: sourceAddress,
destination: destinationAddress,
}),
],
m
),
);
There is also a utility that you can use to estimate the compute units a transaction will consume by running it in simulation mode.
import { getSetComputeUnitLimitInstruction } from '@solana-program/compute-budget';
import { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from '@solana/web3.js';
// 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.
const computeUnitsEstimate = await getComputeUnitEstimateForTransactionMessage(transactionMessage);
// Set the transaction message's compute unit budget.
const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(
getSetComputeUnitLimitInstruction({ units: computeUnitsEstimate }),
transactionMessage,
);
Warning: The compute unit estimate is just that – an estimate. The compute unit consumption of the actual transaction might be higher or lower than what was observed in simulation. Unless you are confident that your particular transaction message will consume the same or fewer compute units as was estimated, you might like to augment the estimate by either a fixed number of CUs or a multiplier.