Skip to content

Instantly share code, notes, and snippets.

@soos3d
Created January 25, 2024 18:36
Show Gist options
  • Save soos3d/a1fc6a95121b2fbfcb0f5cdc37284507 to your computer and use it in GitHub Desktop.
Save soos3d/a1fc6a95121b2fbfcb0f5cdc37284507 to your computer and use it in GitHub Desktop.
Send an RPC request to an Ethereum RPC node with Rust 🦀
[package]
name = "blockchain_collector"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
reqwest = { version = "0.11.23", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.35.1", features = ["full"] }
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::time::Instant;
// Define the Ethereum JSON-RPC URL as a constant
const ETHEREUM_RPC_URL: &str = "YOUR_CHAINSTACK_NODE_URL";
#[derive(Serialize, Deserialize)]
struct JsonRpcRequest {
id: i32,
jsonrpc: String,
method: String,
params: Vec<serde_json::Value>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let client = reqwest::Client::new();
let request_body = JsonRpcRequest {
id: 1,
jsonrpc: "2.0".to_string(),
method: "eth_blockNumber".to_string(),
params: vec![],
};
let start_time = Instant::now();
let response = client
.post(ETHEREUM_RPC_URLc)
.json(&request_body)
.header("accept", "application/json")
.header("content-type", "application/json")
.send()
.await?;
let duration = start_time.elapsed();
if response.status() == StatusCode::OK {
let response_body = response.text().await?;
println!("Response: {}", response_body);
println!("Request took: {:?}", duration);
} else {
eprintln!("Request failed: {}", response.status());
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment