Quiz — Balance Checker
Question
Write a function that returns true if a given address has zero ETH balance. Practical quiz combining Provider + get_balance + .await? + Option/Result in one function. Verify against Vitalik's address.
Principle (minimum model)
- Function signature.
async fn is_empty_wallet(provider: &impl Provider, address: Address) -> eyre::Result<bool>. &impl Provider. Accepts any Provider implementation → trait-bound polymorphism. Works with HTTP / WebSocket / Anvil-fork alike.get_balance(address).await?. Wait for the Future + propagate errors; extract theU256balance..is_zero(). Idiomatic zero-check onU256.balance == 0u64is a type mismatch and won't compile.- Wei units.
get_balancereturns wei asU256. ETH = 10¹⁸ wei.format_etherfor display. Never usef64for money — precision loss.
Worked example + steps
Quiz: balance checker
Goal: write a function that returns true when a given address has zero ETH balance, false otherwise.
What you'll need
Two pieces from Alloy you've already met:
Provider— created viaProviderBuilder::new().connect_http(url)(Provider lesson)get_balance(address)— async method that returns the balance
Plus one bit from the previous Rust lesson: the ? operator for error propagation on async calls (x.await?).
Try it yourself
Create a new project locally (Rust Playground has no Alloy):
cargo new balance-check && cd balance-check
In Cargo.toml:
[dependencies]
alloy = { version = "1.0", features = ["full"] }
tokio = { version = "1", features = ["full"] }
eyre = "0.6"
In src/main.rs, write a function with this signature:
async fn is_empty_wallet(
provider: &impl Provider,
address: Address,
) -> eyre::Result<bool> {
// your code
}
And exercise it from main:
#[tokio::main]
async fn main() -> eyre::Result<()> {
let provider = ProviderBuilder::new()
.connect_http("https://ethereum.reth.rs/rpc".parse()?);
let vitalik = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045".parse::<Address>()?;
println!("vitalik empty? {}", is_empty_wallet(&provider, vitalik).await?);
Ok(())
}
Hints if you get stuck:
provider.get_balance(address)returns a Future — use.await?to extract the balance- The balance type is
U256. There's an idiomatic method on it for the "is this zero?" check — find it in the Alloy docs - You return
Ok(...)from a function that returnsResult<...>
cargo run will hit the public Reth RPC and tell you whether Vitalik's wallet is empty (it isn't).
Quiz
Summary (3 lines)
async fn is_empty_wallet(&impl Provider, Address) -> eyre::Result<bool>+get_balance(addr).await?.is_zero()— one line.impl Provider= trait-bound polymorphism.is_zero()is the idiomatic zero-check. Wei inU256, notf64.- Next module: Inside the EVM, starting with the stack-machine basics.