### Environment Variable Setup Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Shell commands for setting environment variables before running examples. ```bash export RPC_URL=https://eth.public-rpc.com cargo run --example my_example ``` ```bash export WS_URL=wss://eth-mainnet.ws.alchemyapi.io/v2/YOUR-API-KEY cargo run --example subscriptions ``` ```bash export RPC_URLS=https://first.com,https://second.com cargo run --example fallback_layer ``` -------------------------------- ### Run Examples Source: https://github.com/alloy-rs/examples/blob/main/CONTRIBUTING.md Commands to execute individual or all runnable examples within the project. ```sh cargo run --example $YOUR_EXAMPLE_NAME ``` ```sh ./scripts/test.sh ``` -------------------------------- ### Configure Environment Variables for Examples Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Set required environment variables before running specific example types. ```bash export RPC_URL=https://eth.public-rpc.com cargo run --example my_example ``` ```bash export WS_URL=wss://eth-mainnet.ws.alchemyapi.io/v2/YOUR-KEY cargo run --example subscribe_blocks ``` ```bash export IPC_PATH=/tmp/reth/reth.ipc cargo run --example reth_local_instance ``` ```bash export RPC_URLS=https://first.com,https://second.com cargo run --example fallback_layer ``` ```bash export AWS_REGION=us-east-1 export AWS_ACCESS_KEY_ID=your_key export AWS_SECRET_ACCESS_KEY=your_secret export AWS_KMS_KEY_ID=arn:aws:kms:... cargo run --example aws_signer ``` -------------------------------- ### Run an example with an RPC endpoint Source: https://github.com/alloy-rs/examples/blob/main/README.md Provide a network endpoint via the RPC_URL environment variable for examples that query or fork a network. ```sh RPC_URL=https://your-ethereum-endpoint cargo run --example http ``` -------------------------------- ### Run an example with multiple RPC endpoints Source: https://github.com/alloy-rs/examples/blob/main/README.md Supply a comma-separated list of endpoints for examples utilizing the fallback layer. ```sh RPC_URLS=https://first-endpoint,https://second-endpoint cargo run --example fallback_layer ``` -------------------------------- ### Run a basic Alloy example Source: https://github.com/alloy-rs/examples/blob/main/README.md Execute a specific example using the cargo run command. ```sh cargo run --example mnemonic_signer ``` -------------------------------- ### Execute Alloy Examples Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/overview.md Commands to run examples using different transport configurations and environment variables. ```bash # Basic example cargo run --example # Examples requiring RPC endpoint RPC_URL=https://your-endpoint cargo run --example http # WebSocket endpoint WS_URL=wss://your-endpoint cargo run --example websocket # IPC socket IPC_PATH=/path/to/socket cargo run --example ipc # Multiple endpoints (fallback example) RPC_URLS=https://first,https://second cargo run --example fallback_layer ``` -------------------------------- ### Generate Example Index Source: https://github.com/alloy-rs/examples/blob/main/CONTRIBUTING.md Updates the example index after adding or renaming examples. ```python python3 scripts/generate-example-index.py ``` -------------------------------- ### Run Alloy-rs Examples with Environment Variables Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/README.md Commands to execute examples using specific RPC endpoints, fallback configurations, or hardware/cloud signers. ```bash # HTTP endpoint (most common) RPC_URL=https://eth.public-rpc.com cargo run --example my_example # WebSocket endpoint WS_URL=wss://eth-mainnet.ws.alchemyapi.io/v2/KEY cargo run --example subscriptions # Multiple endpoints (fallback) RPC_URLS=https://first.com,https://second.com cargo run --example fallback_layer # Local testing cargo run --example provider_builder # With AWS KMS AWS_REGION=us-east-1 AWS_KMS_KEY_ID=arn:aws:kms:... cargo run --example aws_signer ``` -------------------------------- ### Configure multiple endpoints for fallback examples Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Provide at least two endpoints when running examples that demonstrate failover behavior. ```bash RPC_URLS=https://first-endpoint.com,https://second-endpoint.com cargo run --example fallback_layer ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Run examples with debug-level logging enabled. ```bash RUST_LOG=debug cargo run --example my_example ``` -------------------------------- ### Fork Mainnet with Anvil Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Start a local Anvil node forking mainnet to test examples against live state. ```bash anvil --fork-url https://eth.public-rpc.com # In another terminal: cargo run --example my_example ``` -------------------------------- ### Usage Example for ToAlloy Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/helpers.md Demonstrates converting an Ethers-rs U256 value to an Alloy U256 value. ```rust use helpers::ethers::ToAlloy; use ethers::types::U256; let ethers_num = U256::from(100); let alloy_num = ethers_num.to_alloy(); ``` -------------------------------- ### Basic HTTP Provider Setup Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Connects to the Ethereum mainnet via a public RPC URL to fetch the latest block number. ```bash RPC_URL=https://eth.public-rpc.com cargo run --example http ``` ```rust use example_support::rpc_url; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_http(rpc_url()?.parse()?); let block_number = provider.get_block_number().await?; println!("Current block: {}", block_number); Ok(()) } ``` -------------------------------- ### Enable Full Backtrace for Debugging Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Run examples with full Rust backtrace to see detailed error information. ```bash RUST_BACKTRACE=full cargo run --example my_example ``` -------------------------------- ### DEX Calculations Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Example of calculating output amounts for a Uniswap-style pair. ```rust use helpers::alloy::{get_uniswap_pair, get_amount_out}; use alloy::primitives::U256; let pair = get_uniswap_pair(); let amount_out = get_amount_out( pair.reserve0, pair.reserve1, U256::from(1_000_000_000_000_000_000), ); ``` -------------------------------- ### Use UniV2Pair Helpers Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Example of retrieving a pair and calculating output amounts using helper functions. ```rust use helpers::alloy::get_uniswap_pair; let pair = get_uniswap_pair(); let amount_out = helpers::alloy::get_amount_out( pair.reserve0, pair.reserve1, U256::from(1_000_000_000_000_000_000), ); ``` -------------------------------- ### Use Recommended Fillers for Automatic Configuration Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Simplify provider setup by using ProviderBuilder to automatically handle gas, nonce, and chain ID configuration. ```rust use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() // Automatically includes: // - ChainIdFiller: Sets chain_id // - GasFiller: Estimates gas and prices // - NonceFiller: Manages nonce sequencing .connect_anvil_with_wallet(); // No need to manually set gas_limit, max_fee_per_gas, nonce, chain_id Ok(()) } ``` -------------------------------- ### Usage Example for ToEthers Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/helpers.md Demonstrates converting an Alloy U256 value to an Ethers-rs U256 value. ```rust use helpers::alloy::ToEthers; use alloy::primitives::U256; let alloy_num = U256::from(100); let ethers_num = alloy_num.to_ethers(); ``` -------------------------------- ### Define RPC Authorization Header Values Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Example formats for Bearer or Basic authentication tokens. ```text Bearer YOUR_API_KEY Basic base64_encoded_credentials ``` -------------------------------- ### Handle WebSocket Connection Errors Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Shows how to handle potential failures during WebSocket initialization and subscription setup. ```rust use alloy::providers::{Provider, ProviderBuilder, WsConnect}; use eyre::Result; #[tokio::main] async fn main() -> Result<()> { let ws = WsConnect::new("wss://invalid-endpoint.com"); let provider = ProviderBuilder::new() .connect_ws(ws) .await?; // May fail here let subscription = provider.subscribe_blocks().await?; // May fail here Ok(()) } ``` -------------------------------- ### Configure Google Cloud KMS Signer Environment Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Set required GCP environment variables before executing the signer example. ```bash export GCP_PROJECT_ID=my-gcp-project export GCP_KEY_RING=my-keyring export GCP_KEY_NAME=my-key export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json cargo run --example gcp_signer ``` -------------------------------- ### Configure AWS KMS Signer Environment Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Set required AWS environment variables before executing the signer example. ```bash export AWS_REGION=us-east-1 export AWS_ACCESS_KEY_ID=your_access_key export AWS_SECRET_ACCESS_KEY=your_secret_key export AWS_KMS_KEY_ID=arn:aws:kms:us-east-1:123456789:key/12345678-1234-1234-1234-123456789012 cargo run --example aws_signer ``` -------------------------------- ### Handle Missing Transaction Fields Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Shows an example of a transaction request missing required fields like the 'to' address. ```rust use alloy::rpc::types::TransactionRequest; let tx = TransactionRequest::default() // Missing .with_to() — only valid for contract creation .with_data(contract_code.clone()); ``` -------------------------------- ### Setting Up a Provider Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Methods for initializing a provider using HTTP, WebSocket, or local Anvil instances. ```rust use alloy::providers::ProviderBuilder; use example_support::rpc_url; let provider = ProviderBuilder::new() .connect_http(rpc_url()?.parse()?); ``` ```rust use alloy::providers::{Provider, ProviderBuilder, WsConnect}; use example_support::ws_url; let ws = WsConnect::new(ws_url()?.parse()?); let provider = ProviderBuilder::new() .connect_ws(ws) .await?; ``` ```rust let provider = ProviderBuilder::new() .connect_anvil_with_wallet(); ``` -------------------------------- ### Setting Up an Alloy Provider Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/README.md Configures a provider using HTTP, WebSocket, or a local Anvil instance with a wallet. ```rust // HTTP let provider = ProviderBuilder::new() .connect_http(rpc_url()?.parse()?); // WebSocket let provider = ProviderBuilder::new() .connect_ws(ws_url()?.parse()?).await?; // Local Anvil let provider = ProviderBuilder::new() .connect_anvil_with_wallet(); ``` -------------------------------- ### Initialize a Mainnet Provider Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Uses the ProviderBuilder to automatically configure settings for the Ethereum Mainnet. ```rust use alloy::providers::ProviderBuilder; use alloy_chains::Chain; // Automatically selects appropriate RPC and settings let provider = ProviderBuilder::new() .chain(Chain::Mainnet) // Ethereum Mainnet .connect_builtin()?; ``` -------------------------------- ### Configure Hardware Wallet Signers Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Initializes signers for Ledger or Trezor hardware wallets. ```rust use alloy::signers::ledger::LedgerSigner; let signer = LedgerSigner::new(LedgerHDPath::default()).await?; ``` ```rust use alloy::signers::trezor::TrezorSigner; let signer = TrezorSigner::new(TrezorHDPath::default()).await?; ``` -------------------------------- ### Handle PrivateKeySigner Configuration Errors Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Demonstrates how to handle invalid private key formats when initializing a PrivateKeySigner. ```rust use alloy::signers::local::PrivateKeySigner; // Invalid: wrong length let signer = PrivateKeySigner::from_str("0x1234") .expect_err("Key too short"); // Invalid: invalid hex let signer = PrivateKeySigner::from_str("0xZZZZ...") .expect_err("Invalid hex"); ``` -------------------------------- ### Implement Google Cloud KMS Signer in Rust Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Initialize a GcpSigner with project, keyring, and key name parameters. ```rust use alloy::signers::gcp::GcpSigner; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let signer = GcpSigner::new( "my-project", "my-keyring", "my-key", ).await?; let provider = ProviderBuilder::new() .wallet(signer) .connect_http("https://eth.public-rpc.com".parse()?); Ok(()) } ``` -------------------------------- ### Configure HTTP Connection Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Establishes a standard HTTP connection to an Ethereum node. ```rust use alloy::providers::ProviderBuilder; let provider = ProviderBuilder::new() .connect_http("https://eth.public-rpc.com".parse()?); ``` -------------------------------- ### Initialize Parity Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Shows how to instantiate a Parity recovery ID for ECDSA signatures. ```rust use alloy::primitives::Parity; let parity = Parity::Odd; // or Parity::Even ``` -------------------------------- ### Configure Multi-Provider Fallback Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Sets up a layered HTTP provider using multiple RPC URLs for redundancy. ```rust use example_support::rpc_urls; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let urls: Vec<_> = rpc_urls()? .iter() .map(|url| url.parse()) .collect::>()?; let provider = ProviderBuilder::new() .connect_layered_http(urls); Ok(()) } ``` -------------------------------- ### Configure Single HTTP Provider Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Initializes a provider using a single HTTP RPC URL. ```rust use example_support::rpc_url; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_http(rpc_url()?.parse()?); let balance = provider.get_balance(account).await?; Ok(()) } ``` -------------------------------- ### Run Cargo Development Commands Source: https://github.com/alloy-rs/examples/blob/main/CONTRIBUTING.md Standard commands for checking, building, and linting the workspace using Cargo. ```sh cargo check --workspace --examples --all-features --locked cargo build --workspace --examples --all-features --locked cargo +nightly fmt --all --check cargo +nightly clippy \ --workspace \ --examples \ --all-features \ --locked \ -- -D warnings ``` -------------------------------- ### View Documentation File Structure Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/README.md Displays the directory layout of the generated documentation files. ```text output/ ├── README.md (this file) ├── index.md (master index and navigation) ├── quick-start.md (working code examples) ├── overview.md (project structure) ├── example-support.md (configuration helpers) ├── helpers.md (utility functions) ├── types.md (type definitions) ├── errors.md (error reference) └── configuration.md (all configuration options) ``` -------------------------------- ### Manage Mnemonic Wallets in Rust Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Demonstrates creating wallets from a BIP-39 mnemonic phrase and generating random wallets. ```bash cargo run --example mnemonic_signer ``` ```rust use alloy::signers::local::{coins_bip39::English, MnemonicBuilder}; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { // Standard BIP-39 mnemonic let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; let wallet = MnemonicBuilder::::default() .phrase(phrase) .index(0)? .build()?; println!("Wallet address: {}", wallet.address()); // Generate random wallet let random_wallet = MnemonicBuilder::::default() .word_count(24) .build_random()?; println!("Random wallet: {}", random_wallet.address()); Ok(()) } ``` -------------------------------- ### Run Benchmarks via Cargo Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Commands for executing performance benchmarks using the cargo bench tool. ```bash # Run all benchmarks cargo bench # Run specific benchmark cargo bench --bench abi_encoding # With specific settings cargo bench -- --sample-size=100 --warm-up-time=5 ``` -------------------------------- ### Configure Mnemonic Signer Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Initializes a provider using a BIP39 mnemonic phrase. ```rust use alloy::signers::local::{coins_bip39::English, MnemonicBuilder}; use alloy::providers::ProviderBuilder; let mnemonic = MnemonicBuilder::::default() .phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") .index(0)? .build()?; let provider = ProviderBuilder::new() .wallet(mnemonic) .connect_http("https://eth.public-rpc.com".parse()?); ``` -------------------------------- ### Establish WebSocket Subscription Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Connects to a WebSocket endpoint and initializes a block subscription. ```rust use example_support::ws_url; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_ws(ws_url()?.parse()?) .await?; let mut blocks = provider.subscribe_blocks().await?; Ok(()) } ``` -------------------------------- ### Configure Provider via Explicit Method Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Directly configures a signer and HTTP connection on an existing provider instance. ```rust provider.wallet(signer).connect_http(url.parse()?); ``` -------------------------------- ### Configure WebSocket Connection Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Establishes a WebSocket connection, supporting subscriptions and automatic reconnection. ```rust use alloy::providers::{Provider, ProviderBuilder, WsConnect}; let ws = WsConnect::new("wss://eth-mainnet.ws.alchemyapi.io/v2/YOUR-API-KEY".parse()?); let provider = ProviderBuilder::new() .connect_ws(ws) .await?; ``` -------------------------------- ### Configure Private Key Signer in Rust Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Initializes a provider with a private key for transaction signing. Use only for testing purposes. ```rust use alloy::signers::local::PrivateKeySigner; use alloy::providers::ProviderBuilder; use std::str::FromStr; #[tokio::main] async fn main() -> eyre::Result<()> { // NEVER use this in production let private_key = "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; let signer = PrivateKeySigner::from_str(private_key)?; let provider = ProviderBuilder::new() .wallet(signer) .connect_http("https://eth.public-rpc.com".parse()?); // Now provider is configured to automatically sign transactions let balance = provider.get_balance(provider.default_signer_address()).await?; println!("Balance: {}", balance); Ok(()) } ``` -------------------------------- ### Spawn Geth Node Programmatically Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Spawns a local Geth instance and connects a provider to its endpoint. ```rust use alloy::node_bindings::Geth; use alloy::providers::ProviderBuilder; let geth = Geth::new().try_spawn()?; let provider = ProviderBuilder::new() .connect_http(geth.endpoint_url().parse()?); ``` -------------------------------- ### Configure Provider via Environment Variables Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Sets the RPC URL via environment variable before executing the application. ```bash RPC_URL=https://... cargo run --example my_example ``` -------------------------------- ### Configure Fallback Provider with RPC_URLS Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Set up a multi-provider failover layer using a comma-separated list of URLs from the RPC_URLS environment variable. ```text https://eth.public-rpc.com,https://eth-mainnet.g.alchemy.com/v2/demo https://rpc1.example.com, https://rpc2.example.com, https://rpc3.example.com ``` ```rust use example_support::rpc_urls; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let urls: Vec<_> = rpc_urls()? .iter() .map(|url| url.parse()) .collect::>()?; let provider = ProviderBuilder::new() .connect_layered_http(urls); Ok(()) } ``` -------------------------------- ### Spawn Anvil Node Programmatically Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Demonstrates spawning an Anvil instance and connecting a provider to it. ```rust use alloy::node_bindings::Anvil; use alloy::providers::ProviderBuilder; // Spawn Anvil programmatically let anvil = Anvil::new().block_time(1).try_spawn()?; let provider = ProviderBuilder::new() .connect_http(anvil.endpoint_url().parse()?); ``` -------------------------------- ### Configure Provider via Builder Options Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Uses the ProviderBuilder chain method to set the network context. ```rust ProviderBuilder::new().chain(Chain::Mainnet)... ``` -------------------------------- ### Handle Subscription Errors in Rust Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Demonstrates how subscription attempts fail when using an HTTP provider that does not support WebSocket subscriptions. ```rust use alloy::providers::Provider; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_http("https://eth.public-rpc.com".parse()?); // HTTP can't subscribe // This will fail let subscription = provider.subscribe_blocks().await .expect_err("HTTP doesn't support subscriptions"); Ok(()) } ``` -------------------------------- ### Configure Authenticated HTTP Client Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Inject an authorization header into an HTTP client using environment variables. ```rust use example_support::required_env; use alloy::transports::http::reqwest::{Client, HeaderMap, AUTHORIZATION}; #[tokio::main] async fn main() -> eyre::Result<()> { let mut headers = HeaderMap::new(); headers.insert( AUTHORIZATION, required_env("RPC_AUTHORIZATION")?.parse()? ); let client = Client::builder() .default_headers(headers) .build()?; Ok(()) } ``` -------------------------------- ### Configure WebSocket Provider with WS_URL Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Establish a WebSocket connection for subscriptions using the WS_URL environment variable. ```text wss://eth-mainnet.ws.alchemyapi.io/v2/YOUR-API-KEY wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID ws://localhost:8546 ``` ```rust use example_support::ws_url; use alloy::providers::{Provider, ProviderBuilder, WsConnect}; #[tokio::main] async fn main() -> eyre::Result<()> { let ws_url = ws_url()?; let ws = WsConnect::new(ws_url.parse()?); let provider = ProviderBuilder::new() .connect_ws(ws) .await?; let subscription = provider.subscribe_blocks().await?; Ok(()) } ``` -------------------------------- ### Working with Big Numbers (U256) Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Demonstrates creating U256 instances from primitives and strings, and performing arithmetic operations. ```bash cargo run --example create_instances ``` ```rust use alloy::primitives::U256; use std::str::FromStr; fn main() -> eyre::Result<()> { // From primitives let a = U256::from(42); let b = U256::from(100u64); // From strings let c = U256::from_str("1000000000000000000")?; // 1 ETH in wei // Arithmetic let sum = a + b; let product = a * b; let power = a.pow(U256::from(2)); println!("Sum: {}", sum); println!("Product: {}", product); println!("Power: {}", power); Ok(()) } ``` -------------------------------- ### Configure HTTP Provider with RPC_URL Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Connect to an HTTP JSON-RPC endpoint using the RPC_URL environment variable. ```text https://eth.public-rpc.com https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY https://mainnet.infura.io/v3/YOUR-PROJECT-ID https://localhost:8545 ``` ```rust use example_support::rpc_url; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let url = rpc_url()?; let provider = ProviderBuilder::new() .connect_http(url.parse()?); Ok(()) } ``` -------------------------------- ### Hardware Wallet Signing Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Configuring a provider to use a Ledger hardware wallet for signing. ```rust use alloy::signers::ledger::LedgerSigner; use alloy::providers::ProviderBuilder; let signer = LedgerSigner::new(LedgerHDPath::default()).await?; let provider = ProviderBuilder::new() .wallet(signer) .connect_http("https://eth.public-rpc.com".parse()?); ``` -------------------------------- ### Initialize and use an Alloy Provider Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Use ProviderBuilder to connect to a blockchain via HTTP and perform basic queries like fetching block numbers or balances. ```rust use alloy::providers::{Provider, ProviderBuilder}; let provider = ProviderBuilder::new() .connect_http("https://eth.public-rpc.com".parse()?); let block_number = provider.get_block_number().await?; let balance = provider.get_balance(address).await?; ``` -------------------------------- ### Handle Gas Estimation Failures Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Demonstrates estimating gas for a transaction and handling potential failures if the transaction would revert. ```rust #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new().connect_anvil(); let tx = TransactionRequest::default() .with_to(recipient); // May fail if transaction would revert let gas_estimate = provider.estimate_gas(&tx).await?; Ok(()) } ``` -------------------------------- ### Configure IPC Connection Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Establishes a local IPC connection for low-latency communication with a node. ```rust use alloy::providers::ProviderBuilder; let provider = ProviderBuilder::new() .connect_ipc("/tmp/reth/reth.ipc") .await?; ``` -------------------------------- ### Perform Common Alloy Type Conversions Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Demonstrates conversion methods for U256, Address, and unit parsing utilities. Requires appropriate imports from the alloy crate. ```rust // U256 conversions let u = U256::from(42); let u = U256::from_str("42")?; let string = u.to_string(); let hex = format!("{:#x}", u); // Address conversions let addr: Address = "0x1234...".parse()?; let string = addr.to_string(); let checksum = addr.to_checksum(); // ParseUnits let eth = parse_units("1.5", "ether")?; let token = parse_units("100", 6)?; // Format Units let formatted = format_units(U256::from(1_500_000_000_000_000_000), "ether")?; // Type conversions (Alloy ↔ Ethers) use helpers::alloy::ToEthers; let alloy_u256 = U256::from(100); let ethers_u256 = alloy_u256.to_ethers(); ``` -------------------------------- ### Implement AWS KMS Signer in Rust Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Initialize an AwsSigner using a KMS key ID and attach it to an Alloy provider. ```rust use alloy::signers::aws::AwsSigner; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let signer = AwsSigner::from_key_id("arn:aws:kms:...").await?; let provider = ProviderBuilder::new() .wallet(signer) .connect_http("https://eth.public-rpc.com".parse()?); Ok(()) } ``` -------------------------------- ### Configure IPC Provider with IPC_PATH Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Connect to a local node via IPC using the IPC_PATH environment variable. ```text /tmp/reth/reth.ipc /var/lib/geth/geth.ipc /Users/username/Library/Ethereum/geth.ipc ``` ```rust use example_support::ipc_path; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let path = ipc_path()?; let provider = ProviderBuilder::new() .connect_ipc(&path) .await?; Ok(()) } ``` -------------------------------- ### Address Definition and Usage Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Structure definition and common operations for Ethereum addresses. ```rust #[repr(transparent)] pub struct Address([u8; 20]); ``` ```rust use alloy::primitives::{address, Address}; // Compile-time verification let weth = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); // Runtime parsing let user: Address = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266".parse()?; // Checksum formatting println!("{}", user.to_checksum()); ``` -------------------------------- ### Implement ToAlloy for U256 Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/helpers.md Provides the implementation for converting ethers::types::U256 to alloy::primitives::U256. ```rust impl ToAlloy for ethers::types::U256 { type To = alloy::primitives::U256; fn to_alloy(self) -> Self::To { alloy::primitives::U256::from_limbs(self.0) } } ``` -------------------------------- ### Configure Anvil via CLI Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Command line arguments for configuring Anvil node parameters. ```bash anvil --block-time 1 --port 8545 ``` -------------------------------- ### Calculate Swap Amounts Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/helpers.md Functions to calculate output amounts for swaps or required input amounts across pools. ```rust pub fn get_amount_out(reserve_in: U256, reserve_out: U256, amount_in: U256) -> U256 ``` ```rust pub fn get_amount_in( reserves00: U256, reserves01: U256, is_weth0: bool, reserves10: U256, reserves11: U256, ) -> U256 ``` -------------------------------- ### Handle Network and Provider Connection Errors Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Demonstrates handling errors when connecting to an RPC endpoint or performing network requests. ```rust use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_http("invalid-url".parse()?); // URL parse error let block = provider.get_block_number().await?; // Connection error Ok(()) } ``` -------------------------------- ### Configure Anvil Connection Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Connects to an Anvil testing instance, optionally with auto-funded wallets. ```rust use alloy::providers::ProviderBuilder; // Built-in Anvil endpoint let provider = ProviderBuilder::new() .connect_anvil(); // With wallet (auto-funded accounts) let provider = ProviderBuilder::new() .connect_anvil_with_wallet(); ``` -------------------------------- ### Configure Middleware Fillers Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Manages automatic transaction filling, such as gas estimation and nonce management. ```rust use alloy::providers::{Provider, ProviderBuilder}; let provider = ProviderBuilder::new() // Automatically includes: // - ChainIdFiller: Sets chain_id // - GasFiller: Estimates gas and sets gas price // - NonceFiller: Manages account nonce .connect_anvil_with_wallet(); ``` ```rust let provider = ProviderBuilder::default() // No recommended fillers .disable_recommended_fillers() .connect_anvil_with_wallet(); ``` -------------------------------- ### Configure Custom Middleware Layers Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Adds custom Tower service layers to the provider stack. ```rust use alloy::providers::ProviderBuilder; use tower::ServiceBuilder; let provider = ProviderBuilder::new() // Add custom layers before connecting .connect_http("https://eth.public-rpc.com".parse()?); ``` -------------------------------- ### FixedBytes Creation and Usage Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Macros for creating fixed-size byte arrays and accessing their contents. ```rust use alloy::primitives::{b64, b128, b256, b512, fixed_bytes}; let h64 = b64!("0102030405060708"); let h128 = b128!("0102030405060708090a0b0c0d0e0f10"); let h256 = b256!("...(64 hex chars)..."); let h512 = b512!("...(128 hex chars)..."); let h_auto = fixed_bytes!("0102030405060708090a0b0c0d0e0f1011121314"); // B160 ``` ```rust use alloy::primitives::{b256, FixedBytes}; let hash = b256!("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); let len = hash.len(); // 32 let as_bytes: &[u8; 32] = &hash.0; ``` -------------------------------- ### Retrieve HTTP RPC URL Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Fetches the RPC_URL environment variable to connect an HTTP provider. Requires the variable to be set and non-empty. ```rust use example_support::rpc_url; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let url = rpc_url()?; let provider = ProviderBuilder::new().connect_http(url.parse()?); let block_number = provider.get_block_number().await?; println!("Current block: {}", block_number); Ok(()) } ``` ```bash RPC_URL=https://eth.public-rpc.com cargo run --example my_example ``` -------------------------------- ### Subscribe to Blockchain Events via WebSocket Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Establishes a WebSocket connection to subscribe to new block headers. ```bash WS_URL=wss://eth-mainnet.ws.alchemyapi.io/v2/YOUR-KEY cargo run --example subscribe_blocks ``` ```rust use alloy::providers::{Provider, ProviderBuilder, WsConnect}; use futures_util::StreamExt; #[tokio::main] async fn main() -> eyre::Result<()> { let ws = WsConnect::new("wss://eth-mainnet.ws.alchemyapi.io/v2/YOUR-KEY".parse()?); let provider = ProviderBuilder::new() .connect_ws(ws) .await?; // Subscribe to new blocks let subscription = provider.subscribe_blocks().await?; let mut stream = subscription.into_stream(); while let Some(block) = stream.next().await { println!("New block: {}", block.number); } Ok(()) } ``` -------------------------------- ### Local Testing with Anvil Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Spawns a local Anvil testnet to send a transaction between accounts and display the receipt. ```bash cargo run --example provider_builder ``` ```rust use alloy::providers::ProviderBuilder; use alloy::rpc::types::TransactionRequest; use alloy::network::TransactionBuilder; use alloy::primitives::U256; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_anvil_with_wallet(); let accounts = provider.get_accounts().await?; let alice = accounts[0]; let bob = accounts[1]; let tx = TransactionRequest::default() .with_to(bob) .with_value(U256::from(100)); let pending = provider.send_transaction(tx).await?; let receipt = pending.get_receipt().await?; println!("Transaction confirmed in block: {}", receipt.block_number.unwrap()); Ok(()) } ``` -------------------------------- ### AWS KMS Signing Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Configuring a provider to use AWS KMS for signing transactions. ```rust use alloy::signers::aws::AwsSigner; use alloy::providers::ProviderBuilder; let signer = AwsSigner::from_key_id("arn:aws:kms:...").await?; let provider = ProviderBuilder::new() .wallet(signer) .connect_http("https://eth.public-rpc.com".parse()?); ``` -------------------------------- ### Working with U256 Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Basic arithmetic and string conversion operations for U256 types. ```rust use alloy::primitives::U256; use std::str::FromStr; let amount = U256::from(100); let balance = U256::from_str("1000000000000000000")?; let result = amount + balance; let formatted = format!("{}", result); ``` -------------------------------- ### Calculate Swap Output Amount Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/helpers.md Computes the output amount for a Uniswap V2 swap using the constant product formula with a 0.3% fee. ```rust use helpers::alloy::get_amount_out; use alloy::primitives::U256; let reserve_dai = U256::from(1_000_000); let reserve_weth = U256::from(500); let amount_in = U256::from(1000); let amount_out = get_amount_out(reserve_dai, reserve_weth, amount_in); println!("WETH out: {}", amount_out); ``` -------------------------------- ### Contract Deployment & Interaction Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/quick-start.md Deploys a Counter contract to Anvil, modifies its state, and reads the updated value. ```bash cargo run --example deploy_from_artifact ``` ```rust use alloy::providers::ProviderBuilder; use alloy::primitives::U256; use alloy::sol; sol!( #[sol(rpc)] Counter, "examples/artifacts/Counter.json" ); #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_anvil_with_wallet(); // Deploy let contract = Counter::deploy(&provider).await?; println!("Deployed at: {}", contract.address()); // Call state-changing function let tx = contract.setNumber(U256::from(42)); tx.send().await?.watch().await?; // Call read-only function let number = contract.number().call().await?; println!("Number is now: {}", number); Ok(()) } ``` -------------------------------- ### Parse Address Strings Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Illustrates error cases for invalid address formats, including incorrect length and invalid characters. ```rust use alloy::primitives::Address; // Invalid: wrong length let addr: Address = "0x1234".parse() .expect_err("Too short"); // Error: address must be 40 hex chars // Invalid: wrong format let addr: Address = "not-an-address".parse() .expect_err("Invalid chars"); // Error: invalid hex character // Valid let addr: Address = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266".parse()?; ``` -------------------------------- ### get_amount_out() Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/helpers.md Calculates the output amount for a Uniswap V2 swap using the constant product formula. ```APIDOC ## get_amount_out(reserve_in, reserve_out, amount_in) ### Description Calculates output amount for a Uniswap V2 swap using the constant product formula: (amount_in * 997 * reserve_out) / (reserve_in * 1000 + amount_in * 997). ### Parameters - **reserve_in** (U256) - Reserve of the input token - **reserve_out** (U256) - Reserve of the output token - **amount_in** (U256) - Amount of input token to swap ### Returns - **U256** - The amount of output token received (accounting for 0.3% fee) ``` -------------------------------- ### Retrieve WebSocket RPC URL Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Fetches the WS_URL environment variable to connect a WebSocket provider. ```rust use example_support::ws_url; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let url = ws_url()?; let provider = ProviderBuilder::new().connect_ws(url.parse()?).await?; println!("Connected to WebSocket provider"); Ok(()) } ``` ```bash WS_URL=wss://eth-mainnet.ws.alchemyapi.io/v2/YOUR-API-KEY cargo run --example subscriptions ``` -------------------------------- ### Configure Retry Layer Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Sets up retry logic for HTTP requests. ```rust use alloy::providers::ProviderBuilder; use alloy_transport_http::Http; let provider = ProviderBuilder::new() // Configure retry logic .connect_http("https://eth.public-rpc.com".parse()?); ``` -------------------------------- ### Retrieve Multiple RPC URLs Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Fetches comma-separated RPC URLs from the RPC_URLS environment variable. Requires at least two endpoints. ```rust use example_support::rpc_urls; fn main() -> eyre::Result<()> { let urls = rpc_urls()?; println!("Using {} providers:", urls.len()); for url in urls { println!(" - {}", url); } Ok(()) } ``` ```bash RPC_URLS=https://eth.public-rpc.com,https://eth-mainnet.g.alchemy.com/v2/demo cargo run --example fallback_layer ``` ```rust // Input: "https://first.com, https://second.com, https://third.com " // Processing: // 1. Split by comma: ["https://first.com", " https://second.com", " https://third.com "] // 2. Trim each: ["https://first.com", "https://second.com", "https://third.com"] // 3. Filter empty: ["https://first.com", "https://second.com", "https://third.com"] // Output: vec!["https://first.com", "https://second.com", "https://third.com"] ``` -------------------------------- ### Connect via IPC Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Connects to a local node using an IPC path. ```rust use example_support::ipc_path; use alloy::providers::ProviderBuilder; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_ipc(&ipc_path()?) .await?; Ok(()) } ``` -------------------------------- ### Perform String and Parsing Conversions Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Methods for parsing addresses and U256 values from strings, and converting them back to string representations. ```rust // Parse from string let addr: Address = "0x1234...".parse()?; let u256 = U256::from_str("42")?; // To string let s: String = addr.to_string(); let s = format!("{:#x}", u256); // Hex format ``` -------------------------------- ### Handle Nonce Mismatch Errors Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Shows the error message for a nonce mismatch and the recommended way to prevent it using NonceFiller. ```text Error: nonce too low ``` ```rust let provider = ProviderBuilder::new() .connect_anvil_with_wallet(); // Includes NonceFiller ``` -------------------------------- ### Configure Anvil Node Options Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Programmatic configuration of Anvil node settings such as block time, port, and gas limits. ```rust use alloy::node_bindings::Anvil; let anvil = Anvil::new() .block_time(1) // 1 second block time .port(8545) // Custom port .gas_limit(u64::MAX) // Gas limit .balance(U256::from(100_000_000_000_000_000_000u128)); // 100 ETH per account let endpoint = anvil.endpoint_url(); ``` -------------------------------- ### Configure Fallback Layer Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Configures a list of endpoints to try sequentially upon failure. ```rust use alloy::providers::ProviderBuilder; let urls = vec![ "https://primary.example.com".parse()?, "https://secondary.example.com".parse()?, "https://tertiary.example.com".parse()?, ]; let provider = ProviderBuilder::new() .connect_layered_http(urls); ``` -------------------------------- ### Format EIP-55 Checksum Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Generates an EIP-55 compliant checksum string for an address. ```rust // EIP-55 checksum let checksum = address.to_checksum(); println!("{checksum}"); // "0x1234567890AbCdEF..." ``` -------------------------------- ### Handle empty environment variable errors Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/errors.md Ensure environment variables contain valid values rather than whitespace to prevent runtime errors. ```bash RPC_URL="" # Empty cargo run --example http # Error: RPC_URL must not be empty ``` -------------------------------- ### get_amount_out Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/helpers.md Calculates Uniswap V2 output amount with a 0.3% fee. ```APIDOC ## fn get_amount_out(reserve_in: U256, reserve_out: U256, amount_in: U256) -> U256 ### Description Calculates Uniswap V2 output amount with 0.3% fee (Ethers-rs version). ### Parameters - **reserve_in** (U256) - Required - Input token reserve - **reserve_out** (U256) - Required - Output token reserve - **amount_in** (U256) - Required - Input amount ### Returns - **U256** - Output amount after swap fee. ``` -------------------------------- ### required_env(name: &str) Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Retrieves a non-empty environment variable by name, returning an actionable error if missing or empty. ```APIDOC ## fn required_env(name: &str) ### Description Retrieves a non-empty environment variable by name. Returns an error if the variable is missing, empty, or contains only whitespace. ### Parameters - **name** (&str) - Required - The name of the environment variable to retrieve. ### Returns - **Result** - The value of the environment variable. ### Errors - Environment variable not found: "{name} must be set for this example" - Variable is empty or whitespace: "{name} must not be empty" ``` -------------------------------- ### Format raw token amounts Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Convert raw integer amounts into human-readable decimal strings. ```rust pub fn format_units(amount: T, units: U) -> Result ``` ```rust use alloy::primitives::utils::format_units; use alloy::primitives::U256; let balance = U256::from(1_500_000_000_000_000_000); let formatted = format_units(balance, "ether")?; println!("{}", formatted); // "1.5" let usdc = U256::from(100_000_000); let formatted = format_units(usdc, 6)?; println!("{}", formatted); // "100.0" ``` -------------------------------- ### Parsing Human-Readable Amounts Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/index.md Converting between human-readable strings and U256 values using unit parsing. ```rust use alloy::primitives::utils::{parse_units, format_units}; use alloy::primitives::U256; let eth_amount = parse_units("1.5", "ether")?; let token_amount = parse_units("100.5", 6)?; // USDC let formatted = format_units(U256::from(1_500_000_000_000_000_000), "ether")?; ``` -------------------------------- ### Implement Error Handling with eyre Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/example-support.md Uses eyre::Result for context-wrapped error reporting. Requires the example_support crate for environment variable helpers. ```rust use example_support::{rpc_url, required_env}; use eyre::{Result, WrapErr}; fn main() -> Result<()> { // Errors are automatically context-wrapped let rpc = rpc_url()?; // Error: "RPC_URL must contain a JSON-RPC endpoint\n\nCaused by:\n 0: RPC_URL must be set for this example" // You can add additional context let api_key = required_env("API_KEY").wrap_err("Failed to retrieve API credentials")?; Ok(()) } ``` -------------------------------- ### Spawn Reth Node Programmatically Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/configuration.md Spawns a local Reth instance and connects a provider to its endpoint. ```rust use alloy::node_bindings::Reth; use alloy::providers::ProviderBuilder; let reth = Reth::new().try_spawn()?; let provider = ProviderBuilder::new() .connect_http(reth.endpoint_url().parse()?); ``` -------------------------------- ### Bytes Definition and Usage Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/types.md Structure definition and common operations for variable-length byte arrays. ```rust pub struct Bytes(Arc<[u8]>); ``` ```rust use alloy::primitives::{bytes, Bytes}; let data = bytes!("0x1234abcd"); let len = data.len(); // 4 let hex = format!("{:#x}", &data); // "0x1234abcd" let slice = data.slice(0..2); ```