Skip to content

Common Actions

Networked snippets read RPC_URL (or WS_URL for WebSocket examples) from the environment. This keeps credentials out of source control and lets you choose the node provider. Snippets that start Anvil from Rust, such as the mainnet fork in write_contract.rs, need the node-bindings feature in addition to the defaults:

cargo add alloy --features node-bindings
//! Demonstrates reading a contract by fetching the WETH balance of an address.
use alloy::{primitives::address, providers::ProviderBuilder, sol}; 
use std::error::Error;
 
// Generate the contract bindings for the ERC20 interface.
sol! { 
   // The `rpc` attribute enables contract interaction via the provider.
   #[sol(rpc)] 
   contract ERC20 { 
        function balanceOf(address owner) public view returns (uint256); 
   } 
} 
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Initialize the provider.
    let rpc_url = std::env::var("RPC_URL")?; 
    let provider = ProviderBuilder::new().connect(&rpc_url).await?; 
 
    // Instantiate the contract instance.
    let weth = address!("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
    let erc20 = ERC20::new(weth, provider);
 
    // Fetch the balance of WETH for a given address.
    let owner = address!("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
    let balance = erc20.balanceOf(owner).call().await?;
 
    println!("WETH Balance of {owner}: {balance}");
 
    Ok(())
}

Used By the Best

Optimism KonaFlashbots rBuilderSorella Labs AngstromArbitrum StylusSuccinct Labs Sp1RethFoundryRevm

Features

Alloy supports the following out of the box for a best-in-class developer experience:

Community

Join the Community

Supporters

ParadigmIthaca