Efficient Real‑Time Solana Block Retrieval in Rust

Efficient Real‑Time Solana Block Retrieval in Rust

Efficient Real‑Time Solana Block Retrieval in Rust
Sniper bots require efficient real-time on-chain transaction data

The Solana network churns out a new block in under half a second.
The fastest way to keep up is to subscribe to that stream with the blockSubscribe WebSocket method.
Running your own Solana RPC node is pricey because the hardware requirements are high, so most teams use a commercial provider such as Quicknode, Alchemy, or similar to get reliable, low‑latency access to the subscription API.

Rust Environment Configuration

Rust Installation

Rust is celebrated for its blend of memory safety and high performance. If you want to see the concrete speed gains, take a look at this deep dive.
Getting a Rust development environment up and running is straightforward:

Create Rust Environment

Initialize the Rust configuration

cargo init solana-subscription-example
cd solana-subscription-example

Install Rust Dependencies

The Cargo.toml – Rust’s Dependency Manifest

Cargo.toml is the central configuration file for Cargo, Rust’s build and package manager. Inside this file you list every crate your project needs. Cargo will fetch, compile, and link them for you. When you want to add or update a dependency, simply edit the relevant section of Cargo.toml.

[dependencies]
solana-client = "1.18.12"
solana-sdk = "1.18.12"
solana-transaction-status = "1.18.12"
tokio = "1.37.0"

Solana Block Subscription Method

The source file for Rust projects will default in the main.rs located at ./src/main.rs.

Import Dependencies

At the top of the file, we’ll include imports of the dependencies that we previously added in the Cargo.toml.

use solana_client::{
    pubsub_client::PubsubClient,
    rpc_config::{RpcBlockSubscribeConfig, RpcBlockSubscribeFilter},
};
use solana_transaction_status::{TransactionDetails, UiTransactionEncoding};
use solana_sdk::{commitment_config::CommitmentConfig};

RPC Endpoint

Depending on the RPC endpoint, the URL will be added as a const &str to be referenced. Quicknode allows for cheap and easy solutions to get your project started.

const SOLANA_RPC_URL_WS: &'static str = "wss://<RPC Endpoint>";

Default Main Function

The main() function will be called when we compile and run the Rust project. A main function with a generalized subscription loop with the Tokio decorator as follows:

#[tokio::main]
async fn main() {
    println!("Solana Subscription Example!");

    // obtain full transactions for confirmed blocks
    let config = RpcBlockSubscribeConfig {
        commitment: Some(CommitmentConfig::confirmed()),
        encoding: Some(UiTransactionEncoding::Base64),
        transaction_details: Some(TransactionDetails::Full),
        show_rewards: Some(false),
        max_supported_transaction_version: Some(0),
        ..Default::default()
    };
    // create the subscription with the defined configuration
    let (_tx_confirmed_block, rx_confirmed_block) = PubsubClient::block_subscribe(&SOLANA_RPC_URL_WS, RpcBlockSubscribeFilter::All, Some(config)).unwrap();
    // loop through the subscription responses and print the block slot
    loop {
        match rx_confirmed_block.recv() {
            Ok(response) => {
                println!("{}", response.value.slot.to_string());
            }
            Err(e) => {
                println!("Block Subscription Error: {:?}", e);
                break;
            }
        }
    }
}

The subscription is configured through the RpcBlockSubscribeConfig struct.
It sets a Confirmed commitment level, so each block you receive contains the full transaction payload. While you can tweak the options to suit your needs, the sample below includes everything you’ll need to start a Solana trading or arbitrage bot.

The main loop simply waits for a new confirmed block, uses Rust’s pattern matching to verify the response, and in the demo just prints the block’s slot number. Replace that line with whatever processing you require such as price checks, order execution, or any other logic.

The project may be built and run as follows:

cargo run --release

Resulting in the println macro printing to the terminal:

cargo run --release
   Compiling solana-subscription-example v0.1.0
    Finished `release` profile [optimized] target(s) in 0.63s
     Running `target/release/solana-subscription-example`
Solana Subscription Example!
263591942
263591943
263591944
263591945
263591946
263591947

The blocks are received and processed as soon as the RPC returns the block data via the subscription method!

Conclusion

Implementing a block‑subscription in Rust is painless and highly adaptable—whether you’re building a high‑frequency trading bot, an arbitrage engine, or any other Solana‑centric tool. By listening to confirmed blocks that carry every transaction detail, you can monitor the chain in real time and act faster than competitors. This pattern showcases how raw blockchain feeds can be turned into practical trading logic and gives developers a robust, customizable foundation to build upon.

Subscribe to Wumpus World

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe