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,createSolanaRpc,createSolanaRpcSubscriptions,createTransactionMessage,generateKeyPairSigner,getComputeUnitEstimateForTransactionMessageFactory,getSignatureFromTransaction,lamports,pipe,prependTransactionMessageInstructions,sendAndConfirmTransactionFactory,setTransactionMessageFeePayerSigner,setTransactionMessageLifetimeUsingBlockhash,signTransactionMessageWithSigners} from "@solana/kit";import {getSetComputeUnitLimitInstruction,getSetComputeUnitPriceInstruction} from "@solana-program/compute-budget";import { getAddMemoInstruction } from "@solana-program/memo";// Create an RPCconst rpc = createSolanaRpc("http://127.0.0.1:8899");const rpcSubscriptions = createSolanaRpcSubscriptions("ws://127.0.0.1:8900");// Create utility functionsconst airdrop = airdropFactory({ rpc, rpcSubscriptions });const getComputeUnitEstimate =getComputeUnitEstimateForTransactionMessageFactory({ rpc });const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({rpc,rpcSubscriptions});// Create and fund an accountconst keypairSigner = await generateKeyPairSigner();await airdrop({commitment: "confirmed",lamports: lamports(1000_000n),recipientAddress: keypairSigner.address});// Create a memo transactionconst { value: latestBlockhash } = await rpc.getLatestBlockhash().send();const transactionMessage = pipe(createTransactionMessage({ version: "legacy" }),(m) => setTransactionMessageFeePayerSigner(keypairSigner, m),(m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),(m) =>appendTransactionMessageInstructions([getSetComputeUnitPriceInstruction({ microLamports: 5000n }),getAddMemoInstruction({ memo: "Hello, world!" })],m));// Estimate compute units for this transactionconst estimatedComputeUnits = await getComputeUnitEstimate(transactionMessage);console.log(`Transaction is estimated to consume ${estimatedComputeUnits} compute units`);// Add compute unit limit instruction to the transactionconst budgetedTransactionMessage = prependTransactionMessageInstructions([getSetComputeUnitLimitInstruction({ units: estimatedComputeUnits })],transactionMessage);// Sign and send the transactionconst signedTx = await signTransactionMessageWithSigners(budgetedTransactionMessage);const transactionSignature = getSignatureFromTransaction(signedTx);await sendAndConfirmTransaction(signedTx, { commitment: "confirmed" });console.log(`Transaction Signature: ${transactionSignature}`);
ConsolePowered by Mirror
Click to execute the code.
Is this page helpful?