Solana CookbookTransactions

How to Add Priority Fees to a Transaction

A priority fee is an optional fee paid to increase the chance that the current leader processes your transaction.

To add a priority fee to a transaction, invoke instructions from the Compute Budget Program.

import {
airdropFactory,
appendTransactionMessageInstructions,
createSolanaClient,
createTransaction,
generateKeyPairSigner,
getComputeUnitEstimateForTransactionMessageFactory,
getSignatureFromTransaction,
lamports,
pipe,
prependTransactionMessageInstructions,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
signTransactionMessageWithSigners
} from "gill";
import {
getAddMemoInstruction,
getSetComputeUnitLimitInstruction,
getSetComputeUnitPriceInstruction
} from "gill/programs";
// Create an RPC
const { rpc, rpcSubscriptions, sendAndConfirmTransaction } = createSolanaClient(
{
urlOrMoniker: "localnet"
}
);
// Create utility functions
const airdrop = airdropFactory({ rpc, rpcSubscriptions });
const getComputeUnitEstimate =
getComputeUnitEstimateForTransactionMessageFactory({ rpc });
// Create and fund an account
const keypairSigner = await generateKeyPairSigner();
await airdrop({
commitment: "confirmed",
lamports: lamports(1000_000n),
recipientAddress: keypairSigner.address
});
// Create a memo transaction
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const transactionMessage = createTransaction({
feePayer: keypairSigner,
version: "legacy",
instructions: [
getSetComputeUnitPriceInstruction({ microLamports: 5000n }),
getAddMemoInstruction({ memo: "Hello, world!" })
],
latestBlockhash
});
const estimatedComputeUnits = await getComputeUnitEstimate(transactionMessage);
console.log(
`Transaction is estimated to consume ${estimatedComputeUnits} compute units`
);
// Add compute unit limit instruction to the transaction
const budgetedTransactionMessage = prependTransactionMessageInstructions(
[getSetComputeUnitLimitInstruction({ units: estimatedComputeUnits })],
transactionMessage
);
// Sign and send the transaction
const signedTx = await signTransactionMessageWithSigners(
budgetedTransactionMessage
);
const transactionSignature = getSignatureFromTransaction(signedTx);
await sendAndConfirmTransaction(signedTx, { commitment: "confirmed" });
console.log(`Transaction Signature: ${transactionSignature}`);
Console
Click to execute the code.

Is this page helpful?