### Run Example with Features Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/00-index.md Executes an example with specific Cargo features enabled. This example uses the 'signer-aws' feature. ```bash cargo run --example aws_signer --features signer-aws ``` -------------------------------- ### Run an Example Source: https://github.com/alloy-rs/examples/blob/main/README.md To run any of the provided examples, use the `cargo run --example ` command followed by the example's name. ```sh cargo run --example mnemonic_signer ``` -------------------------------- ### Run All Examples Source: https://github.com/alloy-rs/examples/blob/main/CONTRIBUTING.md Execute all runnable examples in the project using the provided test script. ```sh ./scripts/test.sh ``` -------------------------------- ### Run a Single Example Source: https://github.com/alloy-rs/examples/blob/main/CONTRIBUTING.md Execute a specific runnable example by replacing $YOUR_EXAMPLE_NAME with the desired example's name. ```sh cargo run --example $YOUR_EXAMPLE_NAME ``` -------------------------------- ### Run a Specific Example Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/00-index.md Executes a particular example from the Alloy project. Replace 'builder' with the desired example name. ```bash cargo run --example builder ``` -------------------------------- ### Install Anvil Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/00-index.md Installs Anvil, a local test node required for running Alloy examples. Ensure you have curl installed. ```bash curl -L https://foundry.paradigm.xyz | bash && foundryup ``` -------------------------------- ### Example: Get Transaction Receipt and Assert Status Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/04-transaction-patterns.md Demonstrates how to retrieve a transaction receipt and check if the transaction was successful. It also shows how to access deployed contract addresses. ```rust let receipt = pending.get_receipt().await?; assert!(receipt.status(), "Transaction failed"); println!("Gas used: {}", receipt.gas_used); if let Some(addr) = receipt.contract_address { println!("Deployed at: {}", addr); } ``` -------------------------------- ### Project Structure Overview Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/01-project-overview.md Illustrates the monorepo structure of the Alloy Examples project, including the organization of helper libraries and example implementations. ```text examples/ ├── helpers/ # Shared helper library │ └── src/ │ ├── lib.rs # Main module exports │ ├── alloy.rs # Alloy-specific helpers │ └── ethers.rs # Ethers.rs compatibility helpers ├── examples/ # Example implementations organized by topic │ ├── advanced/ # Complex integration patterns │ ├── big-numbers/ # U256 and numeric operations │ ├── comparison/ # Multi-provider comparisons │ ├── contracts/ # Contract deployment and interaction │ ├── ens/ # Ethereum Name Service operations │ ├── fillers/ # Transaction middleware (gas, nonce, etc.) │ ├── layers/ # HTTP/WebSocket transport layers │ ├── node-bindings/ # Local node integration │ ├── primitives/ # Low-level primitive types │ ├── providers/ # Provider construction and configuration │ ├── queries/ # State and log queries │ ├── sol-macro/ # Solidity! macro patterns │ ├── subscriptions/ # Event and block subscriptions │ ├── transactions/ # Transaction construction and signing │ └── wallets/ # Signer implementations └── Cargo.toml # Workspace manifest ``` -------------------------------- ### Complete Contract Example with Derives and Usage Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/12-sol-macro.md A comprehensive example demonstrating the `sol!` macro with custom derives, event definitions, struct parameters, and asynchronous contract interaction using Alloy. ```rust use alloy::contract::ContractInstance; use alloy::primitives::{Address, U256}; use alloy::providers::Provider; use alloy::rpc::types::TransactionRequest; sol! { contract UniswapV3Router { #[derive(Debug)] event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); error TooLittleReceived(uint256 amountReceived); struct SwapExactInputSingleParams { bytes32 path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } function swapExactInputSingle( SwapExactInputSingleParams calldata params ) external payable returns (uint256 amountOut); function refundETH() external payable; } } #[tokio::main] async fn main() -> eyre::Result<()> { let provider = /* ... */; let params = SwapExactInputSingleParams { path: /* ... */, recipient: Address::from([0; 20]), deadline: /* ... */, amountIn: U256::from(1), amountOutMinimum: U256::from(0), sqrtPriceLimitX96: /* ... */, }; let contract = ContractInstance::new(router_addr, provider, abi); let tx = contract.swapExactInputSingle(params); let receipt = tx.send().await?.get_receipt().await?; println!("Swap succeeded in block {}", receipt.block_number); Ok(()) } ``` -------------------------------- ### Spawn Anvil with Custom Configuration and Error Handling Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Spawns a configured Anvil instance with explicit error handling. This example demonstrates setting block time and expects the 'anvil' binary to be installed. ```rust let anvil = Anvil::new() .block_time(1) .try_spawn() .expect("Anvil failed to start. Is 'anvil' installed?"); ``` -------------------------------- ### GasFiller Example Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/08-fillers-middleware.md Illustrates how the GasFiller automatically estimates gas limits and fees for transactions when included by default. ```rust use alloy::network::TransactionBuilder; use alloy::providers::ProviderBuilder; use alloy::rpc::types::TransactionRequest; use alloy::primitives::U256; let provider = ProviderBuilder::new() .connect_anvil_with_wallet(); // GasFiller included by default // Gas limit and fees are automatically filled let tx = TransactionRequest::default() .with_to(bob) .with_value(U256::from(100)); // No gas_limit, max_fee_per_gas, etc. set let pending = provider.send_transaction(tx).await?; // GasFiller has automatically estimated all fields ``` -------------------------------- ### Batch Balance Queries Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Efficiently retrieve balances for multiple addresses by batching JSON-RPC requests. This example uses futures for concurrent execution. ```rust let addresses = vec![addr1, addr2, addr3]; let futures: Vec<_> = addresses .iter() .map(|addr| provider.get_balance(*addr)) .collect(); let balances = futures::future::join_all(futures).await; ``` -------------------------------- ### Implement Custom Gas Priority Filler Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/08-fillers-middleware.md Create a custom filler to boost transaction pricing. This example shows how to increase the max fee per gas for urgent transactions. ```rust // From examples/fillers/examples/urgent_filler.rs use alloy::network::TransactionBuilder; use alloy::rpc::types::TransactionRequest; use alloy::primitives::U256; struct UrgentFiller { priority_boost: f64, // 1.5 = 50% boost } impl UrgentFiller { pub fn apply_urgent_pricing( &self, mut tx: TransactionRequest, ) -> TransactionRequest { if let Some(max_fee) = tx.max_fee_per_gas { let boosted = (max_fee as f64 * self.priority_boost) as u128; tx = tx.with_max_fee_per_gas(boosted); } tx } } let urgent = UrgentFiller { priority_boost: 1.5 }; let tx = TransactionRequest::default().with_to(bob).with_value(U256::from(100)); let tx_with_boost = urgent.apply_urgent_pricing(tx); ``` -------------------------------- ### Simulation Example: Uniswap V2 Arbitrage Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/14-advanced-patterns.md Demonstrates a full arbitrage simulation using `get_amount_in` and `get_amount_out` to calculate potential profit from trading between two liquidity pools (Uniswap and Sushiswap). ```APIDOC ## Simulation Example: Uniswap V2 Arbitrage ### Description This example simulates an arbitrage opportunity between two liquidity pools (Uniswap and Sushiswap) by calculating the necessary swap amounts and the resulting profit. ### Code ```rust use alloy::primitives::U256; use helpers::alloy::{ get_uniswap_pair, get_sushi_pair, get_amount_out, get_amount_in }; #[tokio::main] async fn main() -> eyre::Result<()> { let uniswap = get_uniswap_pair(); let sushi = get_sushi_pair(); // Calculate arbitrage amount let arb_amount = get_amount_in( uniswap.reserve0, uniswap.reserve1, true, sushi.reserve0, sushi.reserve1, ); println!("Arbitrage amount: {}", arb_amount); // Simulate trade: DAI → WETH on Uniswap let weth_out = get_amount_out( uniswap.reserve0, // DAI uniswap.reserve1, // WETH arb_amount, ); println!("After Uniswap: {} WETH", weth_out); // Return trade: WETH → DAI on Sushiswap let dai_back = get_amount_out( sushi.reserve1, // WETH sushi.reserve0, // DAI weth_out, ); println!("After Sushiswap: {} DAI", dai_back); let profit = dai_back.saturating_sub(arb_amount); println!("Profit: {} DAI", profit); Ok(()) } ``` ``` -------------------------------- ### Simulate Uniswap V2 Arbitrage Trade Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/14-advanced-patterns.md This example demonstrates a full arbitrage simulation between Uniswap V2 and Sushiswap. It calculates the arbitrage amount, simulates trades in both directions, and determines the profit. ```rust use alloy::primitives::U256; use helpers::alloy::{ get_uniswap_pair, get_sushi_pair, get_amount_out, get_amount_in }; #[tokio::main] async fn main() -> eyre::Result<()> { let uniswap = get_uniswap_pair(); let sushi = get_sushi_pair(); // Calculate arbitrage amount let arb_amount = get_amount_in( uniswap.reserve0, uniswap.reserve1, true, sushi.reserve0, sushi.reserve1, ); println!("Arbitrage amount: {}", arb_amount); // Simulate trade: DAI → WETH on Uniswap let weth_out = get_amount_out( uniswap.reserve0, // DAI uniswap.reserve1, // WETH arb_amount, ); println!("After Uniswap: {} WETH", weth_out); // Return trade: WETH → DAI on Sushiswap let dai_back = get_amount_out( sushi.reserve1, // WETH sushi.reserve0, // DAI weth_out, ); println!("After Sushiswap: {} DAI", dai_back); let profit = dai_back.saturating_sub(arb_amount); println!("Profit: {} DAI", profit); Ok(()) } ``` -------------------------------- ### HTTP Provider with Authentication and Fillers Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/08-fillers-middleware.md Connect to an HTTP endpoint, potentially with authentication, using the ProviderBuilder. This example shows a basic HTTP connection with default fillers enabled. ```rust use alloy::providers::ProviderBuilder; // HTTP with authentication and fillers let provider_auth = ProviderBuilder::new() .connect_http("https://eth.llamarpc.com".parse()?); ``` -------------------------------- ### Initialize New Filter Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/07-subscriptions-events.md Creates a new, empty filter instance. Use this as a starting point for building filter criteria. ```rust pub fn new() -> Self ``` -------------------------------- ### Set Start Block for Query Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/07-subscriptions-events.md Specifies the starting block number or tag for historical event queries. Supports specific block numbers, 'Latest', 'Earliest', and 'Pending'. ```rust pub fn from_block(mut self, block: BlockNumberOrTag) -> Self ``` -------------------------------- ### Get Account Balance Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md Query the balance of a specific Ethereum address in Wei. Requires an active `Provider` instance. ```rust let balance = provider.get_balance(alice).await?; println!("Balance: {} wei", balance); ``` -------------------------------- ### Spawn Anvil Instance with Default Configuration Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Creates a new Anvil builder with default settings and spawns a local EVM instance. Ensure the 'anvil' binary is installed and in your PATH. ```rust use alloy::node_bindings::Anvil; let anvil = Anvil::new().try_spawn()?; println!("Running on: {}", anvil.endpoint()); ``` -------------------------------- ### sol! Macro Return Types Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/12-sol-macro.md Shows how functions with single or multiple return values are defined in the `sol!` macro and provides examples of their usage for calling. ```rust sol! { contract Token { // Single return function balanceOf(address account) external view returns (uint256); // Multiple returns function getAmounts() external view returns (uint256 amount0, uint256 amount1); } } // Call usage let balance = contract.balanceOf(address).call().await?; let (a0, a1) = contract.getAmounts().call().await?; ``` -------------------------------- ### Implement Request Logging Middleware Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/08-fillers-middleware.md Add a custom middleware layer to log RPC requests and responses. This example uses a Tower-compatible service to intercept and log before forwarding the request to the inner service. ```rust use alloy::providers::ProviderBuilder; use tower::ServiceBuilder; use std::task::{Context, Poll}; use std::pin::Pin; use futures::future::BoxFuture; struct LoggingMiddleware { inner: S, } impl Service for LoggingMiddleware where S: Service, { type Response = S::Response; type Error = S::Error; type Future = BoxFuture<'static, Result>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { self.inner.poll_ready(cx) } fn call(&mut self, req: Request) -> Self::Future { println!("RPC Request: {}", req.method); let fut = self.inner.call(req); Box::pin(async move { let res = fut.await?; println!("RPC Response received"); Ok(res) }) } } let provider = ProviderBuilder::new() .layer(LoggingMiddleware { inner: /* ... */ }) .connect_http(url.parse()?); ``` -------------------------------- ### Get All Events for an Address Since a Specific Block Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Retrieve all event logs emitted by a contract address starting from a given block number. Requires setting up a Filter object. ```rust let filter = Filter::new() .address(contract_address) .from_block(BlockNumberOrTag::number(start_block)); let logs = provider.get_logs(&filter).await?; println!("Found {} events", logs.len()); ``` -------------------------------- ### Spawn Geth Client Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Instantiate and spawn a Geth client using the builder pattern. Requires `alloy::node_bindings::Geth`. ```rust use alloy::node_bindings::Geth; let geth = Geth::new() .port(8545) .try_spawn()?; let provider = ProviderBuilder::new() .connect_http(geth.endpoint().parse()?); ``` -------------------------------- ### Recommended Fillers Source: https://github.com/alloy-rs/examples/blob/main/README.md Demonstrates the use of a combination of recommended middleware fillers for transaction management. ```rust use alloy::providers::Provider; use alloy::transports::http::HTTP; use alloy::signers::Signer; use alloy::signers::local::LocalWallet; use alloy::middleware::gas_filler::GasFiller; use alloy::middleware::nonce_filler::NonceFiller; use alloy::middleware::gas_oracle::GasOracle; #[tokio::main] async fn main() -> Result<(), Box> { let provider = HTTP::new("http://localhost:8545"); let signer: LocalWallet = "0x...".parse()?; let gas_oracle = GasOracle::new(provider.clone()); let gas_filler = GasFiller::new(provider.clone(), gas_oracle); let nonce_filler = NonceFiller::new(gas_filler, signer.address()); // The provider is now wrapped with both gas and nonce management let final_provider = nonce_filler; // let tx_hash = final_provider.send_transaction(...).await?; Ok(()) } ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/alloy-rs/examples/blob/main/CONTRIBUTING.md Examples of commit messages adhering to the Conventional Commits specification, used for categorizing changes like features, chores, tests, and formatting. ```git feat(abigen): support empty events ``` ```git chore: bump crypto deps ``` ```git test: simplify test cleanup ``` ```git fmt: run rustfmt ``` -------------------------------- ### Create a New Provider Builder Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md Initializes a new `ProviderBuilder`. Recommended fillers like `ChainIdFiller`, `GasFiller`, and `NonceFiller` are enabled by default. ```rust use alloy::providers::ProviderBuilder; let builder = ProviderBuilder::new(); ``` -------------------------------- ### ContractInstance::function Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/06-contract-interaction.md Gets a builder for calling a specific contract function with inline arguments. ```APIDOC ## ContractInstance::function ### Description Gets a builder for calling a specific contract function. ### Signature ```rust pub fn function(&self, name: &str, args: &[DynSolValue]) -> Result ``` ### Parameters - **name** (`&str`) - Function name in contract ABI - **args** (`&[DynSolValue]`) - Function arguments as dynamic values ### Returns `Result` — Function call builder ### Throws - `Error` — If function not found in ABI ### Example ```rust use alloy::dyn_abi::DynSolValue; use alloy::primitives::U256; // Call `setNumber(uint256 newNumber)` let builder = contract.function("setNumber", &[DynSolValue::from(U256::from(42))])?; let tx_hash = builder.send().await?.watch().await?; ``` ``` -------------------------------- ### Alloy Module Constants Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/02-helpers-library.md Constants for common addresses used in Alloy examples, such as WETH and DAI. ```APIDOC ## WETH_ADDR ### Description Mainnet Wrapped Ether (WETH) contract address. ### Signature `pub static WETH_ADDR: Address = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); ``` ```APIDOC ## DAI_ADDR ### Description Mainnet Dai stablecoin (DAI) contract address. ### Signature `pub static DAI_ADDR: Address = address!("6B175474E89094C44Da98b954EedeAC495271d0F"); ``` -------------------------------- ### Ledger Get Accounts Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/05-wallet-signers.md Retrieves a list of derived account addresses available on the connected Ledger device. ```APIDOC ## Ledger Get Accounts ### Description Retrieves accounts available on the Ledger device. ### Method `get_accounts(&self) -> Result>` ### Returns `Result>` — List of derived account addresses ``` -------------------------------- ### Create Address using address! macro Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/09-primitives-types.md Use the `address!()` macro for convenient creation of an Address from a hex string. Ensure the string is a valid Ethereum address. ```rust use alloy::primitives::address; let addr = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); ``` -------------------------------- ### Get Address from PrivateKeySigner Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/05-wallet-signers.md Retrieves the Ethereum address associated with the `PrivateKeySigner`. This address is derived from the private key. ```rust pub fn address(&self) -> Address ``` -------------------------------- ### connect_anvil_with_wallet() Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md Connects to Anvil and automatically attaches the first default Anvil account (Alice) as a signer. ```APIDOC ## connect_anvil_with_wallet() ### Description Connects to Anvil and automatically attaches the first default Anvil account (Alice) as a signer. ### Signature ```rust pub fn connect_anvil_with_wallet(self) -> Provider> ``` ### Returns `Provider>` — Connected provider with first Anvil account as signer ### Example ```rust let provider = ProviderBuilder::new().connect_anvil_with_wallet(); let alice = provider.get_accounts().await?[0]; let tx = TransactionRequest::default() .with_to(bob) .with_value(U256::from(100)); let receipt = provider.send_transaction(tx).await?.get_receipt().await?; ``` ``` -------------------------------- ### Get Account Balance - Rust Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Retrieves the balance of an account in Wei. Can be converted to ETH by dividing by 10^18. ```rust let balance = provider.get_balance(alice).await?; println!("Balance: {} wei", balance); // Convert to ETH let eth = balance / U256::from(1_000_000_000_000_000_000u128); println!("Balance: {} ETH", eth); ``` -------------------------------- ### Get Transaction By Hash Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Retrieves a transaction from the blockchain using its hash. Returns `Some(Transaction)` if found, otherwise `None`. ```APIDOC ## Get Transaction By Hash ### Description Retrieves a transaction from the blockchain using its hash. Returns `Some(Transaction)` if found, otherwise `None`. ### Method `Provider::get_transaction_by_hash(&self, hash: H256) -> Result>` ### Parameters #### Path Parameters - **hash** (H256) - Required - Transaction hash ### Request Example ```rust if let Some(tx) = provider.get_transaction_by_hash(tx_hash).await? { println!("From: {}", tx.from); println!("To: {:?}", tx.to); println!("Value: {}", tx.value); println!("Gas: {}", tx.gas); println!("Nonce: {}", tx.nonce()); } ``` ### Response #### Success Response - **Transaction** (Transaction) - Transaction data if found. - **None** - If the transaction is not found. ``` -------------------------------- ### Initialize AWS KMS Signer Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/05-wallet-signers.md Creates a new AWS KMS signer. Requires AWS configuration and a KMS client. Use for cloud-hosted keys. ```rust use alloy::signers::aws::AwsSigner; use aws_config::load_from_env; use aws_sdk_kms::Client; let config = load_from_env().await; let kms_client = Client::new(&config); let signer = AwsSigner::new("arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012", kms_client).await?; ``` -------------------------------- ### Solidity Macro Syntax Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/12-sol-macro.md The basic syntax for the `sol!` macro, demonstrating how to define a contract with functions, events, and errors. ```APIDOC ## Solidity Macro Basic Syntax ### Description Defines a Solidity contract within Rust code, including functions, events, and custom errors. ### Code ```rust sol! { contract MyContract { function transfer(address to, uint256 amount) external; event Transfer(address indexed from, address indexed to, uint256 value); error InsufficientBalance(uint256 available, uint256 required); } } ``` ``` -------------------------------- ### Get Transaction Receipt Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Retrieves the receipt for a transaction using its hash. Returns `Some(TransactionReceipt)` if the transaction has been mined, otherwise `None`. ```APIDOC ## Get Transaction Receipt ### Description Retrieves the receipt for a transaction using its hash. Returns `Some(TransactionReceipt)` if the transaction has been mined, otherwise `None`. ### Method `Provider::get_transaction_receipt(&self, hash: H256) -> Result>` ### Parameters #### Path Parameters - **hash** (H256) - Required - Transaction hash ### Request Example ```rust if let Some(receipt) = provider.get_transaction_receipt(tx_hash).await? { println!("Block: {}", receipt.block_number.unwrap_or(0)); println!("Gas used: {}", receipt.gas_used); println!("Status: {}", if receipt.status() { "Success" } else { "Reverted" }); println!("Logs: {}", receipt.logs.len()); for log in &receipt.logs { println!(" Event from: {}", log.address); } } ``` ### Response #### Success Response - **TransactionReceipt** (TransactionReceipt) - The receipt of the mined transaction. - **None** - If the transaction has not yet been mined. ``` -------------------------------- ### Provider Builder with Default and Custom Fillers Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/08-fillers-middleware.md Construct a provider using default recommended fillers and adding a custom signer. This enables ChainIdFiller, GasFiller, and NonceFiller by default, with WalletFiller added via the signer. ```rust use alloy::providers::ProviderBuilder; use alloy::signers::local::PrivateKeySigner; let signer = "0xac0974bec39a17e36ba4a6b4d238ff944bacb476caded5cf4646a9de0001f4a6" .parse::()?; // Default recommended fillers + custom signer let provider = ProviderBuilder::new() // ChainIdFiller, GasFiller, NonceFiller enabled by default .wallet(signer) // WalletFiller added .connect_http("http://localhost:8545".parse()?); // Or customize which fillers are included let provider_minimal = ProviderBuilder::new() .disable_recommended_fillers() .wallet(signer) .connect_http("http://localhost:8545".parse()?); ``` -------------------------------- ### Get Chain ID Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md Retrieve the current chain ID of the connected Ethereum network. Used to verify network compatibility. ```rust let chain_id = provider.get_chain_id().await?; assert_eq!(chain_id, 1); // Mainnet ``` -------------------------------- ### Deploy and Link Library Source: https://github.com/alloy-rs/examples/blob/main/README.md Deploys a contract that depends on a library, linking the library during deployment. ```rust use alloy::contract::ContractDeployer; use alloy::providers::Provider; use alloy::transports::http::HTTP; use alloy::signers::Signer; use alloy::signers::local::LocalWallet; use alloy_contracts::MyContractWithLibrary; use alloy_contracts::MyLibrary; #[tokio::main] async fn main() -> Result<(), Box> { let provider = HTTP::new("http://localhost:8545"); let signer: LocalWallet = "0x...".parse()?; let library_deployer = ContractDeployer::new(provider.clone(), signer.clone()); let library_instance = library_deployer.deploy(MyLibrary::abi()).await?; let contract_deployer = ContractDeployer::new(provider, signer); let contract_instance = contract_deployer.deploy_with_libraries( MyContractWithLibrary::abi(), [("MyLibrary", library_instance.address())] ).await?; println!("Contract deployed at: {:?}", contract_instance.address()); Ok(()) } ``` -------------------------------- ### Get Ethereum Accounts Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md Retrieve a list of accounts managed by the connected Ethereum node. Requires an active `Provider` instance. ```rust let accounts = provider.get_accounts().await?; println!("Available accounts: {:?}", accounts); ``` -------------------------------- ### Get Latest Block Number (Alloy Rust) Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Fetch the current latest block number on the chain using `Provider::get_block_number`. ```rust let block_num = provider.get_block_number().await?; println!("Latest block: {}", block_num); ``` -------------------------------- ### Anvil::new() Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Creates a new Anvil builder with default configurations for port, chain ID, pre-funded accounts, block time, and fork state. ```APIDOC ## Anvil::new() ### Description Creates a new Anvil builder with default configurations. ### Returns `Anvil` — New Anvil builder with defaults ### Default Configuration: - Port: Random available port (between 10000-65535) - Chain ID: 31337 - Accounts: 10 pre-funded accounts with 10000 ETH each - Block time: Instant blocks (no automatic mining) - Fork: None (fresh state) ### Example: ```rust use alloy::node_bindings::Anvil; let anvil = Anvil::new().try_spawn()?; println!("Running on: {}", anvil.endpoint()); ``` ``` -------------------------------- ### Get DAI-WETH SushiSwap Pair Data Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/02-helpers-library.md Retrieves the DAI-WETH SushiSwap pair data using Ethers address and U256 types. ```rust pub fn get_sushi_pair() -> UniV2Pair ``` -------------------------------- ### Hashing Functions Source: https://github.com/alloy-rs/examples/blob/main/README.md Shows how to use various hashing functions like Keccak-256. ```rust use alloy::primitives::keccak256; fn main() { let data = b"hello world"; let hash = keccak256(data); println!("Keccak-256 hash: {}", hash); } ``` -------------------------------- ### Get SushiSwap DAI-WETH Pair Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/02-helpers-library.md Retrieves hardcoded configuration for the SushiSwap DAI-WETH pair on mainnet. Use this for SushiSwap specific interactions. ```rust let sushi_pair = get_sushi_pair(); assert_eq!(sushi_pair.token0, DAI_ADDR); assert_eq!(sushi_pair.token1, WETH_ADDR); ``` -------------------------------- ### Create Contract Instance Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/06-contract-interaction.md Instantiates a `ContractInstance` for interacting with a deployed contract. Requires the contract's address, an RPC provider, and its ABI interface. The ABI is typically loaded from an artifact file. ```rust use alloy::contract::{ContractInstance, Interface}; use serde_json; let path = "artifacts/Counter.json"; let artifact = std::fs::read(path)?; let json: serde_json::Value = serde_json::from_slice(&artifact)?; let abi = serde_json::from_str(&json.get("abi").unwrap().to_string())?; let interface = Interface::new(abi); let contract = ContractInstance::new(address, provider.clone(), interface); ``` -------------------------------- ### ContractInstance::new Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/06-contract-interaction.md Creates a new contract instance for interacting with an already-deployed contract. ```APIDOC ## ContractInstance::new ### Description Creates a new contract instance for interacting with an already-deployed contract. ### Signature ```rust pub fn new(address: Address, provider: P, abi: Interface) -> Self ``` ### Parameters - **address** (`Address`) - Deployed contract address - **provider** (`P`) - Provider for RPC calls - **abi** (`Interface`) - Contract ABI interface ### Returns `ContractInstance` — Instance for interaction ### Example ```rust use alloy::contract::{ContractInstance, Interface}; use serde_json; let path = "artifacts/Counter.json"; let artifact = std::fs::read(path)?; let json: serde_json::Value = serde_json::from_slice(&artifact)?; let abi = serde_json::from_str(&json.get("abi").unwrap().to_string())?; let interface = Interface::new(abi); let contract = ContractInstance::new(address, provider.clone(), interface); ``` ``` -------------------------------- ### Get Transaction Count (Nonce) Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md Fetch the next available nonce for a given Ethereum address. This is crucial for sending transactions sequentially. ```rust let nonce = provider.get_transaction_count(alice).await?; ``` -------------------------------- ### Get Transaction by Hash Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Retrieves transaction details using its hash. Use this when you need to inspect a specific transaction's properties after it has been submitted. ```rust if let Some(tx) = provider.get_transaction_by_hash(tx_hash).await? { println!("From: {}", tx.from); println!("To: {:?}", tx.to); println!("Value: {}", tx.value); println!("Gas: {}", tx.gas); println!("Nonce: {}", tx.nonce()); } ``` -------------------------------- ### Deploy Contract from Contract Definition Source: https://github.com/alloy-rs/examples/blob/main/README.md Deploys a smart contract using a contract definition, likely generated from an ABI. ```rust use alloy::contract::ContractDeployer; use alloy::providers::Provider; use alloy::transports::http::HTTP; use alloy::signers::Signer; use alloy::signers::local::LocalWallet; use alloy_contracts::MyContract; #[tokio::main] async fn main() -> Result<(), Box> { let provider = HTTP::new("http://localhost:8545"); let signer: LocalWallet = "0x...".parse()?; let deployer = ContractDeployer::new(provider.clone(), signer); let contract_instance = deployer.deploy(MyContract::abi()).await?; println!("Contract deployed at: {:?}", contract_instance.address()); Ok(()) } ``` -------------------------------- ### Anvil::try_spawn() Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Spawns the configured Anvil instance as a child process. Requires the `anvil` binary to be in the system's PATH. ```APIDOC ## Anvil::try_spawn() ### Description Spawns the configured Anvil instance. Requires the `anvil` binary to be in $PATH. ### Method `pub fn try_spawn(self) -> Result` ### Returns `Result` — A running Anvil instance. ### Throws: - `Error` — If Anvil is not found in $PATH or if there is a port binding failure. ### Prerequisites: - `anvil` binary must be in $PATH ### Example: ```rust let anvil = Anvil::new() .block_time(1) .try_spawn() .expect("Anvil failed to start. Is 'anvil' installed?"); ``` ``` -------------------------------- ### Get Contract Bytecode - Rust Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Retrieves the runtime bytecode deployed at an address. Returns empty bytes if the address is not a contract (EOA or empty). ```rust let code = provider.get_code(contract_address).await?; println!("Bytecode length: {} bytes", code.len()); if code.is_empty() { println!("Address is not a contract (EOA or empty)"); } ``` -------------------------------- ### Subscribe to Pending Transactions Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/07-subscriptions-events.md Subscribes to transactions that are in the mempool but not yet included in a block. This example fetches and prints details for the first 10 pending transactions. ```rust let subscription = provider.subscribe_pending_transactions().await?; let mut stream = subscription.into_stream().take(10); while let Some(tx_hash) = stream.next().await { println!("Pending: {}", tx_hash); let tx = provider.get_transaction_by_hash(tx_hash).await?; if let Some(tx) = tx { println!("From: {:?}, To: {:?}", tx.from, tx.to); } } ``` -------------------------------- ### Spawn Anvil and Connect Provider Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Spawns a local Anvil instance with a 1-second block time, creates a provider connected to it, and funds an account. Requires `tokio` for async execution. ```rust use alloy::node_bindings::Anvil; use alloy::providers::{Provider, ProviderBuilder}; #[tokio::main] async fn main() -> eyre::Result<()> { // Spawn Anvil let anvil = Anvil::new().block_time(1).try_spawn()?; // Create provider with signer let signer: PrivateKeySigner = anvil.keys()[0].clone().into(); let provider = ProviderBuilder::new() .wallet(signer) .connect_http(anvil.endpoint().parse()?); // Get accounts let alice = provider.get_accounts().await?[0]; let bob = anvil.addresses()[1]; // Fund an account let account = anvil.addresses()[5]; provider.anvil_set_balance(account, U256::from(1_000_000_000_000_000_000_000u128)).await?; Ok(()) } ``` -------------------------------- ### Geth Client Binding Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Provides Rust bindings for the Geth Ethereum client, allowing programmatic interaction and spawning of a Geth instance. ```APIDOC ## Type: `Geth` Rust bindings for the Geth Ethereum client. **Signature**: ```rust pub struct Geth { child: Child, port: u16, } ``` ### Usage Similar builder pattern to Anvil: ```rust use alloy::node_bindings::Geth; let geth = Geth::new() .port(8545) .try_spawn()?; let provider = ProviderBuilder::new() .connect_http(geth.endpoint().parse()?); ``` ``` -------------------------------- ### Interface Constructor and Methods Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/06-contract-interaction.md Methods for creating and querying contract ABI interfaces. ```APIDOC ## Type: `Interface` ABI interface for decoding/encoding contract interactions. ### Constructor #### `new()` **Signature**: ```rust pub fn new(abi: JsonAbi) -> Self ``` **Parameters**: | Parameter | Type | Description | |-----------|------|-------------| | `abi` | `JsonAbi` | Parsed ABI JSON | **Returns**: `Interface` — ABI interface **Description**: Creates an interface from parsed JSON ABI. ### Methods #### `functions()` **Signature**: ```rust pub fn functions(&self) -> impl Iterator)> ``` **Returns**: Iterator over function definitions #### `events()` **Signature**: ```rust pub fn events(&self) -> impl Iterator)> ``` **Returns**: Iterator over event definitions #### `errors()` **Signature**: ```rust pub fn errors(&self) -> impl Iterator)> ``` **Returns**: Iterator over error definitions ``` -------------------------------- ### Get Transaction Receipt Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/13-query-patterns.md Fetches the receipt for a given transaction hash. This is useful for checking the status, gas used, and events emitted by a transaction after it has been mined. ```rust if let Some(receipt) = provider.get_transaction_receipt(tx_hash).await? { println!("Block: {}", receipt.block_number.unwrap_or(0)); println!("Gas used: {}", receipt.gas_used); println!("Status: {}", if receipt.status() { "Success" } else { "Reverted" }); println!("Logs: {}", receipt.logs.len()); for log in &receipt.logs { println!(" Event from: {}", log.address); } } ``` -------------------------------- ### Get DAI-WETH Uniswap V2 Pair Data Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/02-helpers-library.md Retrieves the DAI-WETH Uniswap V2 pair data using Ethers address and U256 types. ```rust pub fn get_uniswap_pair() -> UniV2Pair ``` -------------------------------- ### Connect to a Local Anvil Instance Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md A convenience method to connect to a locally running Anvil instance at the default endpoint (`http://127.0.0.1:8545`) with recommended fillers enabled. Requires Anvil to be running. ```rust let provider = ProviderBuilder::new().connect_anvil(); let accounts = provider.get_accounts().await?; ``` -------------------------------- ### Deploy Contract from Artifact Source: https://github.com/alloy-rs/examples/blob/main/README.md Deploys a smart contract to the blockchain using its ABI artifact. ```rust use alloy::contract::ContractDeployer; use alloy::providers::Provider; use alloy::transports::http::HTTP; use alloy::signers::Signer; use alloy::signers::local::LocalWallet; use alloy_contracts::MyContract; // Assuming MyContract is generated from ABI #[tokio::main] async fn main() -> Result<(), Box> { let provider = HTTP::new("http://localhost:8545"); let signer: LocalWallet = "0x...".parse()?; let deployer = ContractDeployer::new(provider.clone(), signer); let contract_instance = deployer.deploy(MyContract::abi()).await?; println!("Contract deployed at: {:?}", contract_instance.address()); Ok(()) } ``` -------------------------------- ### Get Anvil WebSocket RPC Endpoint Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Retrieves the WebSocket RPC endpoint URL for the running Anvil instance. This is useful for real-time event subscriptions. ```rust let ws_url = anvil.ws_endpoint(); // "ws://127.0.0.1:PORT" let ws = WsConnect::new(ws_url); ``` -------------------------------- ### Create Instances of Big Numbers Source: https://github.com/alloy-rs/examples/blob/main/README.md Illustrates various ways to create instances of big number types. ```rust use alloy::primitives::U256; fn main() { // From primitive types let from_u64 = U256::from(100u64); let from_str = U256::from_str_radix("12345", 10).unwrap(); // From byte arrays (little-endian) let bytes = [1u8; 32]; let from_bytes = U256::from_be_bytes(bytes); println!("From u64: {}", from_u64); println!("From str: {}", from_str); println!("From bytes: {}", from_bytes); } ``` -------------------------------- ### Get Anvil HTTP RPC Endpoint Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Retrieves the HTTP RPC endpoint URL for the running Anvil instance. This URL can be used to connect providers. ```rust let url = anvil.endpoint(); // "http://127.0.0.1:PORT" let provider = ProviderBuilder::new().connect_http(url.parse()?); ``` -------------------------------- ### Get Uniswap V2 DAI-WETH Pair Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/02-helpers-library.md Retrieves hardcoded configuration for the Uniswap V2 DAI-WETH pair on mainnet. Used for direct pair data access. ```rust let uniswap_pair = get_uniswap_pair(); assert_eq!(uniswap_pair.token0, DAI_ADDR); assert_eq!(uniswap_pair.token1, WETH_ADDR); ``` -------------------------------- ### Anvil Instance Methods Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Methods available on a running Anvil instance to retrieve connection details and pre-funded accounts. ```APIDOC ## Anvil::endpoint() ### Description Gets the HTTP RPC endpoint URL for the running Anvil instance. ### Method `pub fn endpoint(&self) -> String` ### Returns `String` — The HTTP RPC endpoint URL (e.g., "http://127.0.0.1:PORT"). ### Example: ```rust let url = anvil.endpoint(); // "http://127.0.0.1:PORT" let provider = ProviderBuilder::new().connect_http(url.parse()?); ``` ## Anvil::endpoint_url() ### Description Gets the parsed URL object for the Anvil instance's HTTP RPC endpoint. ### Method `pub fn endpoint_url(&self) -> Url` ### Returns `Url` — A parsed URL object representing the HTTP RPC endpoint. ## Anvil::ws_endpoint() ### Description Gets the WebSocket RPC endpoint URL for the running Anvil instance. ### Method `pub fn ws_endpoint(&self) -> String` ### Returns `String` — The WebSocket RPC endpoint URL (e.g., "ws://127.0.0.1:PORT"). ### Example: ```rust let ws_url = anvil.ws_endpoint(); // "ws://127.0.0.1:PORT" let ws = WsConnect::new(ws_url); ``` ## Anvil::addresses() ### Description Retrieves a list of all pre-funded accounts available in the Anvil instance. ### Method `pub fn addresses(&self) -> Vec
` ### Returns `Vec
` — A vector containing the addresses of the 10 pre-funded accounts. ### Example: ```rust let accounts = anvil.addresses(); println!("Alice: {}", accounts[0]); println!("Bob: {}", accounts[1]); ``` ## Anvil::keys() ### Description Retrieves the private keys for all pre-funded accounts. ### Method `pub fn keys(&self) -> Vec` ### Returns `Vec` — A vector containing the private keys, in the same order as `addresses()`. ### Example: ```rust let signer: PrivateKeySigner = anvil.keys()[0].clone().into(); let provider = ProviderBuilder::new() .wallet(signer) .connect_http(anvil.endpoint().parse()?); ``` ``` -------------------------------- ### Deploy Contract from Bytecode Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/06-contract-interaction.md Deploy a contract directly using its raw bytecode. Ensure the bytecode is correctly decoded from its hex representation. ```rust use alloy::primitives::hex; use alloy::rpc::types::TransactionRequest; let bytecode = hex::decode("6080806040...")?; let tx = TransactionRequest::default().with_deploy_code(bytecode); let receipt = provider.send_transaction(tx).await?.get_receipt().await?; let contract_address = receipt .contract_address .expect("Failed to get contract address"); println!("Contract deployed at: {}", contract_address); ``` -------------------------------- ### connect_anvil_with_config() Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/03-provider-patterns.md Connects to Anvil with custom configuration passed to the Anvil builder. ```APIDOC ## connect_anvil_with_config(self, config: F) ### Description Connects to Anvil with custom configuration passed to the Anvil builder. ### Signature ```rust pub fn connect_anvil_with_config(self, config: F) -> Provider> where F: Fn(Anvil) -> Anvil ``` ### Parameters #### Path Parameters - **config** (`F: Fn(Anvil) -> Anvil`) - Required - Closure to configure Anvil instance ### Returns `Provider>` — Connected provider with configured Anvil ### Available Configurations - `.block_time(seconds)` — Set block production interval - `.chain_id(u64)` — Override chain ID - `.gas_price(u64)` — Set default gas price - etc. ### Example ```rust let provider = ProviderBuilder::new() .connect_anvil_with_config(|anvil| { anvil.block_time(1).chain_id(1337) }); ``` ``` -------------------------------- ### Get Uniswap Pair Information with Alloy Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/02-helpers-library.md Fetches Uniswap V2 pair details using the `get_uniswap_pair` helper function. Prints the pair's address and reserves. ```rust use helpers::alloy::get_uniswap_pair; let pair = get_uniswap_pair(); println!("Pair address: {}", pair.address); println!("Reserve0: {}", pair.reserve0); println!("Reserve1: {}", pair.reserve1); ``` -------------------------------- ### Bytes and Address Types Source: https://github.com/alloy-rs/examples/blob/main/README.md Demonstrates the usage of `Bytes` and `Address` primitive types. ```rust use alloy::primitives::{Address, Bytes}; fn main() { // Address creation let address_str = "0x0000000000000000000000000000000000000001"; let address: Address = address_str.parse().unwrap(); println!("Address: {:?}", address); // Bytes creation let bytes_vec = vec![0x01, 0x02, 0x03]; let bytes_data: Bytes = bytes_vec.into(); println!("Bytes: {:?}", bytes_data); // Convert Address to Bytes let address_bytes: Bytes = address.into(); println!("Address as Bytes: {:?}", address_bytes); } ``` -------------------------------- ### Spawn Reth Client Source: https://github.com/alloy-rs/examples/blob/main/_autodocs/10-node-bindings.md Instantiate and spawn a Reth client using the builder pattern. Requires `alloy::node_bindings::Reth`. ```rust use alloy::node_bindings::Reth; let reth = Reth::new() .try_spawn()?; let provider = ProviderBuilder::new() .connect_http(reth.endpoint().parse()?); ```