Part of the How to land transactions on Solana guide.TLDR:
- The
getRecentPrioritizationFeesmethod provides real-time insights into recent priority fee data on Solana. - It helps you dynamically gauge how much extra fee (in micro-lamports/Compute Unit) others are paying.
- You can then set your transaction priority fee accordingly, balancing costs with faster confirmation needs.
- This guide shows how to implement and analyze recent prioritization fees using TypeScript, with side-by-side examples for both
@solana/kitand the classic@solana/web3.js.
Main article
Within blockchain technology, transaction processing efficiency is a cornerstone of network performance and user satisfaction. At the heart of this efficiency lies the nuanced concept of prioritization fees—a critical element that ensures transactions are processed promptly. Recognizing the importance of this aspect, Solana has introduced thegetRecentPrioritizationFees method provides users with up-to-date information about these fees, allowing them to have an idea of the current fees attached to successful transactions and to estimate the priority fee to attach to transactions dynamically.
In this guide, we’ll explore the getRecentPrioritizationFees method, its operational mechanics, and its role in enhancing transaction efficiency. We will also discuss practical applications, demonstrating how to integrate this method into your decentralized applications (DApps) with TypeScript. Examples are shown for both Solana JavaScript libraries — @solana/kit (the newer, tree-shakable, functional SDK, formerly @solana/web3.js v2) and the classic @solana/web3.js (the Connection/PublicKey API) — both of which are actively maintained.
What are Priority Fees on Solana?
Priority fees on Solana allow users to expedite their transactions by paying an additional fee, measured in micro-lamports per Compute Unit. These optional fees are added to the base transaction fee, typically 5000 lamports per signature. The rationale behind priority fees is to make transactions more appealing to validator nodes for block inclusion, thereby ensuring quicker processing. This system effectively allows users to bid for transaction processing priority, which is especially useful during high network congestion. Validators are motivated to prioritize transactions offering higher fees per compute unit, ensuring efficient use of network resources. While transactions can proceed without priority fees, adding them increases the likelihood of faster execution.Deploy a Chainstack Solana node
Before getting started, deploy a Solana node on Chainstack so you are ready to play with the code and examples. This will provide direct blockchain access, which is essential for effectively exploring features like the getRecentPrioritizationFees method.Understand the `getRecentPrioritizationFees method
ThegetRecentPrioritizationFees method offers real-time insights into the network’s current trends of prioritization fees. These fees are calculated per compute unit and are paid by transactions seeking to secure a higher priority in the block processing queue. By leveraging these prioritization fees, transactions can gain precedence over others in the same block, thus ensuring quicker inclusion and execution on the blockchain.
Opting to pay a prioritization fee is voluntary, yet it significantly enhances a transaction’s chance of being included in the forthcoming block. This strategic payment allows transactions to outpace others, offering lower or no prioritization fees.
The method returns a response composed of objects, each representing a prioritization fee observed in a recent slot or block on the Solana blockchain.
Parameters
- Array: This parameter accepts a variety of base-58 encoded public key strings representing Solana account addresses, with a cap of 128 addresses.
Response
The method’s response is structured as an array of objects, with each object shedding light on a prioritization fee observed in a recent slot (block). The detailed attributes of each object include:- Slot: Identifies the specific slot (or block) on the Solana blockchain where the transactions tied to the observed prioritization fees were processed.
- prioritizationFee: Indicates the fee amount, in micro-lamports, that was paid by at least one transaction in the specified slot to secure a higher processing priority.
cURL example
Below is a practical demonstration of a simplegetRecentPrioritizationFees request using cURL.
This example queries the Orca Whirlpool SOL-USDC pool state account — a writable state account that competing swap transactions lock. Pass writable state accounts (pool state, reserves, user token accounts) for meaningful results.
You can find more explanations and examples in the Chainstack API reference.
Explore the project
This simple project is designed as a comprehensive guide for developers looking to optimize their transactions on the Solana blockchain through the strategic use of priority fees. By harnessing thegetRecentPrioritizationFees method, the provided code dynamically fetches recent prioritization fee data, offering a deep dive into the current fee landscape.
This project will provide various priority fee measurements based on the getRecentPrioritizationFees response:
- Average Prioritization Fee, including slots with zero fees.
- Average Prioritization Fee excluding slots with zero fees.
- Median Prioritization Fee excluding slots with zero fees.
Environment setup
- Node.js: Ensure you have Node.js (version 18 or above) installed on your machine. Node.js is essential for running the scripts and managing the dependencies of the Raydium SDK.
- npm: Node Package Manager is the default package manager for Node.js projects. It is used to install the necessary dependencies for this project. npm comes pre-installed with Node.js, so you don’t need to install it separately.
- Solana wallet: A Solana wallet with some SOL and SLP tokens.
If you prefer, you can also use Yarn as an alternative package manager. Yarn is a fast, reliable, and secure dependency management tool. After installing Node.js, you can install Yarn by running
npm install --global yarn in your terminal.Set up a TypeScript project
Before working on the code, we need to set up a TypeScript project. This will provide us with a structured environment for our code and allow us to take advantage of TypeScript’s type-checking and other features. Follow these steps to create a new TypeScript project: Create a new directory for your project: Open your terminal and navigate to the location where you want to create your project directory. Run the following command to create a new directory:package.json file, which is used to manage project dependencies.
Install TypeScript and type definitions: Next, we must install TypeScript and the Node.js type definitions. Both @solana/kit and @solana/web3.js ship their own TypeScript types, so no separate SDK types package is needed. Run the following command:
tsconfig.json file. Run the following command to generate a basic configuration file:
tsconfig.json file with default settings. You can customize these settings as needed for your project.
Create a source file: Let’s create our first TypeScript file where we’ll write our code.
Install required packages
We must install a package to interact with the Solana blockchain, plusdotenv to load environment variables. This guide shows two Solana JavaScript libraries side by side — both are actively maintained, so pick whichever fits your project:
@solana/kit— the newer, tree-shakable, functional SDK (formerly@solana/web3.jsv2). Its maintainers recommend it for new code.@solana/web3.js— the classic object-oriented API (Connection,PublicKey) used across most existing Solana codebases.
dotenv package (used by both) loads environment variables from a .env file, which helps store sensitive information like private keys.
- @solana/kit
- @solana/web3.js (classic)
Bash
package.json should then include:JSON
Set up your environment variables
This tutorial will use sensitive information such as private keys and RPC node URLs. It’s crucial to keep this information secure and avoid committing it to version control systems like Git. We’ll use thedotenv package to load environment variables from a .env file to achieve this.
Follow these steps to set up your environment variables:
- Create a
.envfile: In the root directory of your project, create a new file called.env. This file will store your environment variables. - Add your environment variables: Open the
.envfile and add the following variables, replacing the placeholders with your actual values:
SOLANA_RPC: This variable should contain your Solana node’s HTTP RPC URL. If you’re using a Chainstack node, the RPC URL is in the node’s credentials.
How to use environment variables
Once the.env file is set up, you can load environment variables in your TypeScript code (e.g., main.ts), import the dotenv package, and load the environment variables at the beginning of your script:
.env file into the process.env object, allowing you to access them using process.env.VARIABLE_NAME.
Access environment variables: You can now access the environment variables in your code like this:
Remember to add the
.env file to your .gitignore file to prevent it from being committed to version control systems, as it contains sensitive information.Code walkthrough
Now that we have set up the project, installed the required packages, and configured the environment variables, it’s time to put everything together and implement the code:Add the code
- Open the
main.tsfile you created earlier in your preferred code editor. - Paste the following code into the
main.tsfile:
- @solana/kit
- @solana/web3.js (classic)
TypeScript
Import dependencies and setup
- Solana SDK: The
@solana/kitversion importscreateSolanaRpcandaddress; the@solana/web3.jsversion importsConnectionandPublicKey. Both interact with the Solana blockchain and handle public key addresses. - Dotenv: Imports configuration for environment variables, allowing the script to securely access the Solana RPC endpoint specified in your environment.
Utility function
getEnvVariable: A utility function that retrieves environment variables securely. It throws an error if the specified environment variable is not found, ensuring the script has all the necessary configurations.
Main async getPrioritizationFees function
-
Initialize the connection:
@solana/kitcreates an RPC client withcreateSolanaRpc;@solana/web3.jscreates anew Connection. Both use the RPC endpoint from your environment variables. -
Define the writable account: Specifies the writable account(s) for which the prioritization fees will be fetched —
address(...)in@solana/kit,new PublicKey(...)in@solana/web3.js. -
Fetch prioritization fees: Retrieves an array of fee objects with recent fee data. In
@solana/kityou callgetRecentPrioritizationFees([writableAccount]).send()(RPC methods return a request object dispatched with.send()) and theslot/prioritizationFeefields come back asbigint, so coerce them withNumber()before arithmetic. In@solana/web3.jsyou callconnection.getRecentPrioritizationFees({ lockedWritableAccounts: [...] })and the fields are alreadynumber. - Handle no data case: Checks if no prioritization fee data was returned and logs a message indicating the absence of data.
-
Data analysis:
- Sorts and analyzes the slots of the returned fee objects to determine the range of slots examined.
- Calculates the average prioritization fee, including and excluding zeros, to provide insights into the overall fee trends.
- Determines the median prioritization fee from the non-zero fees to give a middle-point fee estimate less influenced by outliers.
Calculations and output
- Sort and calculate averages/median: Performs numerical analysis on the fetched fee data to calculate average and median fees, offering a comprehensive view of fee trends. These metrics are essential for developers looking to optimize transaction costs based on current network conditions.
- Logging results: This function outputs the analysis results, including the range of slots examined and the calculated average and median fees, providing actionable insights for setting transaction priority fees.
Error handling
- Catch block: This block captures and logs any errors encountered during the execution of the async function, ensuring that issues are reported for debugging.
Run the script
Now that we have the code and understand how it works, it’s time to run it. You can edit the writable account(s) you pass to the method:- @solana/kit
- @solana/web3.js (classic)
TypeScript
averageFeeIncludingZeros, averageFeeExcludingZeros, and medianFee in your transactions script to add fees dynamically.
Learn how to add Priority Fees to your transactions by reading Solana: How to use Priority Fees to unlock faster transactions.
Conclusion
This guide gets into thegetRecentPrioritizationFees method on Solana, offering a comprehensive overview and practical examples of leveraging priority fees to enhance transaction processing efficiency. We’ve explored the concept of priority fees, set up a Solana node on Chainstack, and provided a detailed walkthrough of fetching and analyzing prioritization fee data using TypeScript.
Through this process, we’ve gained insights into the importance of dynamically estimating fees to balance cost efficiency with transaction speed. This knowledge empowers developers to optimize their DApps on the Solana blockchain, ensuring transactions are processed timely without incurring unnecessary costs.
