### Install Dependencies with Yarn Source: https://github.com/gakonst/ethers-rs/blob/master/examples/wasm/README.md Installs project dependencies using the Yarn package manager. This step is necessary to set up the development environment before building or running the example. ```shell yarn install ``` -------------------------------- ### Build and Serve Example Source: https://github.com/gakonst/ethers-rs/blob/master/examples/wasm/README.md Builds the ethers-wasm example project and starts a local web server to serve the application, making it accessible in a browser for testing. ```shell yarn serve ``` -------------------------------- ### Start Local Anvil Instance Source: https://github.com/gakonst/ethers-rs/blob/master/examples/wasm/README.md Starts a local Anvil instance, a fast Ethereum development node, for testing the application against a local blockchain environment. ```shell yarn anvil ``` -------------------------------- ### Start Local Ganache Instance Source: https://github.com/gakonst/ethers-rs/blob/master/examples/wasm/README.md Starts a local Ganache instance, an alternative Ethereum development blockchain, which can be used instead of Anvil for local testing. ```shell yarn ganache ``` -------------------------------- ### Run ethers-rs Example from Command Line Source: https://github.com/gakonst/ethers-rs/blob/master/README.md Execute a specific example from the ethers-rs examples directory using the cargo run command. Specify the example crate name and the example file name. ```bash # cargo run -p --example cargo run -p examples-big-numbers --example math_operations ``` -------------------------------- ### Example: Instantiating and Using ethers-rs Provider Source: https://github.com/gakonst/ethers-rs/blob/master/CONTRIBUTING.md Provides a Rust documentation test example demonstrating how to create an HTTP provider instance using `ethers_providers` and fetch a block, suitable for API documentation. ```Rust /// ```no_run /// # async fn foo() -> Result<(), Box> { /// use ethers_providers::{Middleware, Provider, Http}; /// /// let provider = Provider::::try_from( /// "https://eth.llamarpc.com" /// ).expect("could not instantiate HTTP Provider"); /// /// let block = provider.get_block(100u64).await?; /// println!("Got block: {}", serde_json::to_string(&block)?); /// # Ok(()) /// # } /// ``` ``` -------------------------------- ### Creating a new Rust project with Cargo (bash) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Uses the Cargo package manager to initialize a new Rust project directory structure. This is the standard way to start a Rust application or library. ```bash cargo new my-project ``` -------------------------------- ### Initializing IPC Provider in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/ipc.md Demonstrates how to create a new IPC provider instance using `Provider::connect_ipc`. Includes examples for connecting via a Unix domain socket on Unix systems and a Windows named pipe on Windows systems using conditional compilation. Requires the `ethers::providers::Provider` and a Tokio runtime. ```Rust use ethers::providers::Provider;\n\n#[tokio::main]\nasync fn main() -> eyre::Result<()> {\n // Using a UNIX domain socket: `/path/to/ipc`\n #[cfg(unix)]\n let provider = Provider::connect_ipc("~/.ethereum/geth.ipc").await?;\n\n // Using a Windows named pipe: `\\\\.\\pipe\\geth`\n #[cfg(windows)]\n let provider = Provider::connect_ipc(r"\\\\.\\pipe\\geth").await?;\n\n Ok(())\n} ``` -------------------------------- ### Including Log and Filtering Examples (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/events/logs-and-filtering.md This snippet shows how to embed external Rust code examples for event filtering and subscription into a documentation file using specific include directives. It references files expected to contain the actual Rust implementation. ```rust {{#include ../../examples/events/examples/filtering.rs}}\n{{#include ../../examples/events/examples/subscribe.rs}} ``` -------------------------------- ### Initializing Ws Provider with Authorization (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/ws.md This example shows how to connect to a WebSocket endpoint that requires basic authorization. It utilizes the `Provider::::connect_with_auth` method along with an `Authorization::basic` object containing the username and password. ```Rust use ethers::providers::{Authorization, Provider, Ws}; #[tokio::main] async fn main() -> eyre::Result<()> { let url = "wss://..."; let auth = Authorization::basic("username", "password"); let provider = Provider::::connect_with_auth(url, auth).await?; Ok(()) } ``` -------------------------------- ### Connecting to Ethereum Node and Getting Block Number (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/connect_to_an_ethereum_node.md This snippet demonstrates how to establish a connection to an Ethereum node using an HTTP provider from the ethers-rs library and retrieve the current block number. It uses `tokio` for asynchronous execution and handles potential errors. It requires the `ethers` and `tokio` crates. ```Rust // The `prelude` module provides a convenient way to import a number // of common dependencies at once. This can be useful if you are working // with multiple parts of the library and want to avoid having // to import each dependency individually. use ethers::prelude::*; const RPC_URL: &str = "https://eth.llamarpc.com"; #[tokio::main] async fn main() -> Result<(), Box> { let provider = Provider::::try_from(RPC_URL)?; let block_number: U64 = provider.get_block_number().await?; println!("{block_number}"); Ok(()) } ``` -------------------------------- ### Adding ethers-rs from Git repository (Cargo.toml) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Configures the `Cargo.toml` file to include `ethers` directly from its GitHub repository. This fetches the latest code from the default branch (usually master/main). ```toml [dependencies] ethers = { git = "https://github.com/gakonst/ethers-rs" } ``` -------------------------------- ### Getting WETH Address on Mainnet (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-addressbook/README.md This snippet demonstrates how to use the `ethers-addressbook` library to retrieve the address of a known contract, specifically WETH, for a particular blockchain network, Mainnet. It imports the `contract` function and `Chain` enum, fetches the WETH contract object, gets its address for Mainnet, and verifies it against the expected address. ```Rust use ethers_addressbook::{contract, Chain}; let weth = contract("weth").unwrap(); let mainnet_address = weth.address(Chain::Mainnet).unwrap(); assert_eq!(mainnet_address, "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2".parse().unwrap()); ``` -------------------------------- ### Adding ethers-rs and core dependencies (Cargo.toml) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Configures the `Cargo.toml` file to include `ethers` at a specific version, `tokio` for async runtime with macros, and `eyre` for error reporting. These are common dependencies for ethers-rs projects. ```toml [dependencies] ethers = "2.0" # Ethers' async features rely upon the Tokio async runtime. tokio = { version = "1", features = ["macros"] } # Flexible concrete Error Reporting type built on std::error::Error with customizable Reports eyre = "0.6" ``` -------------------------------- ### Serve ethers-rs book locally with mdbook Source: https://github.com/gakonst/ethers-rs/blob/master/book/README.md This command uses the mdbook tool to serve the book locally, typically for live preview during development. ```Shell mdbook serve ``` -------------------------------- ### Initialize HTTP Provider and Query Data in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-providers/README.md Demonstrates how to create an HTTP provider instance using ethers-providers and fetch basic blockchain data like a block by number and contract code by address. ```Rust # use ethers_core::types::Address; # use ethers_providers::{Provider, Http, Middleware, Ws}; # async fn foo() -> Result<(), Box> { let provider = Provider::::try_from("https://eth.llamarpc.com")?; let block = provider.get_block(100u64).await?; println!("Got block: {}", serde_json::to_string(&block)?); let addr = "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359".parse::
()?; let code = provider.get_code(addr, None).await?; println!("Got code: {}", serde_json::to_string(&code)?); # Ok(()) # } ``` -------------------------------- ### Initialize Http Provider using TryFrom (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/http.md This snippet demonstrates initializing an `Http` provider using the `Provider::try_from` method with a URL string. This is one of the simplest ways to create a new provider instance. ```Rust use ethers::providers::{Http, Middleware, Provider}; #[tokio::main] async fn main() -> eyre::Result<()> { // Initialize a new Http provider let rpc_url = "https://eth.llamarpc.com"; let provider = Provider::try_from(rpc_url)?; Ok(()) } ``` -------------------------------- ### Adding ethers-rs from a specific Git commit/tag (Cargo.toml) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Configures the `Cargo.toml` file to include `ethers` from a specific commit hash or tag using the `rev` attribute. Provides more stability than using a branch but less than a version. ```toml [dependencies] ethers = { git = "https://github.com/gakonst/ethers-rs", rev = "84dda78" } ``` -------------------------------- ### Adding ethers-rs from a specific Git branch (Cargo.toml) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Configures the `Cargo.toml` file to include `ethers` from a specific branch of its GitHub repository using the `branch` attribute. Useful for testing features on development branches. ```toml [dependencies] ethers = { git = "https://github.com/gakonst/ethers-rs", branch = "branch-name" } ``` -------------------------------- ### Serve ethers-rs book with Docker Source: https://github.com/gakonst/ethers-rs/blob/master/book/README.md This command runs mdbook serve inside a Docker container, mapping port 3000 and mounting the current directory as the book source. ```Shell docker run -p 3000:3000 -v `pwd`:/book peaceiris/mdbook serve ``` -------------------------------- ### Initializing Ws Provider (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/ws.md This snippet demonstrates the most straightforward way to establish a connection to a WebSocket endpoint using the ethers-rs Ws provider. It uses the `Provider::::connect` method and requires a valid WebSocket URL. ```Rust use ethers::providers::{Provider, Ws}; #[tokio::main] async fn main() -> eyre::Result<()> { let provider = Provider::::connect("wss://...").await?; Ok(()) } ``` -------------------------------- ### Interacting with Smart Contracts using ethers-rs (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/http.md Illustrates how to use `ethers-rs` to interact with a deployed smart contract. It shows how to use the `abigen!` macro to generate bindings, instantiate a contract instance with an address and provider, and call a view function (`getReserves`) to fetch data. Requires the `ethers` crate and `tokio`. Notes the use of `Arc` for the provider. ```Rust use ethers::{ prelude::abigen, providers::{Http, Provider}, types::Address, }; use std::sync::Arc; abigen!( IUniswapV2Pair, "[function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)]" ); #[tokio::main] async fn main() -> eyre::Result<()> { let rpc_url = "https://eth.llamarpc.com"; let provider = Arc::new(Provider::try_from(rpc_url)?); // Initialize a new instance of the Weth/Dai Uniswap V2 pair contract let pair_address: Address = "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".parse()?; let uniswap_v2_pair = IUniswapV2Pair::new(pair_address, provider); // Use the get_reserves() function to fetch the pool reserves let (reserve_0, reserve_1, block_timestamp_last) = uniswap_v2_pair.get_reserves().call().await?; Ok(()) } ``` -------------------------------- ### Enabling ipc feature for IPC transport (Cargo.toml) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Adds the `ipc` feature flag to the `ethers` dependency in `Cargo.toml`. This enables support for communicating with a local Ethereum node using the Interprocess Communication protocol. ```toml [dependencies] ethers = { version = "2.0", features = ["ipc"] } ``` -------------------------------- ### Initializing Provider and Subscribing to Logs (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/subscriptions/logs.md Demonstrates how to initialize an ethers-rs Provider using HTTP, create a log Filter specifying criteria like the contract address, and subscribe to the log stream using `provider.subscribe_logs`. Requires a running Ethereum node accessible via HTTP. ```Rust async fn main() -> Result<(), Box> { let provider = Provider::::try_from("http://localhost:8545")?; let filter = Filter::new().address("0xcontract_address_here".parse()?); let mut stream = provider.subscribe_logs(filter).await?; // Your code to handle logs goes here. Ok(()) } ``` -------------------------------- ### Initializing Etherscan Client and Querying Contract Source Code (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-etherscan/README.md This snippet demonstrates how to initialize the `ethers-etherscan` client using either an API key or environment variables and then query the source code for a specific contract address. It requires the `ethers_core::types::Chain` and `ethers_etherscan::Client` dependencies. ```rust # use ethers_core::types::Chain; # use ethers_etherscan::Client; # async fn foo() -> Result<(), Box> { let client = Client::new(Chain::Mainnet, "")?; // Or using environment variables let client = Client::new_from_env(Chain::Mainnet)?; let address = "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413".parse()?; let metadata = client.contract_source_code(address).await?; assert_eq!(metadata.items[0].contract_name, "DAO"); # Ok(()) # } ``` -------------------------------- ### Enabling ws feature for WebSocket transport (Cargo.toml) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Adds the `ws` feature flag to the `ethers` dependency in `Cargo.toml`. This enables support for connecting to Ethereum nodes over the WebSocket protocol for real-time communication. ```toml [dependencies] ethers = { version = "2.0", features = ["ws"] } ``` -------------------------------- ### Enabling rustls feature for HTTPS transport (Cargo.toml) Source: https://github.com/gakonst/ethers-rs/blob/master/book/getting-started/start_a_new_project.md Adds the `rustls` feature flag to the `ethers` dependency in `Cargo.toml`. This enables support for connecting to Ethereum nodes over HTTPS using the rustls TLS library. ```toml [dependencies] ethers = { version = "2.0", features = ["rustls"] } ``` -------------------------------- ### Generate Rust Contract Bindings from ABI File (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/examples/contracts/README.md Demonstrates how to use the `Abigen` builder to load a contract's ABI from a file, generate Rust bindings, and write them to a specified output file. This method is commonly used in build scripts (`build.rs`). ```Rust Abigen::new("ERC20Token", "./abi.json")?.generate()?.write_to_file("token.rs")?; ``` -------------------------------- ### Running Common Cargo Commands Source: https://github.com/gakonst/ethers-rs/blob/master/CONTRIBUTING.md Lists essential `cargo` commands used for checking, formatting, building, testing, and linting the ethers-rs project with all features enabled. ```Shell cargo check --all-features cargo +nightly fmt --all cargo build --all-features cargo test --all-features cargo +nightly clippy --all-features ``` -------------------------------- ### Execute Release Script (Shell) Source: https://github.com/gakonst/ethers-rs/blob/master/CONTRIBUTING.md Runs the main release script located at `bin/release` with the `--execute` flag. This script orchestrates the full release process, including updating crate versions, creating Git tags, generating the CHANGELOG, and publishing to crates.io. ```Shell bin/release --execute ``` -------------------------------- ### Initialize Http Provider with Custom reqwest Client (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/http.md This snippet illustrates initializing an `Http` provider using a pre-configured `reqwest::Client` instance via the `Http::new_with_client` function. This allows for custom client configurations like timeouts or proxy settings. ```Rust use ethers::providers::Http; use url::Url; #[tokio::main] async fn main() -> eyre::Result<()> { let url = Url::parse("http://localhost:8545")?; let client = reqwest::Client::builder().build()?; let provider = Http::new_with_client(url, client); Ok(()) } ``` -------------------------------- ### Initialize Http Provider with Basic Authentication (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/http.md This snippet shows how to initialize an `Http` provider with basic authentication credentials using the `Http::new_with_auth` function. It requires a `url::Url` and an `ethers::providers::Authorization` object. ```Rust use ethers::providers::{Authorization, Http}; use url::Url; #[tokio::main] async fn main() -> eyre::Result<()> { // Initialize a new HTTP Client with authentication let url = Url::parse("http://localhost:8545")?; let provider = Http::new_with_auth(url, Authorization::basic("admin", "good_password")); Ok(()) } ``` -------------------------------- ### Initializing Block Subscription with ethers-rs (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/subscriptions/watch-blocks.md This snippet shows how to set up an HTTP provider and subscribe to new block notifications using the `ethers-rs` library. It creates a stream that will yield new block data as it becomes available on the blockchain. ```Rust async fn main() -> Result<(), Box> { let provider = Provider::::try_from("http://localhost:8545")?; let mut stream = provider.subscribe_blocks().await?; // Your code to handle new blocks goes here. Ok(()) } ``` -------------------------------- ### Instantiate Contract and Event (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/events/events.md Demonstrates how to instantiate an ethers-rs `Contract` object from a provider, address, and ABI, and then create an `Event` watcher specifically for the `ValueChanged` event defined by the Rust struct. ```Rust async fn main() -> Result<(), Box> { let provider = Provider::::try_from("http://localhost:8545")?; let contract_address = "0xcontract_address_here".parse()?; let contract = Contract::from_json(provider, contract_address, include_bytes!("../contracts/abis/SimpleStorage.json"))?; let event = contract.event::()?; // Your code to handle the event goes here. Ok(()) } ``` -------------------------------- ### Format Rust Code with cargo fmt Source: https://github.com/gakonst/ethers-rs/blob/master/README.md Formats the Rust code in the project according to standard style guidelines using the `cargo fmt` tool with the nightly toolchain. ```Shell cargo +nightly fmt ``` -------------------------------- ### Signing Transaction and Message with LocalWallet in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-signers/README.md Demonstrates how to instantiate a `LocalWallet` from a private key, create a `TransactionRequest`, sign the transaction, and sign a generic message. It also includes verification of the signed message. ```Rust # use ethers_signers::{LocalWallet, Signer}; # use ethers_core::{k256::ecdsa::SigningKey, types::TransactionRequest}; # async fn foo() -> Result<(), Box> { // instantiate the wallet let wallet = "dcf2cbdd171a21c480aa7f53d77f31bb102282b3ff099c78e3118b37348c72f7" .parse::()?; // create a transaction let tx = TransactionRequest::new() .to("vitalik.eth") // this will use ENS .value(10000).into(); // sign it let signature = wallet.sign_transaction(&tx).await?; // can also sign a message let signature = wallet.sign_message("hello world").await?; signature.verify("hello world", wallet.address()).unwrap(); # Ok(()) # } ``` -------------------------------- ### Generate Inline Rust Contract Bindings from Solidity Interface (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/examples/contracts/README.md Shows how to use the `abigen!` macro to generate contract bindings directly within your Rust code by providing the contract's Solidity interface definition as a raw string literal. Useful for quick prototyping. ```Rust abigen!( ERC20Token, r#"[ function approve(address spender, uint256 amount) external returns (bool) event Transfer(address indexed from, address indexed to, uint256 value) event Approval(address indexed owner, address indexed spender, uint256 value) ]"#, ); ``` -------------------------------- ### Build Middleware Stack using Builder Methods (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-middleware/README.md Demonstrates building a middleware stack by chaining helper methods provided by the MiddlewareBuilder trait on a Provider. This is a convenient way to add common middleware layers like Gas Oracle, Signer, and Nonce Manager. The layering happens in a wrapping fashion, with the last method call representing the outermost layer. ```Rust # use ethers_providers::{Middleware, Provider, Http}; # use ethers_signers::{LocalWallet, Signer}; # use ethers_middleware::{gas_oracle::GasNow, MiddlewareBuilder}; let key = "fdb33e2105f08abe41a8ee3b758726a31abdd57b7a443f470f23efce853af169"; let signer = key.parse::()?; let address = signer.address(); let gas_oracle = GasNow::new(); let provider = Provider::::try_from("http://localhost:8545")? .gas_oracle(gas_oracle) .with_signer(signer) .nonce_manager(address); // Outermost layer # Ok::<_, Box>(()) ``` -------------------------------- ### Generate Inline Rust Contract Bindings from ABI File (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/examples/contracts/README.md Provides an alternative usage of the `abigen!` macro to generate inline contract bindings by referencing an external ABI file path instead of embedding the interface definition directly. ```Rust abigen!(ERC20Token, "./abi.json",); ``` -------------------------------- ### Import futures Stream Utilities (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/subscriptions/multiple-subscriptions.md Imports necessary traits and functions from the `futures` crate for working with streams, including `stream` for stream combinators, `StreamExt` for stream methods, and `TryStreamExt` for error handling on streams. ```Rust use futures::{stream, StreamExt, TryStreamExt}; ``` -------------------------------- ### Configure and Compile Project in build.rs (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-solc/README.md This Rust code demonstrates how to configure an `ethers_solc::Project` in a `build.rs` file, compile the Solidity contracts defined in the project paths, and instruct Cargo to rerun the build script if any source files change. It requires the `ethers_solc` crate as a build dependency. ```rust use ethers_solc::{Project, ProjectPathsConfig}; fn main() { // configure the project with all its paths, solc, cache etc. let project = Project::builder() .paths(ProjectPathsConfig::hardhat(env!("CARGO_MANIFEST_DIR")).unwrap()) .build() .unwrap(); let output = project.compile().unwrap(); // Tell Cargo that if a source file changes, to rerun this build script. project.rerun_if_sources_changed(); } ``` -------------------------------- ### Subscribe to New Block Headers (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/subscriptions/events-by-type.md This snippet shows how to connect to an Ethereum node via WebSocket and subscribe to a stream of new block headers using the ethers-rs library. It demonstrates setting up a provider, creating a subscription stream, and processing incoming events asynchronously. ```Rust use ethers::{ prelude::*, providers::{Provider, Ws}, }; use std::sync::Arc; use tokio; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to the Anvil node or any WebSocket endpoint let provider = Provider::::connect("ws://localhost:8545").await?; let client = Arc::new(provider); println!("Subscribing to NewBlockHeaders..."); // Subscribe to new block headers let mut stream = client.subscribe_blocks().await?; println!("Waiting for blocks..."); // Process incoming blocks as they arrive while let Some(block) = stream.next().await { println!("New block received: {:?}", block.number); } Ok(()) } ``` -------------------------------- ### Add futures Dependency (TOML) Source: https://github.com/gakonst/ethers-rs/blob/master/book/subscriptions/multiple-subscriptions.md Adds the `futures` crate as a dependency in the `Cargo.toml` file, required for stream manipulation capabilities. ```TOML [dependencies] futures = "0.3" ``` -------------------------------- ### Creating U256 in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/book/big-numbers/intro.md Demonstrates various ways to create U256 instances from integer literals, hexadecimal strings, and decimal strings using the ethers-rs library. ```Rust use ethers::types::U256; fn main() { let num1 = U256::from(100); let num2 = U256::from("0xff"); // Hex string let num3 = "12345".parse::().unwrap(); // From string println!("num1: {}, num2: {}, num3: {}", num1, num2, num3); } ``` -------------------------------- ### Import ethers-rs Prelude in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/README.md Import common types and traits from the ethers-rs library using the prelude module. This provides convenient access to frequently used items. ```rust use ethers::prelude::*; ``` -------------------------------- ### Querying Blockchain Data with ethers-rs Provider (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/http.md Demonstrates how to use the `Provider` struct with an HTTP connection to fetch basic blockchain information like chain ID, current block number, and transaction pool content. Requires the `ethers` crate and `tokio` for async execution. ```Rust use ethers::providers::{Http, Middleware, Provider}; #[tokio::main] async fn main() -> eyre::Result<()> { let rpc_url = "https://eth.llamarpc.com"; let provider = Provider::try_from(rpc_url)?; let chain_id = provider.get_chainid().await?; let block_number = provider.get_block_number().await?; let tx_pool_content = provider.txpool_content().await?; Ok(()) } ``` -------------------------------- ### Initialize HTTP Provider in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-middleware/README.md Initializes a basic HTTP provider instance using `ethers-rs` to connect to an Ethereum node running on localhost. This is the base layer for the middleware stack. ```Rust // Start the stack let provider = Provider::::try_from("http://localhost:8545")?; ``` -------------------------------- ### Build Middleware Stack using wrap_into (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-middleware/README.md Shows how to explicitly wrap middleware layers using the wrap_into function. This method is useful for adding middleware not directly supported by the builder's helper methods or for more granular control over the layering process. Each wrap_into call adds a new layer on top of the existing stack. ```Rust # use ethers_providers::{Middleware, Provider, Http}; # use std::convert::TryFrom; # use ethers_signers::{LocalWallet, Signer}; # use ethers_middleware::{*,gas_escalator::*,gas_oracle::*}; let key = "fdb33e2105f08abe41a8ee3b758726a31abdd57b7a443f470f23efce853af169"; let signer = key.parse::()?; let address = signer.address(); let escalator = GeometricGasPrice::new(1.125, 60_u64, None::); let provider = Provider::::try_from("http://localhost:8545")? .wrap_into(|p| GasEscalatorMiddleware::new(p, escalator, Frequency::PerBlock)) .wrap_into(|p| SignerMiddleware::new(p, signer)) .wrap_into(|p| GasOracleMiddleware::new(p, GasNow::new())) .wrap_into(|p| NonceManagerMiddleware::new(p, address)); // Outermost layer # Ok::<_, Box>(()) ``` -------------------------------- ### Process Event Stream (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/events/events.md Illustrates how to iterate over the `SubscriptionStream` using `stream.next().await` to process incoming events, handling both successful event logs and potential errors. ```Rust while let Some(event) = stream.next().await { match event { Ok(log) => {println!("New event: {:?}", log)}, Err(e) => {println!("Error: {:?}", e)}, ``` -------------------------------- ### Lint Rust Code with cargo clippy Source: https://github.com/gakonst/ethers-rs/blob/master/README.md Runs the Clippy linter on the Rust code to identify potential issues, common mistakes, and code smells. ```Shell cargo clippy ``` -------------------------------- ### Basic eth_call with ethers-rs CallBuilder (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/providers/advanced_usage.md Demonstrates the basic usage of `provider.call_raw()` which returns a `CallBuilder`. This is functionally equivalent to `provider.call()` when no additional methods are chained. It initializes a provider, creates a simple transaction request, and executes the call. ```Rust use ethers::{ providers::{Http, Provider}, types::{TransactionRequest, H160}, utils::parse_ether, }; use std::sync::Arc; #[tokio::main] async fn main() -> eyre::Result<()> { let rpc_url = "https://eth.llamarpc.com"; let provider: Arc> = Arc::new(Provider::::try_from(rpc_url)?); let from_adr: H160 = "0x6fC21092DA55B392b045eD78F4732bff3C580e2c".parse()?; let to_adr: H160 = "0x000000000000000000000000000000000000dead".parse()?; let val = parse_ether(1u64)?; let tx = TransactionRequest::default() .from(from_adr) .to(to_adr) .value(val) .into(); let result = provider.call_raw(&tx).await?; Ok(()) } ``` -------------------------------- ### Perform ENS Resolution and Lookup in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-providers/README.md Shows how to use an ethers-providers instance to interact with the Ethereum Name Service (ENS), including resolving names to addresses, looking up addresses to names, and resolving specific ENS fields like URL and avatar. ```Rust # use ethers_providers::{Provider, Http, Middleware}; # async fn foo() -> Result<(), Box> { let provider = Provider::::try_from("https://eth.llamarpc.com")?; // Resolve ENS name to Address let name = "vitalik.eth"; let address = provider.resolve_name(name).await?; // Lookup ENS name given Address let resolved_name = provider.lookup_address(address).await?; assert_eq!(name, resolved_name); /// Lookup ENS field let url = "https://vitalik.ca".to_string(); let resolved_url = provider.resolve_field(name, "url").await?; assert_eq!(url, resolved_url); /// Lookup and resolve ENS avatar let avatar = "https://ipfs.io/ipfs/QmSP4nq9fnN9dAiCj42ug9Wa79rqmQerZXZch82VqpiH7U/image.gif".to_string(); let resolved_avatar = provider.resolve_avatar(name).await?; assert_eq!(avatar, resolved_avatar.to_string()); # Ok(()) # } ``` -------------------------------- ### Create and Merge Subscription Streams (Rust) Source: https://github.com/gakonst/ethers-rs/blob/master/book/subscriptions/multiple-subscriptions.md Demonstrates how to create multiple distinct subscription streams (e.g., for new blocks, logs matching a filter, or custom contract events) and then merge them into a single `combined_stream` using `stream::select_all`. It maps the items from each stream to a common `EventType` enum for unified processing. ```Rust async fn main() -> Result<(), Box> { // Create multiple subscription streams. let mut block_stream = provider.subscribe_blocks().await?; let mut log_stream = provider.subscribe_logs(filter).await?; let mut event_stream = watcher.subscribe().await?; // Merge the streams into a single stream. let mut combined_stream = stream::select_all(vec![ block_stream.map_ok(|block| EventType::Block(block)), log_stream.map_ok(|log| EventType::Log(log)), event_stream.map_ok(|event| EventType::Event(event)), ]); // Your code to handle the events goes here. Ok(()) } ``` -------------------------------- ### Add ethers-solc to build-dependencies (TOML) Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-solc/README.md This TOML snippet shows how to add `ethers-solc` as a build dependency in your project's `Cargo.toml` file, typically under the `[build-dependencies]` section, allowing it to be used by the `build.rs` script. ```toml [build-dependencies] ethers-solc = { git = "https://github.com/gakonst/ethers-rs" } ``` -------------------------------- ### Auto-fix Rust Lint Issues with cargo clippy Source: https://github.com/gakonst/ethers-rs/blob/master/README.md Runs the Clippy linter with the `--fix` flag to automatically resolve simple lint warnings and errors using the nightly toolchain. ```Shell cargo +nightly clippy --fix ``` -------------------------------- ### Calculate UniswapV2 Pair Address in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-core/README.md This snippet demonstrates how to calculate the deterministic CREATE2 address for a UniswapV2 pair given the factory address, the two token addresses, and the init code hash. It uses utilities from the `ethers_core` crate, specifically for ABI encoding and Keccak-256 hashing. ```rust # use ethers_core::abi::{self, Token}; # use ethers_core::types::{Address, H256}; # use ethers_core::utils; let factory: Address = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f".parse()?; let token_a: Address = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48".parse()?; let token_b: Address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2".parse()?; let encoded = abi::encode_packed(&[Token::Address(token_a), Token::Address(token_b)])?; let salt = utils::keccak256(encoded); let init_code_hash: H256 = "0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f".parse()?; let pair = utils::get_create2_address_from_hash(factory, salt, init_code_hash); let weth_usdc = "0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc".parse()?; assert_eq!(pair, weth_usdc); # Ok::<(), Box>(()) ``` -------------------------------- ### Add Gas Oracle Middleware in Rust Source: https://github.com/gakonst/ethers-rs/blob/master/ethers-middleware/README.md Integrates `GasOracleMiddleware` with a `GasNow` oracle to fetch current recommended gas prices, ensuring transactions are sent with appropriate fees. ```Rust // Use GasNow as the gas oracle let gas_oracle = GasNow::new(); let provider = GasOracleMiddleware::new(provider, gas_oracle); ```