### Basic Provider Setup in Rust Source: https://alloy.rs/llms-full.txt Sets up a basic provider for interacting with an Ethereum node. Clone the examples repository and run with `cargo run --example basic_provider`. ```rust use alloy::network::Ethereum; use alloy::providers::Provider; use alloy::transports::http::HTTP; #[tokio::main] async fn main() { let provider = Ethereum::::new("http://localhost:8545"); let chain_id = provider.get_chain_id().await.unwrap(); println!("Chain ID: {}", chain_id); } ``` -------------------------------- ### Run WebSocket Example Source: https://alloy.rs/llms-full.txt Demonstrates how to establish a WebSocket connection. Clone the examples repository and run the `ws` example. ```rust // [!include ~/snippets/providers/examples/ws.rs] ``` -------------------------------- ### Running the simulation_uni_v2 Example Source: https://alloy.rs/examples/contracts/simulation_uni_v2 Instructions on how to clone the examples repository and run the `simulation_uni_v2` example using Cargo. ```bash git clone git@github.com:alloy-rs/examples.git cd examples cargo run --example simulation_uni_v2 ``` -------------------------------- ### Create Keystore Example Source: https://alloy.rs/llms-full.txt Demonstrates the process of creating a new keystore file. Clone the examples repository and run the `create_keystore` example. ```rust // [!include ~/snippets/wallets/examples/create_keystore.rs] ``` -------------------------------- ### Run Geth Local Instance Example Source: https://alloy.rs/llms-full.txt Demonstrates how to use the `geth_local_instance` example. Clone the examples repository and run the specified cargo command. ```rust // [!include ~/snippets/node-bindings/examples/geth_local_instance.rs] ``` -------------------------------- ### Run Batch RPC Example Source: https://alloy.rs/llms-full.txt Demonstrates how to make batch RPC calls. Clone the examples repository and run the `batch_rpc` example. ```rust // [!include ~/snippets/providers/examples/batch_rpc.rs] ``` -------------------------------- ### Subscribe to Logs Example Source: https://alloy.rs/llms-full.txt This example demonstrates how to subscribe to and receive logs from the Ethereum network. Ensure you have cloned the examples repository and run the command `cargo run --example subscribe_logs`. ```rust use alloy::providers::WsConnect; use alloy::rpc::client::WsClient; use alloy::sub: use alloy::sub::eth::log::Log; use futures_util::stream::StreamExt; #[tokio::main] async fn main() -> anyhow::Result<()> { let provider = WsClient::new("ws://localhost:8545").await?; let mut stream = provider.subscribe_logs().await?; while let Some(log) = stream.next().await { println!("{log:?}"); } Ok(()) } ``` -------------------------------- ### Subscribe to All Logs Example Source: https://alloy.rs/llms-full.txt This example shows how to subscribe to all logs on the Ethereum network. Clone the examples repository and execute `cargo run --example subscribe_all_logs`. ```rust use alloy::providers::WsConnect; use alloy::rpc::client::WsClient; use alloy::sub::eth::log::Log; use futures_util::stream::StreamExt; #[tokio::main] async fn main() -> anyhow::Result<()> { let provider = WsClient::new("ws://localhost:8545").await?; let mut stream = provider.subscribe_all_logs().await?; while let Some(log) = stream.next().await { println!("{log:?}"); } Ok(()) } ``` -------------------------------- ### Trezor Signer Example Source: https://alloy.rs/llms-full.txt Demonstrates how to use the Trezor hardware wallet for signing transactions. Clone the examples repository and run the `trezor_signer` example. ```rust // [!include ~/snippets/wallets/examples/trezor_signer.rs] ``` -------------------------------- ### Run Math Utilities Example Source: https://alloy.rs/llms-full.txt This example showcases mathematical utilities. Clone the repository and run the example using Cargo. ```rust // [!include ~/snippets/big-numbers/examples/math_utilities.rs] ``` -------------------------------- ### Run Anvil Set Storage At Example Source: https://alloy.rs/llms-full.txt Demonstrates how to use the `anvil_set_storage_at` example. Clone the examples repository and run the specified cargo command. ```rust // [!include ~/snippets/node-bindings/examples/anvil_set_storage_at.rs] ``` -------------------------------- ### Rust: All Derives Example Source: https://alloy.rs/llms-full.txt This example showcases the use of all available derive macros for smart contract interfaces. It requires cloning the Alloy RS examples repository and running the specific example. ```rust // [!include ~/snippets/sol-macro/examples/all_derives.rs] ``` -------------------------------- ### Transfer ETH Example Source: https://alloy.rs/llms-full.txt Demonstrates how to transfer ETH. Clone the examples repository and run with `cargo run --example transfer_eth`. ```rust // [!include ~/snippets/transactions/examples/transfer_eth.rs] ``` -------------------------------- ### Run Reth Local Instance Example Source: https://alloy.rs/llms-full.txt Demonstrates how to use the `reth_local_instance` example. Clone the examples repository and run the specified cargo command. ```rust // [!include ~/snippets/node-bindings/examples/reth_local_instance.rs] ``` -------------------------------- ### Run Compare New Heads Example Source: https://alloy.rs/llms-full.txt This example demonstrates comparing new heads. Clone the repository and run the example using Cargo. ```rust // [!include ~/snippets/comparison/examples/compare_new_heads.rs] ``` -------------------------------- ### Run Anvil Local Provider Example Source: https://alloy.rs/llms-full.txt Demonstrates how to use the `anvil_local_provider` example. Clone the examples repository and run the specified cargo command. ```rust // [!include ~/snippets/node-bindings/examples/anvil_local_provider.rs] ``` -------------------------------- ### Logging Layer Example Source: https://alloy.rs/llms-full.txt Demonstrates the logging layer. Clone the examples repository and run `cargo run --example logging_layer` to execute. ```rust // [!include ~/snippets/layers/examples/logging_layer.rs] ``` -------------------------------- ### Decoding JSON ABI Example Source: https://alloy.rs/llms-full.txt This example shows how to decode data using a JSON ABI with Alloy RS. Follow the setup instructions to clone the repository and run the example. ```rust use alloy_json_abi::JsonAbi; use alloy_primitives::Bytes; #[tokio::main] async fn main() -> anyhow::Result<()> { let abi_json = r#"[ { "inputs": [ { "name": "_value", "type": "uint256" } ], "name": "setValue", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ]"#; let abi: JsonAbi = serde_json::from_str(abi_json)?; let function = abi.get("setValue").ok_or_else(|| "Function not found")?; let encoded_data = function.encode_input(&[alloy_primitives::B256::from(100u64).into()])?; println!("Encoded data: {:?}", Bytes::from(encoded_data)); Ok(()) } ``` -------------------------------- ### Run Recommended Fillers Example Source: https://alloy.rs/llms-full.txt Demonstrates how to use the recommended fillers. Clone the examples repository and run the `recommended_fillers` cargo command. ```rust // [!include ~/snippets/fillers/examples/recommended_fillers.rs] ``` -------------------------------- ### Trace Multiple Transactions with `trace_call_many` Source: https://alloy.rs/examples/transactions/trace_call_many This example shows how to set up a local Reth node and use `trace_call_many` to trace two distinct transactions. Ensure Reth is installed and available in your PATH. ```rust #!/usr/bin/env rust //! Example of how to trace a transaction using `trace_call_many`. use alloy:: network::TransactionBuilder, node_bindings::Reth, primitives::{address, U256}, providers::{ext::TraceApi, ProviderBuilder}, rpc::types::{trace::parity::TraceType, TransactionRequest}, ; use eyre::Result; #[tokio::main] async fn main() -> Result<()> { // Spin up a local Reth node. // Ensure `reth` is available in $PATH. let reth = Reth::new().dev().disable_discovery().instance(1).spawn(); let provider = ProviderBuilder::new().connect_http(reth.endpoint().parse()?); // Get users, these have allocated balances in the dev genesis block. let alice = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"); let bob = address!("3C44CdDdB6a900fa2b585dd299e03d12FA4293BC"); let charlie = address!("90F79bf6EB2c4f870365E785982E1f101E93b906"); let dan = address!("15d34AAf54267DB7D7c367839AAf71A00a2C6A65"); // Define transactions. let tx1 = TransactionRequest::default().with_from(alice).with_to(bob).with_value(U256::from(150)); let tx2 = TransactionRequest::default().with_from(charlie).with_to(dan).with_value(U256::from(250)); // Define the trace type for the trace call list. let trace_type: &[TraceType] = &[TraceType::Trace]; // Trace the transaction on top of the latest block. let trace_call_list = &[(tx1, trace_type), (tx2, trace_type)]; let result = provider.trace_call_many(trace_call_list).await?; // Print the trace results. for (index, trace_result) in result.iter().enumerate() { println!("Trace result for transaction {index}: {trace_result:?}"); } Ok(()) } ``` -------------------------------- ### Connect to Ethereum Network with ProviderBuilder Source: https://alloy.rs/llms-full.txt Instantiates an Ethereum provider by automatically detecting the connection type (HTTP, WS, or IPC) from the provided URL. This example uses the `connect` method for asynchronous setup. ```rust use alloy::providers::{Provider, ProviderBuilder}; use std::error::Error; const RPC_URL: &str = "https://ethereum.reth.rs/rpc"; #[tokio::main] async fn main() -> Result<(), Box> { // Instanties a provider using a string. let provider = ProviderBuilder::new().connect(RPC_URL).await?; Ok(()) } ``` -------------------------------- ### Run Wallet Filler Example Source: https://alloy.rs/llms-full.txt Shows how to use the wallet filler. Clone the examples repository and run the `wallet_filler` cargo command. ```rust // [!include ~/snippets/fillers/examples/wallet_filler.rs] ``` -------------------------------- ### Gas Filler Example Source: https://alloy.rs/llms-full.txt Demonstrates a gas filler for transaction management. This example requires cloning the examples repository and running with `cargo run --example gas_filler`. ```rust use alloy::network::Ethereum; use alloy::providers::RootProvider; use alloy::transports::http::HTTP; use alloy_primitives::U256; use alloy_signer::Signer; use alloy_signer_local::LocalAccount; use std::sync::Arc; mod filler; #[tokio::main] async fn main() -> anyhow::Result<()> { let provider = RootProvider::>::new("http://localhost:8545"); let signer = LocalAccount::new( "0xac0974bec39a17e36ba4a6b4d238ab64da56806277472f717717011111111111".parse()?, Address::ZERO, // This is a dummy address, it will be overwritten by the provider. U256::MAX, ); let filler = filler::GasFiller::new(provider.clone(), Arc::new(signer)); let gas_price = filler.fill_gas_price().await?; println!("Gas price: {}", gas_price); Ok(()) } ``` -------------------------------- ### Run HTTP Example Source: https://alloy.rs/llms-full.txt Demonstrates how to run the `http` example. Clone the repository and execute the cargo command. ```rust // [!include ~/snippets/providers/examples/http.rs] ``` -------------------------------- ### Rust: Poll Logs Example Source: https://alloy.rs/llms-full.txt This example demonstrates how to poll for logs from the blockchain using Alloy RS. Clone the examples repository and run the 'poll_logs' example to use this functionality. ```rust // [!include ~/snippets/subscriptions/examples/poll_logs.rs] ``` -------------------------------- ### Run IPC Example Source: https://alloy.rs/llms-full.txt Demonstrates how to run the `ipc` example. Clone the repository and execute the cargo command. ```rust // [!include ~/snippets/providers/examples/ipc.rs] ``` -------------------------------- ### Rust: Subscribe to Blocks Example Source: https://alloy.rs/llms-full.txt This example shows how to subscribe to new block events using Alloy RS. Ensure you have cloned the examples repository and run the 'subscribe_blocks' example. ```rust // [!include ~/snippets/subscriptions/examples/subscribe_blocks.rs] ``` -------------------------------- ### Run Mocking Example Source: https://alloy.rs/llms-full.txt Demonstrates how to run the `mocking` example. Clone the repository and execute the cargo command. ```rust // [!include ~/snippets/providers/examples/mocking.rs] ``` -------------------------------- ### Running Any Network Example Source: https://alloy.rs/llms-full.txt This example demonstrates how to interact with any network using Alloy RS. Ensure you have cloned the Alloy RS examples repository and are running the command as specified. ```rust use alloy_provider::Provider; use alloy_rpc_client::Client use alloy_rpc_client::ClientBuilder; use alloy_network::Network; use alloy_network::AnyNetwork; #[tokio::main] async fn main() -> anyhow::Result<()> { let rpc_url = "http://localhost:8545".parse()?; let client = ClientBuilder::on_http(rpc_url).into_rpc(); let provider = AnyNetwork::new(client); let block_number = provider.get_block_number().await?; println!("Current block number: {}", block_number); Ok(()) } ``` -------------------------------- ### Run HTTP with Authentication Example Source: https://alloy.rs/llms-full.txt Demonstrates how to run the `http_with_auth` example. Clone the repository and execute the cargo command. ```rust // [!include ~/snippets/providers/examples/http_with_auth.rs] ``` -------------------------------- ### Event Multiplexer Example Source: https://alloy.rs/llms-full.txt This example showcases the event multiplexer functionality, allowing for the handling of multiple subscription events. Clone the examples repository and run `cargo run --example event_multiplexer`. ```rust use alloy::providers::WsConnect; use alloy::rpc::client::WsClient; use alloy::sub::eth::log::Log; use alloy::sub::eth::transaction::PendingTransaction; use futures_util::stream::StreamExt; #[tokio::main] async fn main() -> anyhow::Result<()> { let provider = WsClient::new("ws://localhost:8545").await?; let mut logs = provider.subscribe_logs().await?; let mut pending_txs = provider.subscribe_pending_transactions().await?; loop { tokio::select! { Some(log) = logs.next() => { println!("Log: {log:?}"); } Some(tx) = pending_txs.next() => { println!("Pending Tx: {tx:?}"); } else => break, } } Ok(()) } ``` -------------------------------- ### Subscribe to Pending Transactions Example Source: https://alloy.rs/llms-full.txt This example demonstrates subscribing to pending transactions on the Ethereum network. To run, clone the examples repository and use the command `cargo run --example subscribe_pending_transactions`. ```rust use alloy::providers::WsConnect; use alloy::rpc::client::WsClient; use alloy::sub::eth::transaction::PendingTransaction; use futures_util::stream::StreamExt; #[tokio::main] async fn main() -> anyhow::Result<()> { let provider = WsClient::new("ws://localhost:8545").await?; let mut stream = provider.subscribe_pending_transactions().await?; while let Some(tx) = stream.next().await { println!("{tx:?}"); } Ok(()) } ``` -------------------------------- ### Basic Provider Setup Comparison Source: https://alloy.rs/llms-full.txt Compares setting up an HTTP provider for fetching block numbers in ethers-rs and Alloy. ```rust // ethers-rs (OLD) use ethers::{ providers::{Provider, Http, Middleware}, types::Address, }; #[tokio::main] async fn main() -> Result<(), Box> { let provider = Provider::::try_from("https://eth.llamarpc.com")?; let block_number = provider.get_block_number().await?; println!("Latest block: {}", block_number); Ok(()) } ``` ```rust // Alloy (NEW) use alloy::{ providers::{Provider, ProviderBuilder}, primitives::Address, }; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = ProviderBuilder::new() .connect_http("https://eth.llamarpc.com".parse()?); let block_number = provider.get_block_number().await?; println!("Latest block: {}", block_number); Ok(()) } ``` -------------------------------- ### Rust: Extra Derives Example Source: https://alloy.rs/llms-full.txt This example demonstrates the usage of extra derive macros for smart contract interfaces. To run, clone the Alloy RS examples repository and execute the 'extra_derives' example. ```rust // [!include ~/snippets/sol-macro/examples/extra_derives.rs] ``` -------------------------------- ### Run Multicall Example Source: https://alloy.rs/llms-full.txt Demonstrates multicall functionality. Clone the examples repository and run the `multicall` example using Cargo. ```rust // [!include ~/snippets/providers/examples/multicall.rs] ``` -------------------------------- ### GCP Signer Example Source: https://alloy.rs/llms-full.txt Demonstrates how to use the GCP signer. Ensure you have cloned the examples repository and have the necessary GCP authentication configured. ```rust use alloy::signers::google::GcpSigner; use alloy::primitives::address; use alloy::signers::Signer; #[tokio::main] async fn main() { let signer = GcpSigner::new("0x0000000000000000000000000000000000000000").await.unwrap(); let address = signer.address().await.unwrap(); println!("GCP Signer Address: {:?}", address); } ``` -------------------------------- ### Deploy and Link Library Source: https://alloy.rs/llms-full.txt This example demonstrates how to deploy a contract that has library dependencies and link them during the deployment process. Ensure the library contracts are deployed first or available. ```rust use alloy::contracts::impls::erc20::generated::MyToken; use alloy::primitives::address; use alloy::rpc::client::Client; use alloy_provider::Provider; use alloy_signer::local_ வழிகள்::private_key::PrivateKey; #[tokio::main] async fn main() -> anyhow::Result<()> { let provider = Provider::try_from_url("http://localhost:8545")?; let signer = PrivateKey::from_hex("0x0000000000000000000000000000000000000000000000000000000000000001")?; let provider = provider.with_signer(signer); let library_address = address!("0x0000000000000000000000000000000000000000"); let token = MyToken::deploy(&provider) .with_library("MyLibrary", library_address) .await?; println!("Token deployed to: {:?}", token.address()); Ok(()) } ``` -------------------------------- ### Run Math Operations Example Source: https://alloy.rs/llms-full.txt This example demonstrates mathematical operations. Clone the repository and run the example using Cargo. ```rust // [!include ~/snippets/big-numbers/examples/math_operations.rs] ``` -------------------------------- ### Provider with Recommended Fillers Source: https://alloy.rs/guides/fillers Demonstrates how using `RecommendedFillers` significantly simplifies transaction building by automatically handling essential properties like nonce, chain ID, and gas fees. ```rust #[tokio::main] async fn main() -> Result<()> { let provider = ProviderBuilder::new().connect_anvil_with_wallet(); let bob = Address::from([0x42; 20]); let tx = TransactionRequest::default() .with_to(bob) .with_value(U256::from(1)); let bob_balance_before = provider.get_balance(bob).await?; _ = provider.send_transaction(tx).await?.get_receipt().await?; let bob_balance_after = provider.get_balance(bob).await?; println!( "Balance before: {} Balance after: {}", bob_balance_before, bob_balance_after ); Ok(()) } ``` -------------------------------- ### Private Key Signer Example Source: https://alloy.rs/llms-full.txt Shows how to use a private key signer. This is suitable for testing or environments where direct private key management is feasible. ```rust use alloy::signers::private_key::PrivateKeySigner; use alloy::primitives::address; use alloy::signers::Signer; use ethers_core::types::Bytes; #[tokio::main] async fn main() { let private_key = "0x0000000000000000000000000000000000000000000000000000000000000001"; let signer = PrivateKeySigner::from_hex(private_key).unwrap(); let address = signer.address().await.unwrap(); println!("Private Key Signer Address: {:?}", address); } ``` -------------------------------- ### Run Multicall Batching Example Source: https://alloy.rs/llms-full.txt Illustrates multicall batching. Clone the examples repository and run the `multicall_batching` example using Cargo. ```rust // [!include ~/snippets/providers/examples/multicall_batching.rs] ``` -------------------------------- ### Initialize HTTP Provider with connect_http Source: https://alloy.rs/rpc-providers/http-provider Demonstrates how to create an HTTP provider using the `connect_http` method on `ProviderBuilder`. This is the recommended approach for setting up an HTTP connection to a node. ```rust //! Example of creating an HTTP provider using the `connect_http` method on the `ProviderBuilder`. use alloy::providers::{Provider, ProviderBuilder}; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { // Set up the HTTP transport which is consumed by the RPC client. let rpc_url = "https://ethereum.reth.rs/rpc".parse()?; // Create a provider with the HTTP transport using the `reqwest` crate. let provider = ProviderBuilder::new().connect_http(rpc_url); Ok(()) } ``` -------------------------------- ### Deploy Contract from Bytecode Source: https://alloy.rs/llms-full.txt This example demonstrates deploying a contract using its raw bytecode. This method is useful when the contract artifact is not readily available but the bytecode is known. ```rust use alloy::primitives::address; use alloy::rpc::client::Client; use alloy_provider::Provider; use alloy_signer::local_ வழிகள்::private_key::PrivateKey; #[tokio::main] async fn main() -> anyhow::Result<()> { let provider = Provider::try_from_url("http://localhost:8545")?; let signer = PrivateKey::from_hex("0x0000000000000000000000000000000000000000000000000000000000000001")?; let provider = provider.with_signer(signer); let bytecode = hex::decode("60806040523480this...")?; let contract_address = address!("0x0000000000000000000000000000000000000000"); let contract = provider.deploy(bytecode, contract_address).await?; println!("Contract deployed to: {:?}", contract); Ok(()) } ``` -------------------------------- ### Run Embedded Consensus RPC Example Source: https://alloy.rs/llms-full.txt Illustrates how to use an embedded consensus RPC. Clone the examples repository and run the `embed_consensus_rpc` example. ```rust // [!include ~/snippets/providers/examples/embed_consensus_rpc.rs] ```