Search code examples
rustethereumrust-web3

How do I pass in a number to web3.eth().block()?


I'm using the rust-web3 crate to connect to an ethereum node and get information about a block by it's block number (or block height). Based on this example here is how I was able to implement it:

use web3;
use web3::types::{BlockId, BlockNumber, U64};

#[tokio::main]
async fn main() -> web3::Result<()> {
    let transport = web3::transports::Http::new(WEB3_URL)?;
    let web3 = web3::Web3::new(transport);

    web3.eth().block(BlockId::Number(BlockNumber::Number(U64([42]))));
    Ok(())
}

Is there an easier way to pass in that 42 to web3.eth().block()?

Right now I'm using two enums and the U64 struct to make a variable that the compiler accepts. I'm new to rust and I think I'm missing an important concept of the language that would simplify it.


Solution

  • There's an impl From<U64> for BlockId (source), so you can shorten the call a little:

    web3.eth().block(U64([42]).into());