Skip to content

Instantly share code, notes, and snippets.

@kallydev
Last active May 7, 2024 04:35
Show Gist options
  • Save kallydev/50fb06c282a4bd4a62e007961c551819 to your computer and use it in GitHub Desktop.
Save kallydev/50fb06c282a4bd4a62e007961c551819 to your computer and use it in GitHub Desktop.
Use Alloy to trace transactions of a block.
[package]
name = "example"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1.37.0", features = ["full"] }
anyhow = "1.0.82"
alloy = { git = "https://github.com/alloy-rs/alloy", features = ["provider-ws", "transport-ws", "rpc-types-trace", "eips"] }
futures = "0.3.30"
itertools = "0.12.1"
use alloy::eips::BlockNumberOrTag;
use alloy::primitives::B256;
use alloy::providers::{Provider, ProviderBuilder};
use alloy::rpc::types::trace::parity::LocalizedTransactionTrace;
use alloy::transports::ws::WsConnect;
use itertools::Itertools;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let provider = ProviderBuilder::new()
.on_ws(WsConnect::new("wss://mainnet.gateway.tenderly.co"))
.await?;
let mut block_subscription = provider.subscribe_blocks().await?;
loop {
let block = block_subscription.recv().await?;
let transaction_traces = provider
.trace_block(BlockNumberOrTag::Number(block.header.number.unwrap()))
.await?;
let transaction_traces: Vec<(B256, Vec<LocalizedTransactionTrace>)> = transaction_traces
.into_iter()
.group_by(|transaction_trace| transaction_trace.transaction_hash)
.into_iter()
.map(|(transaction_hash, transaction_traces)| (transaction_hash.unwrap(), transaction_traces.collect()))
.collect();
for (transaction_hash, transaction_traces) in transaction_traces {
println!("{:?} {:?}", transaction_hash, transaction_traces.len());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment