I am just learning Rust and I am particularly interested in the web3 crate. I followed this tutorial to build a Ethereum explorer app and wanted to refactor the code to make it more modular. Therefore, I wanted to create functions that only serve a particular use-case - e.g. get_block() or get_transaction(). Most functions however require some call to the JSON-RPC endpoint of the Ethereum client, which I did not want to define again and again in each function. Therefore I created the websocket-connection in the main routine and share it with all functions.
Even though it is working like intended - it appears to be much slower than putting everything into one main function as it is done in the original tutorial. I am wondering if my approach even makes sense or how a more experienced Rust developer would go about this.
This is my main.rs:
let websocket = web3::transports::WebSocket::new(host).await.unwrap();
let web3s = web3::Web3::new(websocket);
let block_no = BlockNumber::Latest;
let block = get_block(&web3s, block_no).await;
for transaction_hash in block.transactions {
let tx = get_transaction(&web3s, transaction_hash).await;
let mut token_name: String = "".to_string();
if is_smart_contract(&web3s, tx.to.unwrap()).await {
token_name = get_token_name(&web3s, tx.to.unwrap()).await;
}
let func_signature = get_func_signature(tx.input);
let from_addr = tx.from.unwrap_or(H160::zero());
let to_addr = tx.to.unwrap_or(H160::zero());
let eth_value = wei_to_eth(tx.value);
println!(
"[{}] ({} -> {}) from {}, to {}, value {}, gas {}, gas price {}",
tx.transaction_index.unwrap_or(U64::from(0)),
token_name,
&func_signature,
w3h::to_string(&from_addr),
w3h::to_string(&to_addr),
eth_value,
tx.gas,
tx.gas_price,
);
}