I want to establish an http connection to a Ganache test blockchain. Going through the GitHub page of the web3 crate I found this example:
#[tokio::main]
async fn main() -> web3::Result<()> {
let _ = env_logger::try_init();
let transport = web3::transports::Http::new("http://localhost:7545")?;
let web3 = web3::Web3::new(transport);
let mut accounts = web3.eth().accounts().await?;
...
Ok(())
}
However I want to implement the connection setup in a function. So I tried the following:
async fn establish_web3_connection_http(url: &str) -> web3::Result<Web3<Http>>{
let transport = web3::transports::Http::new(url)?;
Ok(web3::Web3::new(transport))
}
...
#[tokio::main]
async fn main() -> web3::Result<()> {
let web3_con = establish_web3_connection_http("http://localhost:7545");
println!("Calling accounts.");
let mut accounts = web3_con.eth().accounts().await?;
Ok(())
}
This results in the following error:
I am not sure why I do not return the correct value. There is not error when I don't call web3_con, so the function seems to be fine.
Is the return value somehow wrong, or how I call it?
CodePudding user response:
establish_web3_connection_http()
is an async function, so it returns a future. You're trying to call .eth()
on the future, when you probably want to call it on the value produced by the future. You need to await the result of this function:
let web3_con = establish_web3_connection_http("http://localhost:7545").await?;
// ^^^^^^^
However, you don't do any awaiting in establish_web3_connection_http()
, so there's no reason it needs to be async in the first place. You could just remove async
from its signature instead:
fn establish_web3_connection_http(url: &str) -> web3::Result<Web3<Http>>{