# Alloy Alloy is a high-performance Rust toolkit for Ethereum and EVM-compatible chains. ## Installation [Alloy](https://github.com/alloy-rs/alloy) consists of a number of crates that provide a range of functionality essential for interfacing with any Ethereum-based blockchain. The easiest way to get started is to add the `alloy` crate from the command-line using Cargo: ```sh cargo add alloy ``` Alternatively, you can add the following to your `Cargo.toml` file: ```toml // [!include ~/snippets/installation/alloy.toml] ``` For a more fine-grained dependency, use the `alloy` crate with task-specific features or depend on the individual crate that owns the API. See [how Alloy fits together](https://alloy.rs/introduction/architecture) and the [feature flag reference](https://alloy.rs/reference/feature-flags) before disabling defaults. After `alloy` is added as a dependency you can now import `alloy` as follows: ```rust use alloy::{ network::EthereumWallet, node_bindings::Anvil, primitives::U256, providers::ProviderBuilder, signers::local::PrivateKeySigner, sol, }; ``` The `node_bindings` module, together with the `ProviderBuilder::connect_anvil*` helpers, is only available with the `node-bindings` feature, which the default feature set does not enable. Add it when you want to start Anvil, Geth, or Reth from Rust, for example to run the [getting started](https://alloy.rs/introduction/getting-started) examples: ```sh cargo add alloy --features node-bindings ``` ### Next steps * [Choose a task-oriented path](https://alloy.rs/introduction/choose-a-path). * [Understand Alloy's crate and runtime layers](https://alloy.rs/introduction/architecture). * [Select feature flags](https://alloy.rs/reference/feature-flags). * [Build the first provider and contract calls](https://alloy.rs/introduction/getting-started). # Choose a path Start with the row that matches what you are building. Each path points to an explanation first and then to runnable code where one exists. | Goal | Read first | Runnable examples | | --- | --- | --- | | Connect to a node and make RPC calls | [Getting started](https://alloy.rs/introduction/getting-started), then [RPC providers](https://alloy.rs/rpc-providers/introduction) | [Providers](https://alloy.rs/examples/providers/README) | | Read or write a smart contract | [Contract interactions](https://alloy.rs/contract-interactions/using-sol!), then [reading](https://alloy.rs/contract-interactions/read-contract) or [writing](https://alloy.rs/contract-interactions/write-contract) | [Contracts](https://alloy.rs/examples/contracts/README) | | Build, sign, and send a transaction | [Transaction lifecycle](https://alloy.rs/transactions/transaction-lifecycle), then [transaction builder](https://alloy.rs/transactions/using-the-transaction-builder) | [Transactions](https://alloy.rs/examples/transactions/README) | | Subscribe to blocks, logs, or pending transactions | [WebSocket provider](https://alloy.rs/rpc-providers/ws-provider) | [Subscriptions](https://alloy.rs/examples/subscriptions/README) | | Choose a signer or wallet | [Signers vs. Ethereum wallet](https://alloy.rs/guides/signers-vs-ethereum-wallet) | [Wallets and signers](https://alloy.rs/examples/wallets/README) | | Work with more than one chain or custom network types | [Interacting with multiple networks](https://alloy.rs/guides/interacting-with-multiple-networks) | [Any network](https://alloy.rs/examples/advanced/any_network) | | Add retries, rate limits, fallbacks, or observability | [Transport layers](https://alloy.rs/guides/layers) | [Layers](https://alloy.rs/examples/layers/README) | | Test with mocks, Anvil, Geth, Reth, or a fork | [Testing Alloy applications](https://alloy.rs/guides/testing) | [Mock provider](https://alloy.rs/examples/providers/mocking) and [node bindings](https://alloy.rs/examples/node-bindings/README) | | Decode ABI data, logs, or transaction input | [Using `sol!`](https://alloy.rs/contract-interactions/using-sol!) | [`sol!` examples](https://alloy.rs/examples/sol-macro/README) and [transaction decoding](https://alloy.rs/examples/transactions/decode_input) | | Select a smaller dependency set | [Feature flags](https://alloy.rs/reference/feature-flags) | [Alloy features on docs.rs](https://docs.rs/crate/alloy/latest/features) | | Migrate from ethers-rs | [Migration reference](https://alloy.rs/migrating-from-ethers/reference) | [Conversions](https://alloy.rs/migrating-from-ethers/conversions) | ## When a guide does not cover the API Use the documentation layers in this order: 1. This site for concepts and supported workflows. 2. The [examples repository](https://github.com/alloy-rs/examples) for complete programs. 3. [docs.rs](https://docs.rs/alloy/latest/alloy/) for exact types, traits, methods, and feature gates. 4. The [Alloy source](https://github.com/alloy-rs/alloy) when behavior or version history matters. The [agent guide](https://alloy.rs/introduction/prompting) gives the same retrieval order in a compact form for coding agents. # How Alloy fits together Alloy is a collection of focused crates behind one convenience crate named `alloy`. Most applications should start with the `alloy` crate. Depending on individual crates is useful when a library needs a small public dependency surface, a constrained feature set, or a specific layer of the stack. ```text Application ├── contract bindings and calls alloy-contract ├── providers and middleware alloy-provider ├── wallets and signers alloy-signer-* └── network-specific behavior alloy-network │ ├── RPC methods and types alloy-rpc-client, alloy-rpc-types-* ├── HTTP, WebSocket, IPC alloy-transport-* └── blocks, txs, EIPs, tries alloy-consensus, alloy-eips, alloy-trie Shared values and ABI tooling alloy-core ├── alloy-primitives ├── alloy-sol-types / sol! ├── alloy-dyn-abi └── alloy-json-abi ``` The `alloy` meta-crate re-exports these APIs under stable task-oriented modules such as `alloy::providers`, `alloy::network`, `alloy::signers`, `alloy::rpc`, and `alloy::primitives`. Feature flags decide which re-exports and implementations are compiled. ## The layers ### Core values and ABI [`alloy-core`](https://docs.rs/alloy-core/latest/alloy_core/) supplies addresses, byte strings, fixed-width integers, hashes, ABI codecs, JSON ABI types, and the [`sol!` macro](https://docs.rs/alloy/latest/alloy/macro.sol.html). These pieces can be used without a provider. ### Consensus and networks [`alloy-consensus`](https://docs.rs/alloy-consensus/latest/alloy_consensus/) defines Ethereum block, transaction, receipt, and envelope behavior. [`alloy-network`](https://docs.rs/alloy-network/latest/alloy_network/) connects those types to provider behavior. APIs are commonly generic over a `Network`; the default is Ethereum. Other ecosystems can provide their own network implementation without replacing the provider stack. ### RPC types, client, and transports RPC is split deliberately: * `alloy-rpc-types-*` models request and response data for namespaces such as `eth`, `debug`, `trace`, `txpool`, `engine`, and `anvil`. * `alloy-rpc-client` sends JSON-RPC requests over a transport. * `alloy-transport-http`, `alloy-transport-ws`, and `alloy-transport-ipc` implement the connection. Use these lower layers directly only when building infrastructure or a custom provider. Application code normally uses a provider. ### Providers, fillers, and layers [`alloy-provider`](https://docs.rs/alloy-provider/latest/alloy_provider/) is the application-facing RPC interface. A provider exposes typed methods, while fillers populate transaction fields such as chain ID, nonce, gas, and wallet signatures. Tower layers wrap transport behavior for concerns such as retries, rate limiting, fallback, or logging. See [RPC providers](https://alloy.rs/rpc-providers/introduction), [fillers](https://alloy.rs/rpc-providers/understanding-fillers), and [transport layers](https://alloy.rs/guides/layers). ### Signers and wallets A signer produces a signature. An `EthereumWallet` selects among signers and supplies the network wallet behavior used by transaction fillers. Local keys, mnemonics, keystores, hardware wallets, cloud KMS services, and Turnkey are separate implementations so applications compile only the integration they use. See [signers vs. Ethereum wallet](https://alloy.rs/guides/signers-vs-ethereum-wallet) and the [signer examples](https://alloy.rs/examples/wallets/README). ### Contract bindings `sol!` creates strongly typed Rust bindings from Solidity declarations or JSON ABI. `alloy-contract` uses those bindings with a provider to deploy contracts, call functions, send transactions, and query events. See [contract interactions](https://alloy.rs/contract-interactions/using-sol!). ## Local nodes and tests `alloy-node-bindings` starts supported execution clients as child processes; it does not install the client binary. The `provider-anvil-node` feature adds `ProviderBuilder` helpers for Anvil and also enables the required node bindings. The `full` feature does **not** enable node bindings. For unit tests that should not start a process or use a network, use a mocked provider. Compare the [mock provider](https://alloy.rs/examples/providers/mocking) and [node-binding examples](https://alloy.rs/examples/node-bindings/README). ## Choosing the dependency boundary * **Application:** begin with `alloy` and enable the task-specific features you need. * **Reusable library:** prefer the narrow crate that owns the types in your public API. * **Core-only or constrained target:** depend on `alloy-core` crates directly and inspect their `std` support. * **Custom infrastructure:** compose RPC client, transport, provider, and network crates explicitly. Continue with [feature flags](https://alloy.rs/reference/feature-flags) for concrete dependency recipes. # Getting Started \[The simplest, fastest Rust toolkit to interact with any EVM chain] ## Overview Alloy is a high-performance Rust toolkit for Ethereum and EVM-based blockchains providing developers with: * **High Performance**: Optimized primitives with up to 60% faster U256 operations and 10x faster ABI encoding * **Developer Experience**: Intuitive API for interacting with Smart contracts via the `sol!` macro * **Chain-Agnostic Type System**: Multi-chain support without feature flags or type casting * **Extensibility**: Customizable provider architecture with layers and fillers ## Installation Install Alloy in any Cargo project using the command line. See [feature flags](https://alloy.rs/reference/feature-flags) for task-specific and minimal configurations. ```bash [cargo] cargo add alloy ``` ## Quick Start The default features cover the first example, which connects to an Anvil node you start yourself. The second example starts and controls Anvil from Rust, which requires the `node-bindings` feature and the [`anvil`](https://getfoundry.sh) binary on your `PATH`. The third example subscribes over WebSocket, which requires `provider-ws`. Enable both to run every example on this page: ```bash [cargo] cargo add alloy --features node-bindings,provider-ws ``` ### 1. Sending Transactions This example shows how to send 100 ETH using the [`TransactionBuilder`](https://alloy.rs/transactions/using-the-transaction-builder) on a local anvil node. Start the node with `anvil` in a separate terminal before running it: ```rust use alloy::{ network::TransactionBuilder, primitives::{ address, utils::{format_ether, Unit}, U256, }, providers::{Provider, ProviderBuilder}, rpc::types::TransactionRequest, signers::local::PrivateKeySigner, }; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize a signer with a private key let signer: PrivateKeySigner = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80".parse()?; // Instantiate a provider with the signer and a local anvil node let provider = ProviderBuilder::new() // [!code focus] .wallet(signer) // [!code focus] .connect("http://127.0.0.1:8545") // [!code focus] .await?; // Prepare a transaction request to send 100 ETH to Alice let alice = address!("0x70997970C51812dc3A010C7d01b50e0d17dc79C8"); // [!code focus] let value = Unit::ETHER.wei().saturating_mul(U256::from(100)); // [!code focus] let tx = TransactionRequest::default() // [!code focus] .with_to(alice) // [!code focus] .with_value(value); // [!code focus] // Send the transaction and wait for the broadcast let pending_tx = provider.send_transaction(tx).await?; // [!code focus] println!("Pending transaction... {}", pending_tx.tx_hash()); // Wait for the transaction to be included and get the receipt let receipt = pending_tx.get_receipt().await?; // [!code focus] println!( "Transaction included in block {}", receipt.block_number.expect("Failed to get block number") ); println!("Transferred {:.5} ETH to {alice}", format_ether(value)); Ok(()) } ``` ### 2. Interacting with Smart Contracts Alloy's `sol!` macro makes working with smart contracts intuitive by letting you write Solidity directly in Rust. This example forks mainnet into a local Anvil instance with `connect_anvil_with_config` and funds the signer through the `AnvilApi` extension trait, both of which need the `node-bindings` feature. Set `RPC_URL` to a mainnet RPC endpoint before running it: ```rust use alloy::{ primitives::{ address, utils::{format_ether, Unit}, U256, }, providers::{ext::AnvilApi, ProviderBuilder}, signers::local::PrivateKeySigner, sol, }; use std::error::Error; // Generate bindings for the WETH9 contract sol! { // [!code focus] #[sol(rpc)] // [!code focus] contract WETH9 { // [!code focus] function deposit() public payable; // [!code focus] function balanceOf(address) public view returns (uint256); // [!code focus] function withdraw(uint amount) public; // [!code focus] } // [!code focus] } // [!code focus] #[tokio::main] async fn main() -> Result<(), Box> { // Initialize a random signer and get address from it let signer = PrivateKeySigner::random(); // [!code focus] let from_address = signer.address(); let rpc_url = std::env::var("RPC_URL")?; // Instantiate a provider with the signer let provider = ProviderBuilder::new() // [!code focus] .wallet(signer) // [!code focus] .connect_anvil_with_config(|anvil| anvil.fork(rpc_url)); // Fund the random signer on the local Anvil fork provider // [!code focus] .anvil_set_balance( // [!code focus] from_address, // [!code focus] Unit::ETHER.wei().saturating_mul(U256::from(100)), // [!code focus] ) // [!code focus] .await?; // [!code focus] // Setup WETH contract instance let weth_address = address!("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"); let weth = WETH9::new(weth_address, provider.clone()); // [!code focus] // Read initial balance let initial_balance = weth.balanceOf(from_address).call().await?; // [!code focus] println!("Initial WETH balance: {} WETH", format_ether(initial_balance)); // Write: Deposit ETH to get WETH let deposit_amount = Unit::ETHER.wei().saturating_mul(U256::from(10)); let deposit_tx = weth.deposit().value(deposit_amount).send().await?; // [!code focus] let deposit_receipt = deposit_tx.get_receipt().await?; // [!code focus] println!( "Deposited ETH in block {}", deposit_receipt.block_number.expect("Failed to get block number") ); // Read: Check updated balance after deposit let new_balance = weth.balanceOf(from_address).call().await?; println!("New WETH balance: {} WETH", format_ether(new_balance)); // Write: Withdraw some WETH back to ETH let withdraw_amount = Unit::ETHER.wei().saturating_mul(U256::from(5)); let withdraw_tx = weth.withdraw(withdraw_amount).send().await?; // [!code focus] let withdraw_receipt = withdraw_tx.get_receipt().await?; // [!code focus] println!( "Withdrew ETH in block {}", withdraw_receipt.block_number.expect("Failed to get block number") ); // Read: Final balance check let final_balance = weth.balanceOf(from_address).call().await?; // [!code focus] println!("Final WETH balance: {} WETH", format_ether(final_balance)); Ok(()) } ``` ### 3. Monitoring Blockchain Activity This example shows how to monitor blocks and track the [WETH](https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2) balance of a [Uniswap V3 WETH-USDC](https://etherscan.io/address/0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8) contract in real-time. It needs the `provider-ws` feature, the `futures-util` crate for `StreamExt`, and `WS_URL` set to a WebSocket endpoint: :::code-group ```rust [subscribe_blocks.rs] use alloy::{ primitives::{address, utils::format_ether}, providers::{Provider, ProviderBuilder, WsConnect}, sol, }; use futures_util::StreamExt; sol! { // [!code focus] #[sol(rpc)] // [!code focus] contract WETH { // [!code focus] function balanceOf(address) external view returns (uint256); // [!code focus] } // [!code focus] } // [!code focus] #[tokio::main] async fn main() -> Result<(), Box> { // Connect to an Ethereum node via WebSocket let ws = WsConnect::new(std::env::var("WS_URL")?); // [!code focus] let provider = ProviderBuilder::new().connect_ws(ws).await?; // [!code focus] // Uniswap V3 WETH-USDC Pool address let uniswap_pool = address!("0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8"); // [!code focus] // Setup the WETH contract instance let weth_addr = address!("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); let weth = WETH::new(weth_addr, &provider); // [!code focus] // Subscribe to new blocks let mut block_stream = provider.subscribe_blocks().await?.into_stream(); // [!code focus] println!("🔄 Monitoring for new blocks..."); // Process each new block as it arrives while let Some(block) = block_stream.next().await { // [!code focus] println!("🧱 Block #{}: {}", block.number, block.hash); // Get contract balance at this block let balance = weth.balanceOf(uniswap_pool).block(block.number.into()).call().await?; // [!code focus] // Format the balance in ETH println!("💰 Uniswap V3 WETH-USDC pool balance: {} WETH", format_ether(balance)); } Ok(()) } ``` ```sh [output] 🔄 Monitoring for new blocks... 🧱 Block #22445374: 0x8a75355b6efd4890789f60d1d7cb7b6c32c1ce9b0651db779c145217346d2219 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445375: 0xbb6265e4d4e81adfa73afd759d65804756fb83c5a72065b50343f7b10e1dfc47 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445376: 0xb82d720ea7e4b7019e8573d5a01865bbcecb7b8aae3a03d4dae58af1dc7ec026 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445377: 0x7d21a4f3dd376888df8a1ead3c7f0a9c9f7107b0a627795ec2584eeb92f13ce7 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445378: 0xd552c7595c9b2e77b1a9def6d818376ab6eac4c10dfc9d610a91b23894b54fa7 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445379: 0x89190317a8181eedecdddd4551bc9db0267750e659d78aca53f293c774b343b6 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445380: 0xb68a9c344233b598e43c81b14691ff73453d8ad39491a1a0120bed12d8086d11 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445381: 0x547b15a475d5e5316ddac707c37b5275568872531ca17d3022c9130b37fe0b21 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445382: 0xdd3dcf55908e6ae7cc33949952c9383afc91cf7827d5ada715baaf1a018ce050 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445383: 0x4d3a5565b18b896fea580ce94d009b11a8f076c800a3a738b66de16a91d4cd3c 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH 🧱 Block #22445384: 0xc29957a5d4d981dfb02416e7bec45546678914b3e9660fcb7635d0a679bce635 💰 Uniswap V3 ETH-USDC Pool balance: 7496.034522333161564023 ETH ``` ::: ## Crate Features Alloy can be consumed in multiple ways with numerous combinations of features for different use cases. ### Meta crate The [alloy](https://crates.io/crates/alloy) meta crate is useful when you want to quickly get started without dealing with multiple installations or features. It comes with the following features as default: ```toml [Cargo.toml] default = ["std", "reqwest", "alloy-core/default", "essentials"] # std std = [ "alloy-core/std", "alloy-eips?/std", "alloy-genesis?/std", "alloy-serde?/std", "alloy-consensus?/std", ] # enable basic network interactions out of the box. essentials = ["contract", "provider-http", "rpc-types", "signer-local"] ``` Find the full feature list [here](https://github.com/alloy-rs/alloy/blob/main/crates/alloy/Cargo.toml). ### Individual crates Alloy is a collection of modular crates that can be used independently. Meta-crates can lead to dependencies bloat increasing compile-time. For large projects where compile time can be an issue, we recommend using crates independently as in when required. ```toml [Cargo.toml] // [!include ~/snippets/installation/individual-crates.toml] ``` This allows you to have granular control over the dependencies and features you use in your project. See [how Alloy fits together](https://alloy.rs/introduction/architecture) for the crate and runtime layers. ### `no_std` crates Most of the crates in Alloy are not `no_std` as they are primarily network-focused. Having said that we do support `no_std` implementation for crucial crates such as: 1. [alloy-eips](https://crates.io/crates/alloy-eips): Consists of Ethereum's current and future EIP types and spec implementations. 2. [alloy-genesis](https://crates.io/crates/alloy-genesis): The Ethereum genesis file definitions. 3. [alloy-serde](https://crates.io/crates/alloy-serde): Serialization and deserialization of helpers for alloy. 4. [alloy-consensus](https://crates.io/crates/alloy-consensus): The Ethereum consensus interface. It contains constants, types, and functions for implementing Ethereum EL consensus and communication. This includes headers, blocks, transactions, EIP-2718 envelopes, EIP-2930, EIP-4844, and more. ## Guides Check out our Guides to see more practical use cases, including: * [Building MEV bots with Alloy primitives](https://alloy.rs/guides/speed-up-using-u256) * [Seamless contract interaction with the sol! macro](https://alloy.rs/guides/static-dynamic-abi-in-alloy) * [Creating custom transaction fillers for setting priority fees](https://alloy.rs/guides/fillers) * [Using multicall for aggregating RPC requests](https://alloy.rs/guides/multicall) # Why Alloy? Alloy is the next-generation Rust toolkit for Ethereum development and a complete rewrite of [ethers-rs](https://www.gakonst.com/ethers-rs/getting-started/intro.html). Alloy offers a modular, high-performance, and developer-friendly experience for building on EVM-compatible chains. It addresses pain points in existing Rust Ethereum tooling, such as performance bottlenecks, cumbersome APIs, and feature flags that bloat applications. *** It provides a complete toolkit for Ethereum development in Rust: * **Seamless smart contract interactions**: The `sol!` macro enables you to parse Solidity syntax directly in Rust code, simplifying contract interactions. * **Simplified RPC Provider Usage**: Alloy enables you to connect to an EVM node in a simple and intuitive way. * **Multi-Chain Support**: The `Network` trait allows seamless integration with any EVM-compatible chain without feature flags. * **Layered Architecture**: Replaces monolithic middleware with composable layers and fillers, enhancing modularity and clarity. * **Optimized Primitives**: Alloy's rewritten core components deliver major performance gains across key Ethereum operations such as ABI encoding/decoding, U256 operations, and RLP encoding and decoding. ## Benchmarks Alloy's performance improvements are demonstrated through several key benchmarks. 1. **ABI Encoding**: Measures the speed of encoding Solidity contract data (both static and dynamic types) into the Ethereum ABI format, which is required for making contract calls and sending transactions. For the purpose of this benchmark, we are encoding the Uniswap V2 `swap` function. {" "}
```solidity // Benchmarks encode the calldata for this method function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; ```
| | Ethers | Alloy | Speedup | | :---------- | :-------- | :--------- | :------------ | | **Static** | `1.12 μs` | `90.89 ns` | 🚀 **12.32x** | | **Dynamic** | `2.20 μs` | `1.88 μs` | ✅ **1.17x** | 2. **U256 Operations: Uniswap V2 Swap Calculations**: U256 Math is fairly common in EVM land, specially when interacting with DeFi protocols. For this benchmark we shall calculate the token `amountIn` and `amountOut` necessary for swapping. {" "}
| | Ethers | Alloy | Speedup | | :------------ | :---------- | :---------- | :----------- | | **amountIn** | `512.47 ns` | `216.32 ns` | 🚀 **2.37x** | | **amountOut** | `53.82 ns` | `18.19 ns` | 🚀 **2.96x** | 3. **RLP Encoding/Decoding**: Measures the speed of encoding and decoding data using Recursive Length Prefix (RLP), a serialization method used throughout Ethereum (e.g., for blocks and transactions). For this benchmark, we shall RLP encode and decode a simple struct. ```rust // Derive the necessary traits #[derive(alloy_rlp::RlpEncodable, alloy_rlp::RlpDecodable)] #[derive(rlp_derive::RlpDecodable, rlp_derive::RlpEncodable)] pub struct MyStruct { a: u128, b: Vec, } ```
| | Parity-Rlp | Alloy-Rlp | Speedup | | :----------- | :--------- | :--------- | :----------- | | **Encoding** | `86.70 ns` | `26.88 ns` | 🚀 **3.23x** | | **Decoding** | `88.79 ns` | `21.43 ns` | 🚀 **4.14x** | # Using Alloy documentation with coding agents Alloy publishes machine-readable documentation for coding agents. Give an agent the smallest relevant context instead of copying the entire manual into every prompt. ## Recommended retrieval order 1. Query [`agent-index.json`](https://alloy.rs/agent-index.json) when the client can read JSON. It maps task vocabulary, features, environment variables, guides, and examples. 2. Otherwise start with [`llms.txt`](https://alloy.rs/llms.txt) to discover the canonical page. 3. Load the smallest relevant page through its `markdown_url` field when present. Fall back to its HTML `url`, then follow the runnable examples it links to. 4. Use [docs.rs](https://docs.rs/alloy/latest/alloy/) for exact types, traits, methods, and feature gates. 5. Use [`llms-full.txt`](https://alloy.rs/llms-full.txt) only when the agent cannot retrieve pages individually. The Alloy version displayed in this site's navigation is the version targeted by hand-written documentation. Generated example pages identify the exact examples commit they were copied from. All URLs in the published agent inventories are absolute. Cache them with the documented Alloy version and invalidate the cache when that version changes. ## Starter prompt Use this as a short foundation, then append the task, target chain, transport, signer, and runtime constraints. ```text You are implementing a Rust application with Alloy. Use the supplied alloy.rs documentation and linked docs.rs API pages as the source of truth. Prefer the current stable Alloy APIs shown by those sources. Requirements: - Name every required crate and feature flag. - Produce complete, runnable Rust rather than disconnected fragments. - Import the traits needed for extension methods. - Use ProviderBuilder for provider construction and sol! for typed contract APIs. - Distinguish consensus types, RPC types, and network-specific types. - Explain external prerequisites such as RPC_URL, WebSocket support, credentials, hardware devices, Anvil, or a particular RPC namespace. - Read secrets and RPC URLs from environment variables; do not embed credentials or depend on an undocumented shared endpoint. - Handle transport errors, JSON-RPC errors, contract reverts, transaction timeouts, and confirmations when they are relevant to the task. - Do not invent methods or feature names. Verify exact symbols against docs.rs. - End with the commands needed to format and compile the result. Task: ``` ## Context that improves results Include these details when they matter: * Ethereum or another `Network` implementation. * HTTP, WebSocket, IPC, or a custom transport. * Read-only access or transaction signing. * Local key, mnemonic, keystore, hardware wallet, or cloud signer. * Required RPC namespaces such as Debug, Trace, Engine, TxPool, or Anvil. * Expected confirmation policy and reorg behavior. * Native, WASM, or `no_std` target. * Whether a local Anvil instance may be used for tests. ## Verify generated projects Agents should validate their output with the compiler rather than treating plausible-looking code as complete. ```sh cargo fmt --check cargo check --all-targets --all-features cargo clippy --all-targets --all-features -- -D warnings ``` For a minimal-feature project, also check the exact feature set used in production instead of relying only on `--all-features`. # Build a fast MEV bot with Alloy's Primitive Types [Alloy](https://alloy.rs) is a successor to the deprecated [ethers-rs](https://github.com/gakonst/ethers-rs). In this guide, we will describe how you can reap the benefits of its better performance with minimal codebase changes to ethers-rs project. We will also implement an atomic UniswapV2 arbitrage simulation to showcase how different parts of the Alloy stack fit together. Read on to learn how the benchmark in the examples repository measures Alloy's `U256` at **up to 2× faster** than ethers-rs for this workload. ## How to calculate optimal UniV2 arbitrage profit? An atomic arbitrage between two UniswapV2 pairs is one of the more basic MEV techniques. We will use this example to discuss the performance characteristics of ethers-rs vs Alloy. To execute an atomic arbitrage swap, you have to calculate the required input and output token amounts. UniswapV2 calculations can be done off-chain (i.e., without interacting with deployed Smart Contracts) with a relatively simple equation. Most publicly available bots use an iterative search function to find an optimal amount of input value. However, UniswapV2 constant product formula makes it possible to calculate a profitable input amount without multiple iterations. We will borrow the implementation of this formula [from Flashbots simple-blind-arbitrage repo](https://github.com/flashbots/simple-blind-arbitrage). You can find a step-by-step explanation of how to derive the formula [in this YouTube video](https://www.youtube.com/watch?v=9EKksG-fF1k). All the code examples for this post are available in the [advanced examples](https://github.com/alloy-rs/examples/tree/main/examples/advanced/examples), with shared implementations in the [`helpers` crate](https://github.com/alloy-rs/examples/tree/main/helpers/src). Let's start with implementing a struct representing a Uniswap pool and a few helper functions in Alloy: [`helpers/src/alloy.rs`](https://github.com/alloy-rs/examples/blob/main/helpers/src/alloy.rs) ```rust use alloy::primitives::{address, Address, U256}; pub static WETH_ADDR: Address = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); #[derive(Debug)] pub struct UniV2Pair { pub address: Address, pub token0: Address, pub token1: Address, pub reserve0: U256, pub reserve1: U256, } // https://etherscan.io/address/0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11 pub fn get_uniswap_pair() -> UniV2Pair { UniV2Pair { address: address!("A478c2975Ab1Ea89e8196811F51A7B7Ade33eB11"), token0: DAI_ADDR, token1: WETH_ADDR, reserve0: uint!(6227630995751221000110015_U256), reserve1: uint!(2634810784674972449382_U256), } } pub fn get_amount_out(reserve_in: U256, reserve_out: U256, amount_in: U256) -> U256 { let amount_in_with_fee = amount_in * U256::from(997_u64); // uniswap fee 0.3% let numerator = amount_in_with_fee * reserve_out; let denominator = reserve_in * U256::from(1000_u64) + amount_in_with_fee; numerator / denominator } pub fn get_amount_in( reserves00: U256, reserves01: U256, is_weth0: bool, reserves10: U256, reserves11: U256, ) -> U256 { let numerator = get_numerator(reserves00, reserves01, is_weth0, reserves10, reserves11); let denominator = get_denominator(reserves00, reserves01, is_weth0, reserves10, reserves11); numerator * U256::from(1000) / denominator } //... ``` *Implemenation details are omitted for brevity.* `UniV2Pair` struct represents pools that we will be working with. `get_amount_out` is a standard calculation for determining how much of a given ERC20 you can buy from the pool after paying the protocol fees. `get_amount_in` is the profitable input amount formula that we borrow from Flashbots repo. It's worth noting that we use handy `address!` and `uint!` macros to generate the compile time constant `Address` and `U256` types. ### Iterative UniswapV2 profit algorithm Let's consider the following example: your MEV bot wants to score an arbitrage between UniswapV2 and Sushiswap WETH/DAI pools. Here's how you can calculate the arbitrage in a standard way: * calculate how much DAI you can buy from the UniswapV2 pool for a sample WETH input amount * calculate how much WETH you can buy back from Sushi pool for the previously calculated DAI amount * repeat the process for multiple values to determine which yields the best profit The above algorithm is iterative. There are ways to minimize the number of iterations, but this topic is outside the scope of this tutorial. ### Arbitrage profit formula Instead, we can use the `get_amount_in` method, which does more number crunching than `get_amount_out` but produces a profitable input amount in a single iteration Let's see it in action. In the following example, we use a mocked pool reserve value for [UniswapV2](https://etherscan.io/address/0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11) and [SushiSwap](https://etherscan.io/address/0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f) WETH/DAI Mainnet pools to simulate a profitable arbitrage opportunity. [`uniswap_u256_alloy_profit.rs`](https://github.com/alloy-rs/examples/blob/main/examples/advanced/examples/uniswap_u256_alloy_profit.rs) ```rust fn main() -> Result<()> { let uniswap_pair = get_uniswap_pair(); let sushi_pair = get_sushi_pair(); let amount_in = get_amount_in( uniswap_pair.reserve0, uniswap_pair.reserve1, false, sushi_pair.reserve0, sushi_pair.reserve1, ); let dai_amount_out = get_amount_out(uniswap_pair.reserve1, uniswap_pair.reserve0, amount_in); let weth_amount_out = get_amount_out(sushi_pair.reserve0, sushi_pair.reserve1, dai_amount_out); if weth_amount_out < amount_in { println!("No profit detected"); return Ok(()); } let profit = weth_amount_out - amount_in; println!("Alloy U256"); println!("WETH amount in {}", display_token(amount_in)); println!("WETH profit: {}", display_token(profit)); Ok(()) } ``` You can run it like that: ``` cargo run --locked -p examples-advanced --example uniswap_u256_alloy_profit ``` It should produce: ``` Alloy U256 WETH amount in 2.166958497387277956 WETH profit: 0.006142751241793559 ``` We've calculated a profitable Arbitrage for our mocked Uniswap pool reserves! ## "ethers-rs good, Alloy better!" If you compare the implementations in [`helpers/src/alloy.rs`](https://github.com/alloy-rs/examples/blob/main/helpers/src/alloy.rs) and [`helpers/src/ethers.rs`](https://github.com/alloy-rs/examples/blob/main/helpers/src/ethers.rs), you will notice that they are almost identical. Rewriting your project calculations from ethers-rs to Alloy `U256` should be possible with a very reasonable development effort. But is it worth it? It's high time to compare the performance of legacy ethers-rs U256 with the brand-new (based on the [ruint crate](https://crates.io/crates/ruint)) Alloy integer type. We will use the [criterion.rs crate](https://github.com/bheisler/criterion.rs). It generates reliable benchmarks by executing millions of iterations and turning off some compiler optimizations. You can find the source of the benchmark in [`benches/u256.rs`](https://github.com/alloy-rs/examples/blob/main/benches/benches/u256.rs) and execute it by running `cargo bench U256` We compare the performance of both `get_amount_in` and `get_amount_out`. Benchmark indicates **~1.5x-2x improvement** when using Alloy types! ![U256 performance comparison](https://alloy.rs/guides-images/alloy_u256/u256_bench_chart.png) On the above charts generated with criterion.rs you can see that Alloy is consistently faster for both methods and has less variation in execution time. This means that you can significantly improve the performance of your ethers-rs project by switching to the new U256 type. Here's how you can convert between the two types: [`helpers/src/alloy.rs`](https://github.com/alloy-rs/examples/blob/main/helpers/src/alloy.rs) ```rust use alloy::primitives::U256; use ethers::types::U256 as EthersU256; pub trait ToEthers { type To; fn to_ethers(self) -> Self::To; } impl ToEthers for U256 { type To = EthersU256; #[inline(always)] fn to_ethers(self) -> Self::To { EthersU256(self.into_limbs()) } } ``` [`helpers/src/ethers.rs`](https://github.com/alloy-rs/examples/blob/main/helpers/src/ethers.rs) ```rust use ethers::types::U256; use alloy::primitives::U256 as AlloyU256; pub trait ToAlloy { type To; fn to_alloy(self) -> Self::To; } impl ToAlloy for U256 { type To = AlloyU256; #[inline(always)] fn to_alloy(self) -> Self::To { AlloyU256::from_limbs(self.0) } } ``` This trait can easily be applied to any ethers-rs and Alloy types. You can check out [these conversion docs](https://alloy.rs/migrating-from-ethers/conversions) for details on how to do it. ## How to simulate MEV arbitrage with Alloy? Let's confirm that our calculations are correct by simulating the arbitrage swap. We will use a new Alloy stack to fork Anvil and mock the profit opportunity. Mocking the forked blockchain storage slots is an insanely useful technique. It allows to recreate any past blockchain state without an archive node. Geth full node by default prunes any state older than the last 128 blocks, i.e., only ~25 minutes. Using a forked blockchain saves a lot of effort in seeding the contract bytecodes. You can cherry-pick the exact EVM storage slots and modify them to match your desired simulation state. Anvil will implicitly fetch all the non-modified state from its origin blockchain. Here are the helper methods that we'll use: [`helpers/src/alloy.rs`](https://github.com/alloy-rs/examples/blob/main/helpers/src/alloy.rs) ```rust pub async fn set_hash_storage_slot( anvil_provider: P, address: Address, hash_slot: U256, hash_key: Address, value: U256, ) -> Result<()> { let hashed_slot = keccak256((hash_key, hash_slot).abi_encode()); anvil_provider.anvil_set_storage_at(address, hashed_slot.into(), value.into()).await?; Ok(()) } ``` We will leverage a custom Anvil RPC method, `anvil_setStorageAt`, to mock EVM storage values. `set_hash_storage_slot` method is used to overwrite values inside mappings. It implements a Solidity convention where the storage slot of a mapping value is `keccak256` of the storage slot of the mapping and the key. And here's our simulation: [`uniswap_u256_alloy_simulation.rs`](https://github.com/alloy-rs/examples/blob/main/examples/advanced/examples/uniswap_u256_alloy_simulation.rs) ```rust // imports omitted for brevity sol! { function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } sol!( #[sol(rpc)] contract IERC20 { function balanceOf(address target) returns (uint256); } ); sol!( #[sol(rpc)] FlashBotsMultiCall, "examples/abi/FlashBotsMultiCall.json" ); #[tokio::main] async fn main() -> Result<()> { let uniswap_pair = get_uniswap_pair(); let sushi_pair = get_sushi_pair(); let wallet_address = address!("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); let rpc_url = rpc_url()?; let provider = ProviderBuilder::new().connect_anvil_with_wallet_and_config(|anvil| anvil.fork(rpc_url))?; let executor = FlashBotsMultiCall::deploy(provider.clone(), wallet_address).await?; let iweth = IERC20::new(WETH_ADDR, provider.clone()); // Mock WETH balance for executor contract set_hash_storage_slot( provider.clone(), WETH_ADDR, U256::from(3), *executor.address(), parse_units("5.0", "ether")?.into(), ) .await?; // Mock reserves for Uniswap pair provider .anvil_set_storage_at( uniswap_pair.address, U256::from(8), // getReserves slot B256::from_slice(&hex!( "665c6fcf00000000008ed55850d607f83a660000000526c08d812099d2577fbf" )), ) .await?; // Mock WETH balance for Uniswap pair set_hash_storage_slot( &provider, WETH_ADDR, U256::from(3), uniswap_pair.address, uniswap_pair.reserve1, ) .await?; // Mock DAI balance for Uniswap pair set_hash_storage_slot( &provider, DAI_ADDR, U256::from(2), uniswap_pair.address, uniswap_pair.reserve0, ) .await?; // Mock reserves for Sushi pair provider .anvil_set_storage_at( sushi_pair.address, U256::from(8), // getReserves slot B256::from_slice(&hex!( "665c6fcf00000000006407e2ec8d4f09436700000003919bf56d886af022979d" )), ) .await?; // Mock WETH balance for Sushi pair set_hash_storage_slot( &provider, WETH_ADDR, U256::from(3), sushi_pair.address, sushi_pair.reserve1, ) .await?; // Mock DAI balance for Sushi pair set_hash_storage_slot( &provider, DAI_ADDR, U256::from(2), sushi_pair.address, sushi_pair.reserve0, ) .await?; let balance_of = iweth.balanceOf(*executor.address()).call().await?; println!("Before - WETH balance of executor {:?}", balance_of); let weth_amount_in = get_amount_in( uniswap_pair.reserve0, uniswap_pair.reserve1, false, sushi_pair.reserve0, sushi_pair.reserve1, ); let dai_amount_out = get_amount_out(uniswap_pair.reserve1, uniswap_pair.reserve0, weth_amount_in); let weth_amount_out = get_amount_out(sushi_pair.reserve0, sushi_pair.reserve1, dai_amount_out); let swap1 = swapCall { amount0Out: dai_amount_out, amount1Out: U256::ZERO, to: sushi_pair.address, data: Bytes::new(), } .abi_encode(); let swap2 = swapCall { amount0Out: U256::ZERO, amount1Out: weth_amount_out, to: *executor.address(), data: Bytes::new(), } .abi_encode(); let arb_calldata = FlashBotsMultiCall::uniswapWethCall { _wethAmountToFirstMarket: weth_amount_in, _ethAmountToCoinbase: U256::ZERO, _targets: vec![uniswap_pair.address, sushi_pair.address], _payloads: vec![Bytes::from(swap1), Bytes::from(swap2)], } .abi_encode(); let arb_tx = TransactionRequest::default().with_to(*executor.address()).with_input(arb_calldata); let pending = provider.send_transaction(arb_tx).await?; pending.get_receipt().await?; let balance_of = iweth.balanceOf(*executor.address()).call().await?; println!("After - WETH balance of executor {:?}", balance_of); Ok(()) } ``` It uses a `FlashBotsMultiCall` contract from the [Flashbots simple-arbitrage repo](https://github.com/flashbots/simple-arbitrage) to atomically execute a swap between Uniswap and Sushiswap WETH/DAI pools. You can execute this simulation by running the following command on the examples repo: ``` RPC_URL=https://your-ethereum-endpoint \ cargo run --locked -p examples-advanced --example uniswap_u256_alloy_simulation ``` It should produce: ``` Before - WETH balance of executor 5000000000000000000 After - WETH balance of executor 5006142751241793559 ``` We've managed to simulate exactly the same profit of ~`0.00614` ETH that we've calculated before. ## Summary Rewriting your ethers-rs project could be a significant time investment. But Alloy is here to stay. Starting a migration from the calculations layer will let you reap performance benefits with minimal development effort. # Performant Static and Dynamic ABI Encoding In this guide, we will discuss new ways to work with blockchain ABIs introduced in [Alloy](https://alloy.rs). We will showcase basic smart contract interactions and how they compare to [ethers-rs](https://github.com/gakonst/ethers-rs). We will also discuss more advanced ways to interact with runtime-constructed dynamic ABIs. ## Alloy ABI 101 Below we have [implemented a simulation](https://alloy.rs/examples/contracts/simulation_uni_v2) of an arbitrage swap between two UniswapV2 pairs. We've used the following ABI definitions: ```rust sol! { function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } sol!( #[sol(rpc)] contract IERC20 { function balanceOf(address target) returns (uint256); } ); sol!( #[sol(rpc)] FlashBotsMultiCall, "artifacts/FlashBotsMultiCall.json" ); ``` You can find the complete [static encoding example](https://github.com/alloy-rs/examples/blob/main/examples/advanced/examples/encoding_sol_static.rs), [dynamic encoding example](https://github.com/alloy-rs/examples/blob/main/examples/advanced/examples/encoding_dyn_abi.rs), and [ABI artifacts](https://github.com/alloy-rs/examples/tree/main/examples/advanced/examples/abi) in the examples repository. Let's look into these examples in more detail. ### Static calldata encoding ```rust sol! { function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } ``` Alloy introduces the `sol!` macro that allows to embed compile-time-safe Solidity code directly in your Rust project. In the example, we use it to encode calldata needed for executing `swap` methods for our arbitrage. Here's how you can encode calldata: ```rust // swapCall is the struct generated by the sol! macro let swap_calldata = swapCall { amount0Out: U256::from(1000000000000000000_u128) amount1Out: U256::ZERO, to: sushi_pair.address, data: Bytes::new(), } .abi_encode(); ``` As a result, you'll get a `Vec` type that you can assign to an `input` field of a transaction. It's worth noting that `sol!` macro works with any semantically correct Solidity snippets. Here's how you can generate a calldata for a method that accepts a struct. For example: ```rust sol! { // Define your custom solidity struct struct MyStruct { uint256 id; string name; bool isActive; } // And a function that accepts it as an argument function setStruct(MyStruct memory _myStruct) external; } let my_struct = MyStruct { id: U256::from(1), name: "Hello".to_string(), isActive: true, }; // Encode the calldata for the `setStruct` fn call let calldata = setStructCall { _myStruct: my_struct.clone(), }.abi_encode(); ``` We've just imported a Solidity struct straight into the Rust code. You can use [`cast interface`](https://book.getfoundry.sh/reference/cast/cast-interface) CLI to generate Solidity snippets for any verified contract: :::code-group ```bash [cast] cast interface 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 --etherscan-api-key API_KEY ``` ```solidity [interace] // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; interface WETH9 { event Approval(address indexed src, address indexed guy, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); fallback() external payable; function allowance(address, address) external view returns (uint256); function approve(address guy, uint256 wad) external returns (bool); function balanceOf(address) external view returns (uint256); function decimals() external view returns (uint8); function deposit() external payable; // ... } ``` ::: ### Performance benchmark ethers-rs vs. Alloy On top of a nicer API, Alloy also comes with significantly better performance benefits. We've used the [criterion.rs crate](https://github.com/bheisler/criterion.rs) to produce reliable benchmarks for comparing encoding of static calldata for a method call. The reproducible benchmarks can be [found here](https://github.com/alloy-rs/examples/blob/main/benches/BENCHMARKS.md). | Ethers | Alloy | Speedup | | -------- | -------- | --------- | | 997.39ns | 92.69 ns | 10.76x 🚀 | Alloy is **~10x faster** than ethers-rs! Here's a chart to visualize the difference: ![Static ABI encoding performance comparison](https://alloy.rs/guides-images/alloy_abi/static_encoding_bench.png) ## Interacting with on-chain contracts Using `#[sol(rpc)]` marco, you can easily generate an interface to an on-chain contract. Let's see it in action: ```rust sol!( #[sol(rpc)] contract IERC20 { function balanceOf(address target) returns (uint256); function name() returns (string); } ); #[tokio::main] async fn main() -> Result<(), Box> { let rpc_url = std::env::var("RPC_URL")?; let provider = ProviderBuilder::new().connect(&rpc_url).await?; let iweth = IERC20::new(address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), provider.clone()); let name = iweth.name().call().await?; println!("Name: {}", name); // => Wrapped Ether } ``` Alternatively, instead of defining the interface methods in Solidity, you can use the standard JSON ABI file generated using `cast interface` with `--json` flag: ```bash cast interface 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 --json --etherscan-api-key API_KEY > abi/weth.json ``` Later you can use it like that: ```rust sol!( IERC20, "abi/WETH.json" ); ``` ### Deploying Smart Contract with `sol!` macro To deploy a smart contract, you must use its *"build artifact file"*. It's a JSON file you can generate by running the [`forge build` command](https://book.getfoundry.sh/reference/forge/forge-build): ```shell forge build contracts/FlashBotsMultiCall.sol ``` It produces a file containing contract's ABI, bytecode, deployed bytecode, and other metadata. Alternatively, you can use a recently added [`cast artifact` method](https://book.getfoundry.sh/reference/cli/cast/artifact): ```bash cast artifact 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 --etherscan-api-key $API_KEY --rpc-url $ETH_RPC_URL -o weth.json ``` It generates a minimal artifact file containing contract's bytecode and ABI based on Etherscan and RPC data. Contrary to `forge build`, you don't have to compile contracts locally to use it. You can later use an artifact file with the `sol!` macro like this: ```rust sol!( #[sol(rpc)] FlashBotsMultiCall, "artifacts/FlashBotsMultiCall.json" ); #[tokio::main] async fn main() -> Result<(), Box> { let rpc_url = std::env::var("RPC_URL")?; let anvil = Anvil::new().fork(rpc_url).try_spawn()?; let wallet_address = anvil.addresses()[0]; let provider = ProviderBuilder::new().connect(anvil.endpoint()).await?; let executor = FlashBotsMultiCall::deploy(provider.clone(), wallet_address).await?; println!("Executor deployed at: {}", *executor.address()); } ``` It uses Anvil to fork the mainnet and deploy smart contract to the local network. You can also use [`cast constructor-args`](https://book.getfoundry.sh/reference/cli/cast/constructor-args) command to check what were the original deployment arguments: ```bash cast constructor-args 0x6982508145454ce325ddbe47a25d4ec3d2311933 --etherscan-api-key $API_KEY --rpc-url $ETH_RPC_URL # 0x00000000000000000000000000000000000014bddab3e51a57cff87a50000000 → Uint(420690000000000000000000000000000, 256) ``` We've only discussed a few common ways to use ABI and `sol!` macro in Alloy. Make sure to [check the official docs](https://docs.rs/alloy-sol-macro/latest/alloy_sol_macro/macro.sol.html) for more examples. ## How to use dynamic ABI encoding? All the previous examples were using so-called static ABIs, i.e., with format known at the compile time. However, there are use cases where you'll have to work with ABI formats interpreted in the runtime. One practical example is a backend for a web3 wallet. It's not possible to include all the possible ABIs in the binary. So you'll have to work with JSON ABI files downloaded from the Etherscan API based on a user-provided address. Let's assume that we want to generate a calldata for a [UniswapV2 WETH/DAI pair](https://etherscan.io/address/0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11) `swap` method with arguments provided by a user: ```rust // Solidity: function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; use alloy::{ dyn_abi::{DynSolValue, JsonAbiExt}, hex, json_abi::Function, primitives::{uint, Address, Bytes, U256}, }; use std::error::Error; fn main() -> Result<(), Box> { // Setup the dynamic inputs for the `swap` function let input = vec![ DynSolValue::Uint(uint!(100000000000000000_U256), 256), DynSolValue::Uint(U256::ZERO, 256), DynSolValue::Address(Address::from([0x42; 20])), DynSolValue::Bytes(Bytes::new().into()), ]; // Parse the function signature let func = Function::parse( "function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external", )?; // Dynamically encode the function call let input = func.abi_encode_input(&input)?; println!("Calldata: {}", hex::encode(&input)); Ok(()) } ``` In the above example, we used the `DynSolValue` enum type to setup the input values for the `swap` function. We then parsed the funtion signature into the `Function` type which gives us access to the `abi_encode_input` method. This method accepts a vector of `DynSolValue` allowing us to dynamically encode the function calldata. This approach offers flexibility for interacting with virtually any ABIs that can be defined in a runtime. ### Performance benchmark for dynamic vs static ABI encoding Let's now compare the performance of generating `swap` method calldata for the same arguments with with Alloy and ethers-rs. You can find the reproducible [criterion benchmark here](https://github.com/alloy-rs/examples/blob/main/benches/BENCHMARKS.md). | Ethers | Alloy | Speedup | | ------ | ------ | -------- | | 2.12μs | 1.79μs | 1.19x 🚀 | Here's a chart to visualize the difference: ![Dynamic ABI encoding performance comparison](https://alloy.rs/guides-images/alloy_abi/dyn_encoding_bench.png) This time difference is not as dramatic as in static encoding. But Alloy is still ~20% faster than ethers-rs. ## Summary We've discussed common ways to interact with smart contracts ABI using the new Alloy stack. # Multicall and Multicall Batching layer ## What is Multicall? Multicall is a smart contract and pattern that allows you to batch multiple read-only calls to the Ethereum blockchain into a single request. Instead of sending separate RPC requests, Multicall combines them into one transaction, significantly reducing network overhead and latency. This solves various problems such as reduced latency and rate-limiting, network overhead, atomic state reading & offers better UX. ## When should I use Multicall ? * To read multiple contract states e.g. fetching balances, allowances, or prices across multiple contracts * To reduce request count e.g. working with public RPC endpoints that have rate limits * To ensure data consistency e.g. when you need multiple values from the same blockchain state Note that Multicall is not suitable for write operations (transactions that change state) and sequential operations where each call depends on the result of the previous one. ## Multicall with Alloy Alloy provides two ways in which a user can make multicalls to the [Multicall3 contract](https://www.multicall3.com/), both of which tightly integrated with the `Provider` to make usage as easy as possible: 1. Multicall Builder: The `multicall()` method gives you explicit control over which calls to batch 2. Multi-batching Layer: The batching layer automatically batches requests that are made in parallel ### 1. Multicall Builder Accessed via the `provider.multicall()` method works hand in hand with the bindings returned by the `sol!` macro to stack up multiple calls. ```rust let multicall = provider .multicall() // Set the address of the Multicall3 contract. If unset it uses the default address from : 0xcA11bde05977b3631167028862bE2a173976CA11 // .address(multicall3) // Get the total supply of WETH on our anvil fork. .add(weth.totalSupply()) // Get Alice's WETH balance. .add(weth.balanceOf(alice)) // Also fetch Alice's ETH balance. .get_eth_balance(alice); ``` You can find the complete example [here](https://alloy.rs/examples/providers/multicall) This approach is suitable when: * You know exactly which calls you want to batch together * You need to explicitly collect related data in a single request * You need fine-grained control over the order of results * You are working with varied contract types in a single batch ### 2. Multicall Batching Layer The batching layer is especially powerful because it requires no changes to your existing code and reduces the number of network requests. However, this only works when requests are made in parallel, for example when using the \[`tokio::join!`] macro or in multiple threads/tasks, as otherwise the requests will be sent one by one as normal, but with an added delay. ```rust [multicall_batching.rs] use alloy_provider::{layers::CallBatchLayer, Provider, ProviderBuilder}; use std::time::Duration; async fn f(url: &str) -> Result<(), Box> { // Build a provider with the default call batching configuration. let provider = ProviderBuilder::new().with_call_batching().connect(url).await?; // Build a provider with a custom call batching configuration. let provider = ProviderBuilder::new() .layer(CallBatchLayer::new().wait(Duration::from_millis(10))) .connect(url) .await?; // Both of these requests will be batched together and only 1 network request will be made. let (block_number_result, chain_id_result) = tokio::join!(provider.get_block_number(), provider.get_chain_id()); let block_number = block_number_result?; let chain_id = chain_id_result?; println!("block number: {block_number}, chain id: {chain_id}"); Ok(()) } ``` Find the complete example [here](https://alloy.rs/examples/providers/multicall_batching). This approach is suitable when: * You want to optimize existing code without restructuring it * You need to batch calls that are made from different parts of your codebase # Interacting with multiple networks The provider trait is generic over the network type, `Provider`, with the default network set to `Ethereum`. The `Network` generic helps the provider to accomodate various network types with different transaction and RPC response types seamlessly. ## The Network trait This removes the need for implementing the `Provider` trait for each network type you want to interact with. Instead, we just need to implement the `Network` trait. Following is the [`Ethereum` network implementation](https://github.com/alloy-rs/alloy/blob/main/crates/network/src/ethereum/mod.rs) which defines the structure of the network and its RPC types. ```rust [ethereum.rs] impl Network for Ethereum { type TxType = alloy_consensus::TxType; type TxEnvelope = alloy_consensus::TxEnvelope; type UnsignedTx = alloy_consensus::TypedTransaction; type ReceiptEnvelope = alloy_consensus::ReceiptEnvelope; type Header = alloy_consensus::Header; type TransactionRequest = alloy_rpc_types_eth::transaction::TransactionRequest; type TransactionResponse = alloy_rpc_types_eth::Transaction; type ReceiptResponse = alloy_rpc_types_eth::TransactionReceipt; type HeaderResponse = alloy_rpc_types_eth::Header; type BlockResponse = alloy_rpc_types_eth::Block; } ``` Choosing the wrong network type can lead to unexpected deserialization errors due to differences in RPC types. For example, the using an `Ethereum` network provider to get a full block with transactions can result in the following error: ```rust [base_block.rs] let rpc_url = std::env::var("RPC_URL")?; let provider = ProviderBuilder::new() .network::() .connect(&rpc_url) .await?; // Yields: Error: deserialization error: data did not match any variant of untagged enum BlockTransactions // [!code hl] let block_with_txs = provider.get_block(25508329.into()).full().await?; ``` This is due to the `Deposit` transaction type which is not supported by `Ethereum` network. This can be fixed in two ways either by using the catch-all `AnyNetwork` type or by using the dedicated `Optimism` network implementation from [op-alloy-network](https://crates.io/crates/op-alloy-network). ## Catch-all network: `AnyNetwork` The `Provider` defaults to the ethereum network type, but one can easily switch to another network while building the provider like so: ```rust let provider = ProviderBuilder::new() .network::() // [!code hl] .connect_http("http://localhost:8545"); ``` The [`AnyNetwork` type](https://github.com/alloy-rs/alloy/blob/main/crates/network/src/any/mod.rs) is a catch-all network allowing you to interact with any network type, in case you don't want to roll your own network type. ## Custom Network: `Optimism` The [`Optimism` network](https://github.com/alloy-rs/op-alloy/blob/main/crates/network/src/lib.rs) type has been created to interact with OP-stack chains such as Base. ```rust [optimism.rs] impl Network for Optimism { type TxType = OpTxType; type TxEnvelope = op_alloy_consensus::OpTxEnvelope; type UnsignedTx = op_alloy_consensus::OpTypedTransaction; type ReceiptEnvelope = op_alloy_consensus::OpReceiptEnvelope; type Header = alloy_consensus::Header; type TransactionRequest = op_alloy_rpc_types::OpTransactionRequest; type TransactionResponse = op_alloy_rpc_types::Transaction; type ReceiptResponse = op_alloy_rpc_types::OpTransactionReceipt; type HeaderResponse = alloy_rpc_types_eth::Header; type BlockResponse = alloy_rpc_types_eth::Block; } ``` ```rust let provider = ProviderBuilder::new() .network::() // [!code hl] .connect_http("http://localhost:8545"); ``` # Signers and `EthereumWallet` A signer owns or delegates access to signing material. A network wallet selects a signer for a transaction and turns the network's unsigned transaction into a signed envelope. Keeping these roles separate lets the same provider work with local keys, hardware devices, or remote KMS services. ## Signer traits The [`Signer`](https://docs.rs/alloy-signer/latest/alloy_signer/trait.Signer.html) trait signs hashes, messages, and EIP-712 typed data. Transaction signing also uses [`TxSigner`](https://docs.rs/alloy-network/latest/alloy_network/trait.TxSigner.html), which exposes the signer address and signs a network transaction in place. Most applications do not call the transaction trait directly. They put a signer in an `EthereumWallet`, attach that wallet to `ProviderBuilder`, and let the wallet filler sign prepared transactions. ## Available integrations | Signer | `alloy` feature | Configuration | Runnable example | | --- | --- | --- | --- | | Private key | `signer-local` | key string or generated key | [Private key](https://alloy.rs/examples/wallets/private_key_signer) | | Mnemonic | `signer-mnemonic` | phrase, derivation path, optional password | [Mnemonic](https://alloy.rs/examples/wallets/mnemonic_signer) | | Encrypted keystore | `signer-keystore` | keystore file and password | [Create](https://alloy.rs/examples/wallets/create_keystore), [load](https://alloy.rs/examples/wallets/keystore_signer) | | YubiHSM | `signer-yubihsm` | connector and key ID | [YubiHSM](https://alloy.rs/examples/wallets/yubi_signer) | | AWS KMS | `signer-aws` | AWS credentials, region, key ID | [AWS](https://alloy.rs/examples/wallets/aws_signer) | | GCP KMS | `signer-gcp` | Google credentials and KMS key version | [GCP](https://alloy.rs/examples/wallets/gcp_signer) | | Ledger | `signer-ledger` | device transport, derivation path, chain ID | [Ledger](https://alloy.rs/examples/wallets/ledger_signer) | | Trezor | `signer-trezor` | device transport, derivation path, chain ID | [Trezor](https://alloy.rs/examples/wallets/trezor_signer) | | Turnkey | `signer-turnkey` | Turnkey organization, key, and API credentials | [API docs](https://docs.rs/alloy-signer-turnkey/latest/alloy_signer_turnkey/) | `signer-local` is part of the default `essentials` set. The other integrations are opt-in. Some local capabilities, including mnemonics and keystores, also have their own feature because they add dependencies or platform requirements. ## Attach a signer to a provider Read secrets from a secret manager or environment rather than source code: ```rust use alloy::{ network::EthereumWallet, providers::ProviderBuilder, signers::local::PrivateKeySigner, }; # async fn run() -> Result<(), Box> { let signer: PrivateKeySigner = std::env::var("PRIVATE_KEY")?.parse()?; let signer_address = signer.address(); let wallet = EthereumWallet::new(signer); let rpc_url = std::env::var("RPC_URL")?; let provider = ProviderBuilder::new() .wallet(wallet) .connect(&rpc_url) .await?; # let _ = (provider, signer_address); # Ok(()) # } ``` `ProviderBuilder::wallet(signer)` also accepts compatible signer types directly and converts them to the network wallet. Construct `EthereumWallet` explicitly when registering more than one signer or when wallet behavior is part of the application boundary. ## Multiple signers `EthereumWallet::new(signer)` registers the first signer as the default. Add others with `register_signer`; use `register_default_signer` when changing the default. The wallet filler selects a signer as follows: 1. If a transaction has a `from` address, use the signer registered for that address. 2. Otherwise, use the default signer and populate `from` with its address. 3. Return an error if the requested address has no registered signer. See the complete [multi-signer wallet example](https://alloy.rs/examples/wallets/ethereum_wallet), which combines a local key, AWS KMS, and Ledger. Prefer separate wallets or providers when accounts have different authorization, retry, audit, or rate-limit policies. A large shared wallet can hide which external system will be contacted for a given transaction. ## Chain ID and transaction intent Remote and hardware signer constructors may accept a chain ID. The provider's fillers also populate and validate transaction fields. Configure the signer and provider for the same chain, and check the connected chain ID at startup before allowing writes. Always review or log safe transaction intent before asking an interactive or remote signer to sign: sender, chain ID, destination, value, method selector, gas bounds, and nonce. Never log the private key, mnemonic, keystore password, cloud credential, or raw secrets returned by a signing service. ## Message and typed-data signing Signing a message is not the same as signing a transaction. Use the signer methods directly for messages and EIP-712 data, and verify with the matching recovery rules. See [sign and verify message](https://alloy.rs/examples/wallets/sign_message) and [Permit hash signing](https://alloy.rs/examples/wallets/sign_permit_hash). Enable the `eip712` feature when the selected signer integration requires typed-data support. Check the concrete signer documentation because not every hardware or remote backend supports every signing mode. ## Secret-handling checklist * Keep development keys clearly separated from funded accounts. * Use a secret manager or protected environment injection in production. * Give cloud KMS identities only the key permissions they need. * Pin the expected chain ID and verify it before signing. * Apply human or policy approval for high-value operations. * Zeroize or drop plaintext secret buffers as soon as practical. * Never commit example credentials, even if an account is believed to be empty. # Testing Alloy applications Use the smallest test environment that exercises the behavior you own. Alloy supports deterministic mocked RPC calls, local execution clients, forked chain state, and explicit live-network tests. | Test level | Best for | External requirements | | --- | --- | --- | | Mock transport | request shape, response handling, error paths | none | | Local Anvil | transactions, contracts, mining, node controls | `anvil` binary | | Local Geth or Reth | client-specific and operational APIs | matching client binary | | Forked node | behavior against existing contracts and state | node binary plus upstream RPC | | Live RPC | provider compatibility and deployment smoke tests | credentials, network, funded account if writing | ## Mock a provider `Asserter` supplies a FIFO queue of serialized successes and JSON-RPC failures to a mock transport. This keeps unit tests offline and makes error cases deterministic. ```rust use alloy::{ providers::{Provider, ProviderBuilder}, transports::mock::Asserter, }; # async fn run() -> Result<(), Box> { let asserter = Asserter::new(); let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone()); asserter.push_success(&42_u64); assert_eq!(provider.get_block_number().await?, 42); asserter.push_failure_msg("rate limited"); let error = provider.get_block_number().await.unwrap_err(); assert_eq!(error.as_error_resp().unwrap().message, "rate limited"); # Ok(()) # } ``` Push responses in the exact order the code will request them. A mock validates your client logic; it does not prove that a real node accepts the request or returns the same shape. See the runnable [mock provider example](https://alloy.rs/examples/providers/mocking). For application code, accept `impl Provider`, a generic `P: Provider`, or a narrow trait owned by the application. This allows a mock provider without hiding every call behind dynamic dispatch. ## Start a local Anvil provider Enable `provider-anvil-node` to use the `ProviderBuilder` helpers. Install Foundry separately and ensure `anvil` is on `PATH`. ```rust use alloy::providers::{ext::AnvilApi, ProviderBuilder}; # async fn run() -> Result<(), Box> { let provider = ProviderBuilder::new() .connect_anvil_with_config(|anvil| anvil.chain_id(31_337).block_time(1)); let info = provider.anvil_node_info().await?; assert_eq!(info.environment.chain_id, 31_337); # Ok(()) # } ``` The node process is stopped when its owning handle or provider state is dropped. Use dynamically assigned ports for parallel tests and avoid assuming a globally running node. The [node-binding examples](https://alloy.rs/examples/node-bindings/README) also cover Anvil deployment and storage overrides, plus local Geth and Reth processes. ## Fork existing state Fork tests are useful for integration with deployed contracts, but they are not deterministic by default. Read the upstream endpoint from `RPC_URL` and pin a block number whenever the test permits: ```rust use alloy::providers::ProviderBuilder; # fn provider() -> Result> { let rpc_url = std::env::var("RPC_URL")?; let provider = ProviderBuilder::new().connect_anvil_with_config(|anvil| { anvil.fork(rpc_url).fork_block_number(20_000_000_u64) }); # Ok(provider) # } ``` A pinned height stabilizes state but still depends on upstream availability and archive access. Use a fixture or mock for unit tests, and reserve forks for cases where real bytecode and storage are the point of the test. ## Client-specific tests Use `alloy-node-bindings` to start Geth, Reth, or Anvil when testing an extension namespace or client-specific behavior. The binding does not install the binary. Pin the client version in CI and skip with an explicit message when a developer has not installed an optional binary. Do not treat one client as proof of compatibility with every other client. Run a small matrix for the JSON-RPC methods your library promises to support. ## Live-network tests Keep live RPC tests outside the default offline suite. Require explicit environment variables, avoid shared public endpoints, and fail early with an actionable message when configuration is missing. Read-only smoke tests should assert stable invariants; write tests should use a dedicated ephemeral account and bounded funds. ## CI recommendations * Run mock tests and `cargo check --all-targets` on every change. * Run deterministic local-node tests when the required binary is provisioned in CI. * Pin fork block numbers, node versions, dependency versions, and the Rust toolchain. * Serialize tests that mutate one shared node, or give each test its own node and ports. * Set timeouts so a missing block, device, or endpoint does not hang the job. * Mark tests that need credentials, hardware, or paid services and run them in protected jobs. * Never expose RPC tokens, private keys, or cloud credentials in test output. # RPC Provider Abstractions Alloy offers *Provider Wrapping* as a design pattern that lets you extend or customize the behavior of a Provider by encapsulating it inside another object. There are several reasons why you would want create your own RPC provider abstractions, for example to simplify complex workflows, or build more intuitive interfaces for particular use cases (like deployment, data indexing, or trading). Let's dive into an example: Imagine you have multiple contracts that need to be deployed and monitored. Rather than repeating the same boilerplate code throughout your application, you can create specialized abstractions that wrap the Provider. Your `Deployer` struct ingests the `Provider` and the bytecode to deploy contracts and interact with them. More on this in the example snippets below. There are two ways to ways to implement provider wrapping, both offer different trade-offs depending on your use case: 1. Using Generics (`P: Provider`): Preserves type information and enables static dispatch 2. Using Type Erasure (`DynProvider`): Simplifies types at the cost of some runtime overhead ## 1. Using generics `P: Provider` The ideal way is by using the `P: Provider` generic on the encapsulating type. This approach Preserves full type information and static dispatch, though can lead to complex type signatures and handling generics. This is depicted by the following [example](https://alloy.rs/examples/providers/wrapped_provider). Use generics when you need maximum performance and type safety, especially in library code. ```rust [wrapped_provider.rs] // [!include ~/snippets/providers/examples/wrapped_provider.rs] ``` During this approach the compiler creates a unique `Deployer` struct for each Provider type you use static dispatch with slightly better runtime overhead. Use this approach when performance is critical, type information is valuable e.g. when creating library code or working with embedded systems. Type information is valuable: You need to know the exact Provider type for specialized behavior ## 2. Using Type Erasure `DynProvider` Use DynProvider when you prioritize simplicity and flexibility, such as in application code where the performance difference is negligible. [`DynProvider`](https://alloy.rs/examples/providers/dyn_provider) erases the type of a provider while maintaining its core functionality. ```rust [dyn_provider.rs] // [!include ~/snippets/providers/examples/dyn_provider.rs] ``` With `DynProvider` we use dynamic dispatch, accept a slightly slower runtime overhead but can avoid dealing with generics. Use this approach when you prefer simplicity over speed speed, minimise compile and binary size or want to create heterogeneous collections. ## `Provider` does not require `Arc` You might be tempted to wrap a `Provider` in `Arc` to enable sharing and cloning: ```rust #[derive(Clone)] struct MyProvider { inner: Arc

, // Unnecssary } ``` This is actually unnecessary because Alloy's Providers already implement internal reference counting. Instead, simply add the `Clone` bound when needed: ```rust struct MyProvider { inner: P, } ``` This eliminates common boilerplate and prevents potential performance issues from double Arc-ing. # Building a High-Priority Transaction Queue with Alloy Fillers In this guide, we will explore more advanced use cases of Alloy Providers APIs. We will cover non-standard ways to instantiate and customize providers and deep dive into custom layers and fillers implementations. We have a lot to cover, so let's get started! ## Fillers Fillers decorate a Provider, and hook into the transaction lifecycle filling details before they are sent to the network. We can use fillers to build a transaction preprocessing pipeline, "filling" all the missing properties such as `nonce`, `chain_id`, `max_fee_per_gas`, and `max_priority_fee_per_gas` etc. Since, [alloy `v0.11.0`](https://github.com/alloy-rs/alloy/releases/tag/v0.11.0) the most essential fillers are enabled by default when building a provider using `ProviderBuilder::new()`. These core fillers are termed as [`RecommendedFillers`](https://docs.rs/alloy-provider/latest/alloy_provider/fillers/type.RecommendedFiller.html) and consists of the following: * [`NonceFiller`](https://docs.rs/alloy-provider/latest/alloy_provider/fillers/struct.NonceFiller.html): Fills the `nonce` field of a transaction with the next available nonce. * [`ChainIdFiller`](https://docs.rs/alloy-provider/latest/alloy_provider/fillers/struct.ChainIdFiller.html): Fills the `chain_id` field of a transaction with the chain ID of the provider. * [`GasFiller`](https://docs.rs/alloy-provider/latest/alloy_provider/fillers/struct.GasFiller.html): Fills the gas related fields such as `gas_price`, `gas_limit`, `max_fee_per_gas` and `max_priority_fee_per_gas` fields of a transaction with the current gas price. * [`BlobGasFiller`](https://docs.rs/alloy-provider/latest/alloy_provider/fillers/struct.BlobGasFiller.html): Fills the `max_fee_per_blob_gas` field for EIP-4844 transactions. In a world without the above fillers, sending a simple transfer transaction looks like the following: [ `examples/basic_provider.rs`](https://alloy.rs/examples/providers/basic_provider) :::code-group ```rust [basic_provider.rs] // [!include ~/snippets/providers/examples/basic_provider.rs] ``` ```bash [output] Balance before: 0 Balance after: 1 ``` ::: In this example, we sent 1 wei from `alice` (default anvil account) to `bob`. You can see that a lot of boilerplate is involved in building the transaction data. We must manually check the account's current `nonce`, network fees, `gas_limit`, and `chain_id`. If we omitted any of the transaction properties we'd see an error like: ```text Caused by: missing properties: [("Wallet", ["nonce", "gas_limit", "max_fee_per_gas", "max_priority_fee_per_gas"])] ``` Now, let's see how using `RecommendedFillers` improves this: [ `examples/recommended.rs`](https://alloy.rs/examples/fillers/recommended_fillers) ```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: {}\nBalance after: {}", bob_balance_before, bob_balance_after ); Ok(()) } ``` We've removed ~15 LOC while preserving the same functionality! Most heavy lifting was taken over by recommended fillers that are enabled upon `ProviderBuilder::new()` and the `connect_anvil_with_wallet` method. `connect_anvil_with_wallet` is a helper method that implicitly spawns the Anvil process and enables the [`WalletFiller`](https://docs.rs/alloy/latest/alloy/providers/fillers/struct.WalletFiller.html) that sets the `from` field based on the wallet's signer address and signs the transaction. This explains why we could omit filling out `nonce`, `chain_id`, `max_fee_per_gas` and `max_priority_fee_per_gas` in the second example. In case you want you want to disable the default fillers you can do so by calling [`disable_recommended_fillers()`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.disable_recommended_fillers) on the `ProviderBuilder`, and setting the fillers of your choice manually. Alloy comes with builder methods for automatically applying fillers to providers: * [ `wallet`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.wallet) - set `from` based on the wallet's signer address * [ `fetch_chain_id`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.fetch_chain_id) - automatically set `chain_id` based on data from the provider * [ `with_chain_id`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.with_chain_id) - automatically set `chain_id` based on provided value * [ `with_simple_nonce_management`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.with_simple_nonce_management) - set `nonce` based on txs count from provider * [ `with_cached_nonce_management`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.with_cached_nonce_management) - like above but with caching * [ `with_nonce_management`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.with_nonce_management) - provided custom `nonce` management strategy * [ `with_gas_estimation`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.with_gas_estimation) - set gas prices based on data from the provider Let's go beyond the basics and implement a custom filler to better understand the inner workings. ## Implementing a custom filler Submitting txs with a high-enough gas price, to land in the next block is a common use case. We will implement a custom filler to automatically check and fill the correct gas price. We will query the free [Blocknative Gas API](https://docs.blocknative.com/gas-prediction/gas-platform) to check the recommended gas price, and land our payload in the next block. We will be working with the following API output: :::code-group ```bash [request] curl https://api.blocknative.com/gasprices/blockprices ``` ```json [response] { "system": "ethereum", "network": "main", "unit": "gwei", "maxPrice": 172.0, "currentBlockNumber": 21465702, "msSinceLastBlock": 14416, "blockPrices": [ { "blockNumber": 21465703, "estimatedTransactionCount": 67, "baseFeePerGas": 36.23398572, "blobBaseFeePerGas": 25.17758517, "estimatedPrices": [ { "confidence": 99, "price": 36.53, "maxPriorityFeePerGas": 0.29, "maxFeePerGas": 72.76 }, { "confidence": 95, "price": 36.3, "maxPriorityFeePerGas": 0.062, "maxFeePerGas": 72.53 }, { "confidence": 90, "price": 36.29, "maxPriorityFeePerGas": 0.057, "maxFeePerGas": 72.52 }, { "confidence": 80, "price": 36.28, "maxPriorityFeePerGas": 0.047, "maxFeePerGas": 72.51 }, { "confidence": 70, "price": 36.27, "maxPriorityFeePerGas": 0.037, "maxFeePerGas": 72.5 } ] } ] } ``` ::: It shows gas prices needed to commit tx in the next block, with a specified confidence. To build a custom filler, you have to implement a [`TxFiller`](https://docs.rs/alloy-provider/latest/alloy_provider/fillers/trait.TxFiller.html) trait. Here's a sample implementation for our `UrgentQueue` filler: [`examples/urgent_filler.rs`](https://alloy.rs/examples/fillers/urgent_filler) ```rust #[derive(Clone, Debug, Default)] pub struct UrgentQueue { client: Client, } impl UrgentQueue { pub fn new() -> Self { Self { client: Client::new(), } } } #[derive(Debug)] pub struct GasPriceFillable { max_fee_per_gas: u128, max_priority_fee_per_gas: u128, } impl TxFiller for UrgentQueue { type Fillable = GasPriceFillable; fn status(&self, tx: &::TransactionRequest) -> FillerControlFlow { if tx.max_fee_per_gas().is_some() && tx.max_priority_fee_per_gas().is_some() { FillerControlFlow::Finished } else { FillerControlFlow::Ready } } fn fill_sync(&self, _tx: &mut SendableTx) {} async fn fill( &self, fillable: Self::Fillable, mut tx: SendableTx, ) -> TransportResult> { if let Some(builder) = tx.as_mut_builder() { builder.set_max_fee_per_gas(fillable.max_fee_per_gas); builder.set_max_priority_fee_per_gas(fillable.max_priority_fee_per_gas); } else { panic!("Expected a builder"); } Ok(tx) } async fn prepare

( &self, _provider: &P, _tx: &::TransactionRequest, ) -> TransportResult where P: Provider, { println!("Fetching gas prices from Blocknative"); let data = match self.client.get("https://api.blocknative.com/gasprices/blockprices").send().await { Ok(res) => res, Err(e) => { return Err(RpcError::Transport(TransportErrorKind::Custom(Box::new( std::io::Error::new( std::io::ErrorKind::Other, format!("Failed to fetch gas price, {}", e), ), )))); } }; let body = data.text().await.unwrap(); let json = serde_json::from_str::(&body).unwrap(); let prices = &json["blockPrices"][0]["estimatedPrices"][0]; let max_fee_per_gas = (prices["maxFeePerGas"].as_f64().unwrap() * 1e9) as u128; let max_priority_fee_per_gas = (prices["maxPriorityFeePerGas"].as_f64().unwrap() * 1e9) as u128; let fillable = GasPriceFillable { max_fee_per_gas, max_priority_fee_per_gas }; Ok(fillable) } } ``` The above implementation fetches gas prices from the Blocknative API and injects them into our transaction. With this implementation, we'll have 99% confidence that our transaction will land in the next block. Here's how you can build the provider with the `UrgentQueue` filler: [ `examples/urgent_filler.rs`](https://alloy.rs/examples/fillers/urgent_filler) ```rust let provider = ProviderBuilder::new() .filler(UrgentQueue::default()) .connect_anvil_with_wallet(); ``` The rest of the example remains the same. It shows a great feature of fillers, i.e. composability. They are processed in reverse order, meaning that our `UrgentQueue` filler will take precedence over the built-in `GasFiller`. ## Summary Fillers are helpful in reworking txs submission logic, depending on any custom conditions. The presented `UrgentQueue` implementation is relatively basic, but should serve you as a starting point for building your custom fillers. # Customizing RPC Communication with Alloy's Layers In the [previous guide](https://alloy.rs/guides/fillers), we covered [Alloy fillers](https://alloy.rs/rpc-providers/understanding-fillers). This time we'll discuss how to use [Alloy layers](https://alloy.rs/examples/layers/README) to customize HTTP-related aspects of RPC client communication. ## Layers 101 To better understand layers, we first have to explore the [Tower crate](https://github.com/tower-rs/tower). It's a basic building block for many popular Rust tools, including [Reqwest](https://github.com/seanmonstar/reqwest), [Hyper](https://github.com/hyperium/hyper), [Axum](https://github.com/tokio-rs/axum), and, of course, Alloy. What all these crates have in common is that they work with HTTP request/response communication. That's where Tower comes into play. It's an opinionated framework for constructing pipelines for `Request -> Response` transformations. Tower also comes with a set of built-in layers that add functionality like rate limiting, compression, retry logic, logging, etc. Check out [this classic blog post](https://tokio.rs/blog/2021-05-14-inventing-the-service-trait) for a more in-depth explanation of the origins of the Tower `Service` trait. To better understand `Service` and `Layer` traits, let's implement a barebones `Request/Response` processing pipeline using Tower. ### Basic tower service and layer implementation For the sake of simplicity, we're implementing a basic tower service that prepends a "Hello " to the incoming request message. A custom `DelayLayer` will be added to this service using the [`ServiceBuilder`](https://docs.rs/tower/latest/tower/struct.ServiceBuilder.html). Here's the implementation of our [`DelayLayer`](https://alloy.rs/examples/layers/delay_layer): ```rust struct DelayLayer { delay: Duration, } impl DelayLayer { fn new(delay: Duration) -> Self { Self { delay } } } impl Layer for DelayLayer { type Service = DelayService; fn layer(&self, service: S) -> Self::Service { DelayService { service, delay: self.delay, } } } struct DelayService { service: S, delay: Duration, } impl Service for DelayService where S: Service + Send, S::Future: Send + 'static, { type Response = S::Response; type Error = S::Error; type Future = BoxFuture<'static, Result>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { self.service.poll_ready(cx) } fn call(&mut self, req: Request) -> Self::Future { let delay = self.delay; let future = self.service.call(req); Box::pin(async move { sleep(delay).await; future.await }) } } ``` It's a bit verbose for its minimal functionality. Please refer to the [*inventing the service layer* post](https://tokio.rs/blog/2021-05-14-inventing-the-service-trait) to understand the origin of this boilerplate better. The core functionality of our layer is implemented in the `call` method. You can see that it wraps the unresolved future and delays it by calling `sleep`. This implementation is similar to how we can modify the alloy `Request/Response` cycle. It's worth noting that the `DelayLayer` is generic over the `Service` allowing composibilty/layering with other services. Here's our `DelayLayer` being added added to a basic tower service: :::code-group ```rust [tower_basic.rs] #[tokio::main] async fn main() { let mut service = ServiceBuilder::new() .layer(DelayLayer::new(Duration::from_secs(5))) .service(MyService); let response = service.call("Alice".to_string()).await; match response { Ok(msg) => println!("{}", msg), Err(_) => eprintln!("An error occurred!"), } } ``` ```rust [my_service.rs] struct MyService; impl Service for MyService { type Response = String; type Error = (); type Future = Ready>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: String) -> Self::Future { ready(Ok(format!("Hello {}!", req))) } } ``` ::: Running this example outputs *"Hello Alice!"* after a 5-second delay. Layers might sound similar to the fillers, but there's a crucial difference. Fillers can be used to modify the `TransactionRequest` object before it is submitted. Layers work within the `Request/Response` scope, allowing us to customize logic before and after sending the RPC request. If you're familiar with the Alloy predecessor Ethers.rs, you've probably noticed that it used [middleware](https://www.gakonst.com/ethers-rs/middleware/middleware.html) to achieve the same result. ## How to use layers in Alloy Now that we've covered the basics let's see how layers fit within the Alloy stack. In this context, a `Service` is the Alloy `Provider`, and we can tweak how it sends RPC requests and handles responses. Let's start with a simple example of reusing our `DelayLayer` for Alloy providers. This particular example does not have the best practical use case, but it shows that some generic layers can be reused regardless of the underlying `Service` `Request` type: [ `examples/alloy_delay.rs`](https://alloy.rs/examples/layers/delay_layer) ```rust #[tokio::main] async fn main() -> Result<()> { let anvil = Anvil::new().try_spawn()?; let signer: PrivateKeySigner = anvil.keys()[0].clone().into(); let client = ClientBuilder::default() .layer(DelayLayer::new(Duration::from_secs(1))) .http(anvil.endpoint().parse()?); let provider = ProviderBuilder::new() .wallet(signer) .connect_client(client); 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: {}\nBalance after: {}", bob_balance_before, bob_balance_after ); Ok(()) } ``` Running this example would output: ```text # After a 1 second delay Balance before: 0 Balance after: 1 ``` You'll notice a considerable delay before it executes. Let's add logging to better understand where it's coming from. ### Using logging layer for Alloy provider ```rust struct LoggingLayer; impl Layer for LoggingLayer { type Service = LoggingService; fn layer(&self, inner: S) -> Self::Service { LoggingService { inner } } } #[derive(Debug, Clone)] struct LoggingService { inner: S, } impl Service for LoggingService where S: Service, S::Future: Send + 'static, S::Response: Send + 'static + Debug, S::Error: Send + 'static + Debug, { type Response = S::Response; type Error = S::Error; type Future = Pin> + Send>>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { self.inner.poll_ready(cx) } fn call(&mut self, req: RequestPacket) -> Self::Future { println!("Request: {req:?}"); let fut = self.inner.call(req); Box::pin(async move { let res = fut.await; println!("Response: {res:?}"); res }) } } ``` You can notice that it's very similar to the `DelayLayer`. Core logic lives in the `call` method, and instead of delaying requests with `sleep`, we use `tracing::info!` calls to log them. Here's how you can connect it to the provider: [ `examples/alloy_logging.rs`](https://alloy.rs/examples/layers/logging_layer) ```rust // Request/Response modifying layers should be added to the RPC-client let client = ClientBuilder::default() .layer(DelayLayer::new(Duration::from_secs(1))) .layer(LoggingLayer) // Previously, on_http .connect_http(anvil.endpoint().parse()?); let provider = ProviderBuilder::new() .wallet(signer) .connect_client(client); ``` ![Alloy logging](https://alloy.rs/guides-images/layers/alloy_logs.png) You can see that our simple example triggered various RPC requests: `eth_blockNumber`, `eth_getBlockByNumber`, `eth_chainId`, `eth_transactionCount`, `eth_getBalance`, and more. Thanks to the custom layer we can fine-tune the `LoggingLayer` policy and for example only log RPC calls sending transactions: ```rust fn call(&mut self, req: RequestPacket) -> Self::Future { if let RequestPacket::Single(req) = &req { if req.method() == "eth_sendTransaction" || req.method() == "eth_sendRawTransaction" { tracing::info!("Request: {req:?}"); }; } let fut = self.inner.call(req); Box::pin(fut) } ``` Running this reworked example produces a much cleaner output: ![Alloy logging txs](https://alloy.rs/guides-images/layers/alloy_logs_tx.png) You can see that layers provide powerful low-level control over how the provider handles RPC calls. ## Summary Alloy layers combined with fillers allow for elaborate customization of transaction dispatch logic. Mastering these APIs could save you a lot of manual tweaking and enable building robust provider pipelines fine-tuned to your application requirements. ## RPC Provider A [`Provider`](https://docs.rs/alloy/latest/alloy/providers/trait.Provider.html) is an abstraction of a connection to the Ethereum network, providing a concise, consistent interface to standard Ethereum node functionality. ### Provider Builder Pattern The correct way of creating a [`Provider`](https://docs.rs/alloy/latest/alloy/providers/trait.Provider.html) is through the [`ProviderBuilder`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html), a [builder](https://rust-unofficial.github.io/patterns/patterns/creational/builder.html). Alloy provides concrete transport implementations for [`HTTP`](https://alloy.rs/rpc-providers/http-provider), [`WS` (WebSockets)](https://alloy.rs/rpc-providers/ws-provider) and [`IPC` (Inter-Process Communication)](https://alloy.rs/rpc-providers/ipc-provider), as well as higher level transports which wrap a single or multiple transports. The [`connect`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.connect) method on the [`ProviderBuilder`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html) will automatically determine the connection type (`Http`, `Ws` or `Ipc`) depending on the format of the URL. The examples use environment variables for endpoints so credentials are not committed to source control. Set `RPC_URL` to an HTTP endpoint or `WS_URL` to a WebSocket endpoint before running them. ```rust showLineNumbers //! Example of setting up a provider using the `.connect` method. use alloy::providers::{Provider, ProviderBuilder}; // [!code focus] use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { // Instantiate a provider using a caller-supplied endpoint. let rpc_url = std::env::var("RPC_URL")?; // [!code focus] let provider = ProviderBuilder::new().connect(&rpc_url).await?; // [!code focus] Ok(()) } ``` In order to instantiate a provider in synchronous settings use [`connect_http`](https://alloy.rs/rpc-providers/http-provider). ## HTTP Provider The `Http` provider establishes an HTTP connection with a node, allowing you to send JSON-RPC requests to the node to fetch data, simulate calls, send transactions and much more. ### Initializing an Http Provider The recommended way of initializing a `Http` provider is by using the [`connect_http`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.connect_http) method on the [`ProviderBuilder`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html). ```rust //! Example of creating an HTTP provider using the `connect_http` method on the `ProviderBuilder`. use alloy::providers::{Provider, ProviderBuilder}; // [!code focus] 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 = std::env::var("RPC_URL")?.parse()?; // Create a provider with the HTTP transport using the `reqwest` crate. let provider = ProviderBuilder::new().connect_http(rpc_url); // [!code focus] Ok(()) } ``` ## WS Provider The `Ws` provider establishes an WebSocket connection with a node, allowing you to send JSON-RPC requests to the node to fetch data, simulate calls, send transactions and much more. The `Ws` provider can be used with any Ethereum node that supports WebSocket connections. This allows programs to interact with the network in real-time without the need for HTTP polling for things like new block headers and filter logs. ### Initializing a `Ws` Provider The recommended way of initializing a `Ws` provider is by using the [`connect_ws`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.connect_ws) method on the [`ProviderBuilder`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html) with a [`WsConnect`](https://docs.rs/alloy/latest/alloy/providers/struct.WsConnect.html) configuration. ```rust //! Example of creating an WS provider using the `connect_ws` method on the `ProviderBuilder`. use alloy::providers::{Provider, ProviderBuilder, WsConnect}; // [!code focus] use std::error::Error; #[tokio::main] async fn main() -> eyre::Result<(), Box> { // Set up the WS transport which is consumed by the RPC client. let rpc_url = "wss://eth-mainnet.g.alchemy.com/v2/your-api-key"; // Create the provider. let ws = WsConnect::new(rpc_url); // [!code focus] let provider = ProviderBuilder::new().connect_ws(ws).await?; // [!code focus] Ok(()) } ``` ### Ws with Authorization Similar to the other providers, you can also establish an authorized connection with a node via websockets. ```rust // [!include ~/snippets/providers/examples/ws_with_auth.rs] ``` ## IPC Provider The [IPC (Inter-Process Communication)](https://en.wikipedia.org/wiki/Inter-process_communication) transport allows our program to communicate with a node over a local [Unix domain socket](https://en.wikipedia.org/wiki/Unix_domain_socket) or [Windows named pipe](https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipes). Using the IPC transport allows the ethers library to send JSON-RPC requests to the Ethereum client and receive responses, without the need for a network connection or HTTP server. This can be useful for interacting with a local Ethereum node that is running on the same network. Using IPC [is faster than RPC](https://github.com/0xKitsune/geth-ipc-rpc-bench), however you will need to have a local node that you can connect to. ### Initializing an `Ipc` Provider The recommended way of initializing an `Ipc` provider is by using the [`connect_ipc`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html#method.connect_ipc) method on the [`ProviderBuilder`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html) with an [`IpcConnect`](https://docs.rs/alloy/latest/alloy/providers/struct.IpcConnect.html) configuration. ```rust //! Example of creating an IPC provider using the `connect_ipc` method on the `ProviderBuilder`. use alloy::providers::{IpcConnect, Provider, ProviderBuilder}; // [!code focus] use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { // Set up the IPC transport which is consumed by the RPC client. let ipc_path = "/tmp/reth.ipc"; // Create the provider. let ipc = IpcConnect::new(ipc_path.to_string()); // [!code focus] let provider = ProviderBuilder::new().connect_ipc(ipc).await?; // [!code focus] Ok(()) } ``` # Subscriptions and polling Alloy offers three event-streaming patterns. Choose based on transport support and whether the consumer must resume from a known block. | Pattern | Transport | Starts from history | Reorg handling | | --- | --- | --- | --- | | `subscribe_*` | WebSocket or IPC | No | Delivers what the node publishes | | `watch_*` | HTTP, WebSocket, or IPC | No | Follows the node filter | | `watch_*_from` | HTTP, WebSocket, or IPC | Yes | Ordered or canonical variants | The node must support the corresponding JSON-RPC method. Hosted providers sometimes disable filters or individual subscription kinds. ## Live subscriptions Subscriptions use `eth_subscribe` and require a pubsub transport. Enable `provider-ws` or `provider-ipc` when using the `alloy` meta-crate. ```rust use alloy::providers::{Provider, ProviderBuilder, WsConnect}; use futures_util::StreamExt; # async fn run() -> Result<(), Box> { let ws_url = std::env::var("WS_URL")?; let provider = ProviderBuilder::new() .connect_ws(WsConnect::new(ws_url)) .await?; let subscription = provider.subscribe_blocks().await?; let mut blocks = subscription.into_stream(); while let Some(header) = blocks.next().await { println!("new block: {}", header.number); } # Ok(()) # } ``` Provider methods include `subscribe_blocks`, `subscribe_full_blocks`, `subscribe_logs`, and pending-transaction subscriptions. Use `.channel_size(n)` on a subscription builder when the default channel capacity does not fit the workload. A larger channel absorbs bursts but also keeps more data in memory; it does not replace timely processing. See the runnable [block](https://alloy.rs/examples/subscriptions/subscribe_blocks), [log](https://alloy.rs/examples/subscriptions/subscribe_logs), and [pending transaction](https://alloy.rs/examples/subscriptions/subscribe_pending_transactions) examples. ## JSON-RPC filter polling The `watch_*` methods create a node-side filter and repeatedly call `eth_getFilterChanges`. This is the portable choice for HTTP: ```rust use alloy::providers::Provider; use futures_util::{stream, StreamExt}; # async fn run(provider: impl Provider) -> Result<(), Box> { let poller = provider.watch_blocks().await?; let mut hashes = poller.into_stream().flat_map(stream::iter); while let Some(hash) = hashes.next().await { println!("new block: {hash}"); } # Ok(()) # } ``` Polling consumes an RPC request on every interval even when nothing changes. Configure the poller interval for the chain and provider limits, and avoid creating many overlapping filters. ## Resumable historical streams An indexer should persist its last processed block and resume with `watch_blocks_from` or `watch_logs_from`. These streams fetch each height in order, catch up to the head, and continue polling. * `watch_blocks_from` and `watch_logs_from` never emit the same height twice, but do not reconcile a later reorg. * `watch_canonical_blocks_from` and `watch_canonical_logs_from` emit canonical added and removed events so a consumer can roll state backward and forward. * Configure the block tag, poll interval, RPC concurrency, and maximum reorg depth on the returned builder as the workload requires. Use a finalized or safe block tag when latency is less important than reorg risk. If downstream state must follow the chain head, store both block number and hash and implement the removed-event path. ## Reconnection is not replay Alloy pubsub transports reconnect and restore subscriptions after retryable connection failures. Events produced while the connection is unavailable can still be absent from the live stream. Applications that require gap-free processing should track progress and backfill the missing block range before returning to the live head. Configure WebSocket connection retry count and base interval with [`ConnectionConfig`](https://alloy.rs/rpc-providers/reliability#connection-and-reconnection). Handle the stream ending as an application event: reconnect, backfill, and resubscribe rather than silently waiting. # Reliability and retries Connection establishment, a JSON-RPC request, and transaction confirmation are different failure boundaries. Configure them separately so retry behavior is intentional. ## Connection and reconnection `ConnectionConfig` controls built-in connection settings. For WebSockets, the retry interval is the base of a capped exponential reconnect backoff. ```rust use alloy::providers::{ConnectionConfig, ProviderBuilder}; use std::time::Duration; # async fn run() -> Result<(), Box> { let ws_url = std::env::var("WS_URL")?; let config = ConnectionConfig::new() .with_max_retries(8) .with_retry_interval(Duration::from_secs(1)); let provider = ProviderBuilder::new() .connect_with_config(&ws_url, config) .await?; # let _ = provider; # Ok(()) # } ``` The same configuration can carry an `Authorization` header. Prefer environment-based credentials and never put provider tokens in source or committed URLs. Connection retries do not retry every failed RPC response. Apply a request layer for that. ## Request retries and rate limits `RetryBackoffLayer` wraps the RPC transport. Its default policy retries responses Alloy recognizes as transient, including common rate-limit and temporary-unavailability responses, while honoring a server backoff hint when one is present. ```rust use alloy::{ providers::ProviderBuilder, rpc::client::RpcClient, transports::layers::RetryBackoffLayer, }; # fn build(rpc_url: alloy::transports::http::reqwest::Url) { let max_retries = 6; let initial_backoff_ms = 250; let compute_units_per_second = 100; let retry = RetryBackoffLayer::new( max_retries, initial_backoff_ms, compute_units_per_second, ); let client = RpcClient::builder().layer(retry).http(rpc_url); let provider = ProviderBuilder::new().connect_client(client); # let _ = provider; # } ``` The compute-unit setting spaces retries to avoid immediately exceeding the service limit again. Tune it to the provider plan; it is not a universal requests-per-second value. For application-specific errors, implement `RetryPolicy` or extend `RateLimitRetryPolicy`. Be conservative with state-changing or non-standard methods: retry only when duplicate submission is safe and the failure is known to be transient. See the runnable [retry layer example](https://alloy.rs/examples/layers/retry_layer). ## Multiple endpoints `FallbackLayer` ranks a collection of transports and can route around an unhealthy endpoint. Use it when endpoints are equivalent for the operation. Reads from nodes at different heads can return different data, and transaction submission to multiple nodes can have provider-specific effects. See the runnable [fallback layer example](https://alloy.rs/examples/layers/fallback_layer). The example endpoint list should come from application configuration rather than source code. ## Timeouts Alloy does not impose one application-wide timeout. Wrap individual calls with the async runtime timeout appropriate to the operation: ```rust use alloy::providers::Provider; use std::time::Duration; # async fn run(provider: impl Provider) -> Result<(), Box> { let block_number = tokio::time::timeout( Duration::from_secs(10), provider.get_block_number(), ) .await??; # let _ = block_number; # Ok(()) # } ``` Pending transactions have a separate confirmation timeout: ```rust # use std::time::Duration; # async fn run(pending: alloy::providers::PendingTransactionBuilder) -> Result<(), Box> { let receipt = pending .with_required_confirmations(2) .with_timeout(Some(Duration::from_secs(60))) .get_receipt() .await?; # let _ = receipt; # Ok(()) # } ``` Timeouts cancel the caller's wait, not the on-chain transaction. Store the transaction hash before waiting so another process can resume receipt tracking. ## Error handling Provider calls return `TransportError`, an RPC error whose variants distinguish: * an error response returned by the JSON-RPC server; * request serialization or response deserialization; * an absent or null response; * HTTP and lower-level transport failures; * a lost backend or unavailable pubsub service. Log the RPC method, endpoint identity, chain ID, request ID, and transaction hash where applicable. Do not log authorization headers, private keys, signed secrets, or full provider URLs containing tokens. Match only the variants the application can recover from; propagate unexpected errors with their source chain intact. ## Production checklist * Set explicit connection, request, and confirmation timeouts. * Bound retries and add jitter or provider-aware backoff where appropriate. * Persist progress before processing long-running block or log streams. * Treat reorgs, duplicate delivery, and endpoint head skew as normal distributed-system behavior. * Record retry counts, latency, error class, and endpoint health. * Test rate limits, disconnects, stale endpoints, and shutdown behavior before deployment. # RPC namespaces The base `Provider` trait exposes the standard Ethereum `eth_*` API. Optional extension traits add client-specific and operational namespaces. Enabling Rust types does not enable a method on the node: the connected client or hosted service must expose that namespace. ## Enable and import an extension For the `alloy` meta-crate, add the provider feature and import its trait: ```sh cargo add alloy --features provider-debug-api ``` ```rust use alloy::providers::{ext::DebugApi, ProviderBuilder}; # async fn run() -> Result<(), Box> { let rpc_url = std::env::var("RPC_URL")?; let provider = ProviderBuilder::new().connect(&rpc_url).await?; // Methods from DebugApi are now available on the provider. let _ = provider; # Ok(()) # } ``` If Rust reports that a method is missing, verify both the feature and the trait import. ## Namespace map | RPC namespace | Provider extension trait | `alloy` feature | Typical use | | --- | --- | --- | --- | | `admin_*` | `AdminApi` | `provider-admin-api` | peers and node information | | Anvil methods | `AnvilApi` | `provider-anvil-api` | account impersonation and test-node controls | | `debug_*` | `DebugApi` | `provider-debug-api` | Geth-style traces and debug operations | | `engine_*` | `EngineApi`, `TestingApi` | `provider-engine-api` | consensus/execution Engine API integration | | MEV and Flashbots methods | `MevApi` | `provider-mev-api` | bundles and private transactions | | `net_*` | `NetApi` | `provider-net-api` | peer count, network ID, listening status | | `trace_*` | `TraceApi` | `provider-trace-api` | OpenEthereum-style traces | | `txpool_*` | `TxPoolApi` | `provider-txpool-api` | pending and queued transaction inspection | The `full` feature includes Anvil, debug, trace, and txpool provider APIs. It does not include admin, engine, MEV, or net APIs. See the [feature flag reference](https://alloy.rs/reference/feature-flags). ## Direct `alloy-provider` features The provider crate also exposes extensions that the `alloy` meta-crate does not currently map to a same-named top-level feature: | `alloy-provider` feature | Extension | | --- | --- | | `rpc-api` | `RpcApi` for `rpc_modules` | | `erc4337-api` | `Erc4337Api` for bundler operations | | `tenderly-api` | `TenderlyApi` | | `tenderly-admin-api` | `TenderlyAdminApi` | Depend on `alloy-provider` directly when one of these is required, and align its version with the rest of the Alloy dependency graph. ## Node compatibility and security Namespace behavior varies by execution client and configuration. Before using an extension: 1. Check the node's enabled modules and authentication requirements. 2. Confirm that the exact method and version are supported by that client release. 3. Keep privileged namespaces such as `admin`, `engine`, `debug`, and test-node controls off public interfaces. 4. Use the concrete types and method documentation in the [`alloy_provider::ext` module](https://docs.rs/alloy-provider/latest/alloy_provider/ext/). Trace APIs are not interchangeable: `debug_*` and `trace_*` use different method families and response types. Engine API methods are fork-versioned and normally require authenticated JWT access. Anvil operations are for controlled development nodes, not general production endpoints. ## Raw JSON-RPC escape hatch When a server method is not modeled by an extension, send a typed request through the provider's RPC client: ```rust use alloy::providers::{Provider, ProviderBuilder}; # async fn run() -> Result<(), Box> { let rpc_url = std::env::var("RPC_URL")?; let provider = ProviderBuilder::new().connect(&rpc_url).await?; let chain_name: String = provider .client() .request_noparams("custom_chainName") .await?; # let _ = chain_name; # Ok(()) # } ``` Prefer a local request/response type over unstructured `serde_json::Value`, and isolate the custom method behind an application trait. If it becomes broadly useful, contribute a typed extension to Alloy. ## Understanding `Fillers` [Fillers](https://docs.rs/alloy/latest/alloy/providers/fillers/index.html) decorate a [`Provider`](https://docs.rs/alloy/latest/alloy/providers/trait.Provider.html), filling transaction details before they are sent to the network. Fillers are used to set the nonce, gas price, gas limit, and other transaction details, and are called before any other layer. ### Recommended Fillers `RecommendedFillers` are enabled by default when initializing the `Provider` using `ProviderBuilder::new`. ```rust // [!include ~/snippets/fillers/examples/recommended_fillers.rs] ``` ### Gas Filler ```rust // [!include ~/snippets/fillers/examples/gas_filler.rs] ``` ### Nonce Filler ```rust // [!include ~/snippets/fillers/examples/nonce_filler.rs] ``` ### Wallet Filler ```rust // [!include ~/snippets/fillers/examples/wallet_filler.rs] ``` ## Crafting Transactions The simplest way to craft transactions is by using the [TransactionRequest](https://docs.rs/alloy-rpc-types/latest/alloy_rpc_types/transaction/struct.TransactionRequest.html) builder with the help of the [TransactionBuilder](https://docs.rs/alloy-network/latest/alloy_network/trait.TransactionBuilder.html). The `TransactionBuilder` provides a convenient interface for setting transaction fields such as recipient, value, gas, data and more, allowing you to easily construct different types of transactions whether you're sending ETH, calling a contract, or deploying a new contract. Here's a short example of crafting a simple ETH transfer request: ```rust showLineNumbers use alloy::{ rpc::types::TransactionRequest, network::TransactionBuilder, primitives::{address, U256}, }; let tx = TransactionRequest::default() .with_to(address!("0x1234567890abcdef1234567890abcdef12345678")) .with_value(U256::from(1000)); ``` This approach ensures your transaction is correctly structured and ready to be signed and submitted to the network. Note that we didn't set `from`, `nonce`, `chain_id`, or any gas related fields. These necessary fields are automatically filled by the `RecommendedFillers` before dispatch making our code less verbose. You can find more details about a transactions lifecycle and `RecommendedFillers` in the [Transaction Lifecycle](https://alloy.rs/transactions/transaction-lifecycle) post. ## Building specific transaction types Alloy supports building a transaction request for all types of transactions via the same `TransactionRequest` builder we used above for crafting an ETH transfer. By default, the `TransactionRequest` attempts to build an [EIP1559](https://eips.ethereum.org/EIPS/eip-1559) transaction. However, you can also build other types of transactions by specifying the required type-specific fields or using specialized builders: * **Legacy transactions:** Set the `gas_price` field. Omit EIP-1559 fields like `max_fee_per_gas` and `max_priority_fee_per_gas`. * **EIP-2930 transactions:** Set the `access_list` field. This creates an access-list transaction. * **EIP-1559 transactions:** Set the `max_fee_per_gas` and `max_priority_fee_per_gas` fields. Omit the `gas_price` field. * **EIP-4844 transaction:** Use the `TransactionBuilder4844` to set blob specific fields using the `.with_blob_sidecar(..)` method. * **EIP-7594 sidecar:** Convert the pooled EIP-4844 sidecar to its PeerDAS cell-proof representation. This remains `TxType = 3`. * **EIP-7702 transaction:** Use the `TransactionBuilder7702` to set the authorization list using the `.with_authorization_list(..)` method. ### Legacy Transactions Setting the `gas_price` field hints the builder to construct a legacy transaction i.e `TxType = 0`. ```rust showLineNumbers use alloy::{ rpc::types::TransactionRequest, network::TransactionBuilder, primitives::{address, U256}, }; let tx = TransactionRequest::default() .with_to(address!("0x1234567890abcdef1234567890abcdef12345678")) .with_value(U256::from(10000)) .with_gas_price(U256::from(100)); // [!code hl] ``` Find the full example [here](https://alloy.rs/transactions/sending-a-legacy-transaction). ### EIP-2930 Transaction [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list transaction (`TxType = 1`) can be built by setting the `access_list` field. You can learn more about the `AccessList` [here](https://docs.rs/alloy-rpc-types-eth/latest/alloy_rpc_types_eth/transaction/struct.AccessList.html). ```rust showLineNumbers use alloy::{ rpc::types::TransactionRequest, network::TransactionBuilder, primitives::{address, U256}, }; // ..snip.. let tx = TransactionRequest::default() .with_to(address!("0x1234567890abcdef1234567890abcdef12345678")) .with_value(U256::from(100)) .with_input(calldata) .with_access_list(access_list); // [!code hl] ``` Find the full example [here](https://alloy.rs/transactions/using-access-lists). ### EIP-1559 Transaction By default the builder attempts to construct an [EIP1559](https://eips.ethereum.org/EIPS/eip-1559) transaction (`TxType = 2`). You can make this explicit by specifying the priority gas fields. ```rust showLineNumbers use alloy::{ rpc::types::TransactionRequest, network::TransactionBuilder, primitives::{address, U256}, }; let tx = TransactionRequest::default() .with_to(address!("0x1234567890abcdef1234567890abcdef12345678")) .with_value(U256::from(10000)) .with_max_fee_per_gas(1000) // [!code hl] .with_max_priority_fee_per_gas(100); // [!code hl] ``` Find the full example [here](https://alloy.rs/transactions/sending-an-EIP-1559-transaction). ### EIP-4844 Transaction EIP-4844 transactions (`TxType = 3`) are available on networks that have activated blob transactions. Build one using the `TransactionBuilder4844` trait, which provides `.with_blob_sidecar(..)` for blob-specific fields. ```rust showLineNumbers use alloy::{ rpc::types::TransactionRequest, network::{TransactionBuilder, TransactionBuilder4844}, primitives::{address, U256}, }; // ..snip.. let tx = TransactionRequest::default() .with_to(address!("0x1234567890abcdef1234567890abcdef12345678")) .with_value(U256::from(1000)) .with_blob_sidecar(blob_sidecar); // [!code hl] ``` Find the full example [here](https://alloy.rs/transactions/sending-an-EIP-4844-transaction). ### EIP-7594 Blob Sidecar EIP-7594 changes the pooled blob sidecar representation for PeerDAS; it does not introduce a new transaction type. Build and fill an EIP-4844 transaction, then convert its sidecar before encoding and submitting it to a compatible node. Find the full example [here](https://alloy.rs/transactions/sending-an-EIP-7594-transaction). ### Example: EIP-7702 Transaction EIP-7702 transaction (`TxType = 4`) ```rust showLineNumbers use alloy::{ rpc::types::TransactionRequest, network::{TransactionBuilder, TransactionBuilder7702}, primitives::{address, U256}, }; // .. snip.. let tx = TransactionRequest::default() .with_to(address!("0x1234567890abcdef1234567890abcdef12345678")) .with_value(U256::from(1000)) .with_authorization_list(authorization_list); // [!code hl] ``` Find the full example [here](https://alloy.rs/transactions/sending-an-EIP-7702-transaction). ### Inspecting Transaction Type Output The `TransactionBuilder` provides methods inspect the transaction type while building it: * **`.complete_type(tx_type: TxType)`**: Check if all necessary keys are present to build the specified type, returning a list of missing keys. * **`.output_tx_type()`**: Returns the transaction type that this builder will attempt to build. This does not imply that the builder is ready to build. * **`.output_tx_type_checked()`**: Like `.output_tx_type()`, Returns `None` if the builder is not ready to build. ## The transaction lifecycle This article will walk you through the process of defining a transaction to send `100 wei` from `Alice` to `Bob`, signing the transaction and broadcasting the signed transaction to the Ethereum network. Let's express our intent in the form of a [`TransactionRequest`](https://docs.rs/alloy/latest/alloy/rpc/types/eth/struct.TransactionRequest.html): ```rust // Build a transaction to send 100 wei from Alice to Bob. let tx = TransactionRequest::default() .with_from(alice) .with_to(bob) .with_nonce(nonce) .with_chain_id(chain_id) .with_value(U256::from(100)) .with_gas_price(gas_price) .with_gas_limit(gas_limit); ``` ### Setup First we will set up our environment: We start by defining the RPC URL of our local Ethereum node [Anvil](https://github.com/foundry-rs/foundry/tree/master/crates/anvil) node. If you do not have `Anvil` installed see the [Foundry](https://github.com/foundry-rs/foundry) [installation instructions](https://book.getfoundry.sh/getting-started/installation). ```rust // Spin up a local Anvil node. // Ensure `anvil` is available in $PATH. let anvil = Anvil::new().try_spawn()?; // Get the RPC URL. let rpc_url = anvil.endpoint().parse()?; ``` ```rust // Alternatively, use a caller-supplied endpoint. let rpc_url = std::env::var("RPC_URL")?.parse()?; ``` Next let's define a `signer` for Alice. By default `Anvil` defines a mnemonic phrase: `"test test test test test test test test test test test junk"`. Make sure to not use this mnemonic phrase outside of testing environments. We add a signer to the `Provider` using the `.wallet` method which is responsible for signing the transactions.s Derive the first key of the mnemonic phrase for `Alice`: ```rust // Set up signer from the first default Anvil account (Alice). let signer: PrivateKeySigner = anvil.keys()[0].clone().into(); ``` Next lets grab the address of our users `Alice` and `Bob`: ```rust // Create two users, Alice and Bob. let alice = anvil.addresses()[0]; let bob = anvil.addresses()[1]; ``` Next we can build the [`Provider`](https://docs.rs/alloy/latest/alloy/providers/trait.Provider.html) using the [`ProviderBuilder`](https://docs.rs/alloy/latest/alloy/providers/struct.ProviderBuilder.html). ```rust // Create a provider with the signer. // `ProviderBuilder::new` initializes the recommended fillers. let provider = ProviderBuilder::new() .wallet(signer) // Previously, on_http .connect_http(rpc_url); ``` Note that the [ProviderBuilder](https://alloy.rs/rpc-providers/introduction) constructor `new` initializes the [RecommendedFillers](https://alloy.rs/rpc-providers/understanding-fillers). Let's modify our original `TransactionRequest` to make use of the [RecommendedFiller](https://docs.rs/alloy/latest/alloy/providers/fillers/type.RecommendedFiller.html) installed on the `Provider` to automatically fill out transaction details. The `RecommendedFillers` includes the following fillers: * [GasFiller](https://docs.rs/alloy/latest/alloy/providers/fillers/struct.GasFiller.html) * [BlobGasFiller](https://docs.rs/alloy-provider/latest/alloy_provider/fillers/struct.BlobGasFiller.html) * [NonceFiller](https://docs.rs/alloy/latest/alloy/providers/fillers/struct.NonceFiller.html) * [ChainIdFiller](https://docs.rs/alloy/latest/alloy/providers/fillers/struct.ChainIdFiller.html) Because we are using `RecommendedFillers` for filling the `TransactionRequest` we only need a subset of the original fields: ```diff showLineNumbers // Build a transaction to send 100 wei from Alice to Bob. let tx = TransactionRequest::default() - .with_from(alice) .with_to(bob) - .with_nonce(nonce) - .with_chain_id(chain_id) .with_value(U256::from(100)) - .with_gas_price(gas_price) - .with_gas_limit(gas_limit); ``` Changes to: ```rust showLineNumbers // Build a transaction to send 100 wei from Alice to Bob. // The `from` field is automatically filled to the first signer's address (Alice). let tx = TransactionRequest::default() .with_to(bob) .with_value(U256::from(100)); ``` Much better! ### Signing and broadcasting the transaction Given that we have configured a signer on our `Provider` we can sign the transaction locally and broadcast in a single line: There are three ways to listen for transaction inclusion after broadcasting the transaction, depending on your requirements: ```rust // Send the transaction and listen for the transaction to be broadcasted. let pending_tx = provider.send_transaction(tx).await?.register().await?; ``` ```rust // Send the transaction and listen for the transaction to be included. let tx_hash = provider.send_transaction(tx).await?.watch().await?; ``` ```rust // Send the transaction and fetch the receipt after the transaction was included. let tx_receipt = provider.send_transaction(tx).await?.get_receipt().await?; ``` Let's dive deeper into what we just did. By calling: ```rust let tx_builder = provider.send_transaction(tx).await?; ``` The [`Provider::send_transaction`](https://docs.rs/alloy/latest/alloy/providers/trait.Provider.html#method.send_transaction) method returns a [`PendingTransactionBuilder`](https://docs.rs/alloy/latest/alloy/providers/struct.PendingTransactionBuilder.html) for configuring the pending transaction watcher. On it we can for example, set the [`required_confirmations`](https://docs.rs/alloy/latest/alloy/providers/struct.PendingTransactionBuilder.html#method.set_required_confirmations) or set a [`timeout`](https://docs.rs/alloy/latest/alloy/providers/struct.PendingTransactionBuilder.html#method.set_timeout): ```rust // Configure the pending transaction. let pending_tx_builder = provider.send_transaction(tx) .await? .with_required_confirmations(2) .with_timeout(Some(std::time::Duration::from_secs(60))); ``` By passing the `TransactionRequest`, we populate any missing fields. This involves filling in details such as the nonce, chain ID, gas price, and gas limit: ```diff // Build a transaction to send 100 wei from Alice to Bob. let tx = TransactionRequest::default() + .with_from(alice) .with_to(bob) + .with_nonce(nonce) + .with_chain_id(chain_id) .with_value(U256::from(100)) + .with_gas_price(gas_price) + .with_gas_limit(gas_limit); ``` As part [Wallet's `fill` method](https://docs.rs/alloy/latest/alloy/providers/fillers/trait.TxFiller.html#tymethod.fill), registered on the `Provider`, we build a signed transaction from the populated `TransactionRequest` using our signer, Alice. At this point, the `TransactionRequest` becomes a `TransactionEnvelope`, ready to send across the network. By calling either [`register`](https://docs.rs/alloy/latest/alloy/providers/struct.PendingTransactionBuilder.html#method.register), [`watch`](https://docs.rs/alloy/latest/alloy/providers/struct.PendingTransactionBuilder.html#method.watch) or [`get_receipt`](https://docs.rs/alloy/latest/alloy/providers/struct.PendingTransactionBuilder.html#method.get_receipt) we can broadcast the transaction and track the status of the transaction. For instance: ```rust // Send the transaction and fetch the receipt after the transaction was included. let tx_receipt = provider.send_transaction(tx).await?.get_receipt().await?; ``` The [`TransactionReceipt`](https://docs.rs/alloy/latest/alloy/rpc/types/struct.TransactionReceipt.html) provides a comprehensive record of the transaction's journey and outcome, including the transaction hash, block details, gas used, and addresses involved. ```rust pub struct TransactionReceipt { // ... /// Transaction Hash. pub transaction_hash: TxHash, /// Index within the block. pub transaction_index: Option, /// Hash of the block this transaction was included within. pub block_hash: Option, /// Number of the block this transaction was included within. pub block_number: Option, /// Gas used by this transaction alone. pub gas_used: u128, /// Address of the sender. pub from: Address, /// Address of the receiver. None when its a contract creation transaction. pub to: Option

, /// Contract address created, or None if not a deployment. pub contract_address: Option
, // ... } ``` This completes the journey of broadcasting a signed transaction. Once the transaction is included in a block, it becomes an immutable part of the Ethereum blockchain, ensuring that the transfer of `100 wei` from `Alice` to `Bob` is recorded permanently. ## Putting it all together ```rust // [!include ~/snippets/transactions/examples/transfer_eth.rs] ``` # Encode and decode EIP-2718 envelopes The examples use the `alloy` meta-crate's default features. With `default-features = false`, select `consensus` and `eips` for envelope codecs, `k256` and `signer-local` for recovery and local signing, and the relevant `rpc-types` and provider features for RPC access. See [feature flags](https://alloy.rs/reference/feature-flags). Ethereum transaction bytes are not ABI-encoded and are not the JSON returned by an RPC node. Signed execution transactions and receipts use [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) envelopes; EIP-4844 additionally defines a pooled sidecar wrapper for submission and gossip. In Alloy, use [`TxEnvelope`](https://docs.rs/alloy/latest/alloy/consensus/type.TxEnvelope.html) for signed Ethereum transactions and [`ReceiptEnvelope`](https://docs.rs/alloy/latest/alloy/consensus/enum.ReceiptEnvelope.html) for execution receipts. Do not encode `TxLegacy`, `TxEip2930`, `TxEip1559`, `TxEip4844`, or `TxEip7702` directly when you need canonical transaction bytes. Sign the concrete transaction and convert it into `TxEnvelope` first. The envelope preserves the signature and variant, including the type byte for typed transactions and its absence for legacy transactions. ## Choose the representation at the boundary | Data at the boundary | Alloy representation | Encoding | | --- | --- | --- | | Unsigned transaction being constructed | `TransactionRequest` or a concrete `TxEip*` type | Signing payload, not broadcast bytes | | Signed execution transaction for blocks or storage | `TxEnvelope` with any EIP-4844 sidecar stripped | EIP-2718 execution envelope | | Signed transaction for submission or pooled gossip | Network's signed envelope; EIP-4844 includes a sidecar | EIP-2718, with the pooled EIP-4844 wrapper when applicable | | Ethereum JSON-RPC transaction response | `rpc::types::Transaction` wrapping a `TxEnvelope` and node-reported sender | JSON-RPC | | Consensus execution receipt | `ReceiptEnvelope` | EIP-2718 | | Solidity arguments, return values, events, and errors | `SolValue` and `SolType` implementations | Solidity ABI | See [protocol and RPC types](https://alloy.rs/reference/protocol-and-rpc-types) for the wider type hierarchy. ## Understand the type byte Legacy transactions and receipts are RLP lists without an EIP-2718 type byte. Newer variants begin with one byte followed by that type's encoded payload: | Variant | Type byte | | --- | --- | | Legacy | none | | EIP-2930 access-list | `0x01` | | EIP-1559 dynamic-fee | `0x02` | | EIP-4844 blob | `0x03` | | EIP-7702 authorization-list | `0x04` | EIP-7594 changes the blob sidecar format; it does not introduce another execution transaction type. The transaction envelope remains EIP-4844 type `0x03`. These variants describe the bytes Alloy can represent, not whether a particular chain has activated the type or whether the transaction is statefully valid. For example, a submit-ready EIP-4844 transaction needs at least one blob and its sidecar, while EIP-7702 requires a non-empty list of signed authorizations. ## Encode a signed transaction Import `Encodable2718` to use the allocating convenience method or write into a reusable buffer: ```rust use alloy::{ consensus::TxEnvelope, eips::eip2718::Encodable2718, }; fn encode(envelope: &TxEnvelope) -> Vec { // Convenience form. let encoded = envelope.encoded_2718(); // Equivalent form for a caller-owned, preallocated buffer. let mut buffer = Vec::with_capacity(envelope.encode_2718_len()); envelope.encode_2718(&mut buffer); assert_eq!(encoded, buffer); // `encode_2718` appends, so clear the buffer before encoding into it again. buffer.clear(); envelope.encode_2718(&mut buffer); assert_eq!(encoded, buffer); encoded } ``` When manually constructing a concrete transaction, sign its `signature_hash()` and then convert the signed value: ```rust use alloy::{ consensus::{SignableTransaction, TxEnvelope}, signers::{local::PrivateKeySigner, SignerSync}, }; # fn example( # transaction: alloy::consensus::TxEip1559, # signer: &PrivateKeySigner, # ) -> eyre::Result { let signature = signer.sign_hash_sync(&transaction.signature_hash())?; let envelope: TxEnvelope = transaction.into_signed(signature).into(); # Ok(envelope) # } ``` For application code, the transaction builder and wallet filler usually build the signed envelope for you. [`Provider::send_tx_envelope`](https://docs.rs/alloy/latest/alloy/providers/trait.Provider.html#method.send_tx_envelope) accepts it directly. ## Decode exactly one transaction Use `decode_2718_exact` when a byte slice must contain exactly one envelope: ```rust use alloy::{ consensus::TxEnvelope, eips::eip2718::Decodable2718, }; # fn example(raw: &[u8]) -> eyre::Result { let envelope = TxEnvelope::decode_2718_exact(raw)?; # Ok(envelope) # } ``` `decode_2718(&mut input)` advances a mutable slice and deliberately permits trailing bytes. Use it when parsing a larger stream. Prefer the exact decoder for standalone, untrusted input so appended data is rejected. For typed envelopes, `network_encode` and `network_decode` add or consume the outer RLP string wrapper used by Ethereum's peer-to-peer protocol; the legacy RLP list is unchanged. These methods are not substitutes for EIP-2718 bytes passed to `eth_sendRawTransaction`. ## Convert an RPC transaction response The default Ethereum RPC transaction response wraps a consensus envelope with the `from` address reported by the node. Consume the concrete response with `into_inner()` instead of serializing through JSON. If the response is untrusted, verify the reported sender and hash against the signed bytes: ```rust use alloy::{ consensus::{transaction::SignerRecoverable, TxEnvelope}, eips::eip2718::{Decodable2718, Encodable2718}, providers::Provider, }; # async fn example( # provider: &impl Provider, # hash: alloy::primitives::B256, # ) -> eyre::Result<()> { let response = provider .get_transaction_by_hash(hash) .await? .ok_or_else(|| eyre::eyre!("transaction not found"))?; let rpc_from = response.inner.signer(); let reported_hash = *response.inner.tx_hash(); let envelope = response.into_inner(); assert_eq!(envelope.recover_signer()?, rpc_from); let raw = envelope.encoded_2718(); let decoded = TxEnvelope::decode_2718_exact(&raw)?; assert_eq!(decoded.recover_signer()?, rpc_from); assert_eq!(*decoded.tx_hash(), reported_hash); # Ok(()) # } ``` Use `into_recovered()` instead when you want to retain the sender alongside the envelope. Network-generic code should use the envelope and response types associated with its `Network`; rollup and custom networks can define variants that Ethereum's `TxEnvelope` does not. `AnyNetwork` can preserve unknown variants at the JSON-RPC boundary, but its catch-all unknown envelopes cannot be EIP-2718 encoded or decoded; use a concrete network envelope for binary round trips. ## Distinguish the hashes * `signature_hash()` is the hash of the unsigned signing payload. A signer signs this value. * `tx_hash()` is the identifier of the signed transaction envelope. * `recover_signer()` recovers the sender from the signed payload and signature. For EIP-7702, `recover_signer()` recovers the outer transaction sender. Each authorization has a separate signature and authority, available through `SignedAuthorization::recover_authority()`. Do not calculate a transaction hash from the JSON text. For a trusted response, preserve or extract the embedded envelope and use `tx_hash()`. To verify an untrusted node's reported hash, decode the canonical bytes into a fresh envelope as shown above. ## Encode and decode receipts Receipt envelopes use the same legacy-versus-typed distinction and the same EIP-2718 traits: ```rust use alloy::{ consensus::ReceiptEnvelope, eips::eip2718::{Decodable2718, Encodable2718}, }; # fn example(receipt: ReceiptEnvelope) -> eyre::Result<()> { let encoded = receipt.encoded_2718(); let decoded = ReceiptEnvelope::decode_2718_exact(&encoded)?; assert_eq!(decoded, receipt); # Ok(()) # } ``` An RPC `TransactionReceipt` contains RPC metadata and logs with block context. Convert those logs to primitive consensus logs before persisting canonical receipt bytes: ```rust # async fn example( # receipt: alloy::rpc::types::TransactionReceipt, # ) -> eyre::Result<()> { use alloy::eips::eip2718::Encodable2718; let consensus_receipt = receipt.into_primitives_receipt().into_inner(); let encoded = consensus_receipt.encoded_2718(); # let _ = encoded; # Ok(()) # } ``` The receipt envelope does not contain the transaction hash, per-transaction gas used, block number, or RPC log indices. Its consensus payload contains status or post-state, cumulative gas used, logs bloom, and logs. ## EIP-4844 sidecars An EIP-4844 transaction appears without a sidecar in execution blocks and body retrieval, but submission and transaction-pool gossip require the pooled representation with a sidecar. The transaction hash commits to the EIP-4844 payload and blob versioned hashes, not the blob bodies. Convert a default `TxEnvelope` into `EthereumTxEnvelope` to strip any sidecar before encoding the execution/block form. On that sidecar-free envelope, `try_into_pooled_eip4844(sidecar)` attaches a sidecar for submission. More general `map_eip4844` and `try_map_eip4844` conversions can replace the EIP-4844 representation inside an envelope. ## Runnable examples * [Encode and decode transaction envelopes](https://alloy.rs/examples/transactions/encode_decode_transaction_envelopes) covers all current Ethereum variants, signer recovery, hashes, reusable buffers, and conversion from an RPC response. * [Encode and decode receipt envelopes](https://alloy.rs/examples/transactions/encode_decode_receipt_envelopes) round-trips every current Ethereum receipt variant. * [Consensus and RPC type unification](https://alloy.rs/examples/providers/embed_consensus_rpc) shows how blocks, transactions, and receipts embed their consensus counterparts. ## Using the `TransactionBuilder` The [`TransactionBuilder`](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html) is a network specific transaction builder configurable with `.with_*` methods. Common fields one can configure are: * [with\_from](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_from) * [with\_to](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_to) * [with\_nonce](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_nonce) * [with\_chain\_id](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_chain_id) * [with\_value](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_value) * [with\_gas\_limit](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_gas_limit) * [with\_max\_priority\_fee\_per\_gas](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_max_priority_fee_per_gas) * [with\_max\_fee\_per\_gas](https://docs.rs/alloy/latest/alloy/network/trait.TransactionBuilder.html#method.with_max_fee_per_blob_gas) It is generally recommended to use the builder pattern, as shown, rather than directly setting values (`with_to` versus `set_to`). ```rust // Build a transaction to send 100 wei from Alice to Bob. let tx = TransactionRequest::default() .with_to(bob) .with_nonce(0) .with_chain_id(provider.get_chain_id().await?) .with_value(U256::from(100)) .with_gas_limit(21_000) .with_max_priority_fee_per_gas(1_000_000_000) .with_max_fee_per_gas(20_000_000_000); ``` ## Sending a legacy transaction Send a [pre-EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) legacy transaction by specifying the `gas_price` field. ```rust // [!include ~/snippets/transactions/examples/send_legacy_transaction.rs] ``` ## Sending an EIP-1559 transaction Send an [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) transaction by specifying the `max_fee_per_gas` and `max_priority_fee_per_gas` fields. This is also known as a dynamic or priority fee transaction. ```rust // [!include ~/snippets/transactions/examples/send_eip1559_transaction.rs] ``` ## Sending an EIP-4844 transaction Send an [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) transaction by specifying the `blob_sidecar` field. This is also known as a blob transaction. ```rust // [!include ~/snippets/transactions/examples/send_eip4844_transaction.rs] ``` # Sending an EIP-7594 blob sidecar [EIP-7594](https://eips.ethereum.org/EIPS/eip-7594) introduces PeerDAS cell proofs for blob data. It does not add a new execution-layer transaction type: the transaction remains an EIP-4844 blob transaction (`TxType = 3`), while its pooled sidecar uses the EIP-7594 representation. The workflow is: 1. Build an EIP-4844 transaction and blob sidecar. 2. Let the provider fill and sign the transaction. 3. Convert the pooled EIP-4844 sidecar to `BlobTransactionSidecarEip7594` using the intended KZG settings. 4. Encode the envelope and submit it with `send_raw_transaction`. ```rust // [!include ~/snippets/transactions/examples/send_eip7594_transaction.rs] ``` The connected node must support the fork and pooled transaction format. The runnable example starts Anvil with the Osaka hardfork; it requires a recent compatible Anvil binary and the `provider-anvil-node` feature. Use `EnvKzgSettings::Default` only when its environment-selected settings match the network. KZG setup and sidecar conversion errors should stop submission rather than falling back to a different format silently. For ordinary pre-PeerDAS blob transactions, use the [EIP-4844 guide](https://alloy.rs/transactions/sending-an-EIP-4844-transaction). ## Sending an EIP-7702 transaction Send an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) transaction by specifying the `authorization_list` field. This is also known as a set code transaction. ```rust // [!include ~/snippets/transactions/examples/send_eip7702_transaction.rs] ``` ## Using access lists Send an [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list transaction by specifying the `access_list` field. ```rust // [!include ~/snippets/transactions/examples/with_access_list.rs] ``` ## Using the sol! macro Alloy provides a powerful and intuitive way to read and write to contracts using the `sol!` procedural macro. The sol! parses Solidity syntax to generate types that implement [alloy-sol-types](https://github.com/alloy-rs/core/tree/main/crates/sol-types) traits. It uses [`syn-solidity`](https://github.com/alloy-rs/core/tree/main/crates/syn-solidity), a [syn](https://github.com/dtolnay/syn)-powered Solidity parser. It aims to mimic the behavior of the official Solidity compiler (`solc`) when it comes to parsing valid Solidity code. This means that all valid Solidity code, as recognized by `solc` `0.5.0` and above is supported. In its most basic form `sol!` is used like this: ```rust showLineNumbers use alloy::{primitives::U256, sol}; // Declare a Solidity type in standard Solidity // [!code focus] sol! { // [!code focus] // ... with attributes too! #[derive(Debug)] // [!code focus] struct Foo { // [!code focus] uint256 bar; // [!code focus] bool baz; // [!code focus] } // [!code focus] } // [!code focus] // A corresponding Rust struct is generated: // #[derive(Debug)] // pub struct Foo { // pub bar: U256, // pub baz: bool, // } let foo = Foo { bar: U256::from(42), baz: true }; // [!code focus] println!("{foo:#?}"); // [!code focus] ``` ## Generate Rust Bindings The sol! macro comes with the flexibilty of generating rust bindings for your contracts in multiple ways. ### Solidity You can directly write Solidity code: ```rust sol! { contract Counter { uint256 public number; function setNumber(uint256 newNumber) public { number = newNumber; } function increment() public { number++; } } } ``` Or provide a path to a Solidity file: ```rust sol!( "artifacts/Counter.sol" ); ``` ### JSON-ABI By enabling the `json` feature, you can generate rust bindings from ABI compliant strings or abi files directly. The format is either a JSON ABI array or an object containing an `"abi"` key. It supports common artifact formats like Foundry's: Using an ABI file: ```rust sol!( ICounter, "abi/Counter.json" ); ``` Using an ABI compliant string: ```rust sol!( ICounter, r#"[ { "type": "function", "name": "increment", "inputs": [], "outputs": [], "stateMutability": "nonpayable" }, { "type": "function", "name": "number", "inputs": [], "outputs": [ { "name": "", "type": "uint256", "internalType": "uint256" } ], "stateMutability": "view" }, { "type": "function", "name": "setNumber", "inputs": [ { "name": "newNumber", "type": "uint256", "internalType": "uint256" } ], "outputs": [], "stateMutability": "nonpayable" } ]"# ); ``` ### Snippets At times, you don't want to generate for the complete contract to keep your project light but still want call one or two functions. You can generate bindings for valid solidity snippets as well. ```rust sol!( function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); ); println!("Decoding https://etherscan.io/tx/0xd1b449d8b1552156957309bffb988924569de34fbf21b51e7af31070cc80fe9a"); let input = hex::decode("0x38ed173900000000000000000000000000000000000000000001a717cc0a3e4f84c00000000000000000000000000000000000000000000000000000000000000283568400000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000201f129111c60401630932d9f9811bd5b5fff34e000000000000000000000000000000000000000000000000000000006227723d000000000000000000000000000000000000000000000000000000000000000200000000000000000000000095ad61b0a150d79219dcf64e1e6cc01f0b64c4ce000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7")?; // Decode the input using the generated `swapExactTokensForTokens` bindings. let decoded = swapExactTokensForTokensCall::abi_decode(&input); ``` ### Forge bind When working with large solidity projects it can be cumbersome to input your solidity code or ABI files into the `sol!` macro. You can use the `forge bind` command from [foundry](https://book.getfoundry.sh/reference/forge/forge-bind) to generate alloy compatible rust bindings for your entire project or a selection of files. You can learn more about the command and its various options [here](https://book.getfoundry.sh/reference/forge/forge-bind). ## Attributes One can use the sol attributes to add additional functionality to the generated rust code. For example, the `#[sol(rpc)]` attribute generates code to enable seamless interaction with the contract over the RPC provider. It generates a method for each function in a contract that returns a [`CallBuilder`](https://docs.rs/alloy/latest/alloy/contract/struct.CallBuilder.html) for that function. If `#[sol(bytecode = "0x...")]` is provided, the contract can be deployed with `Counter::deploy` and a new instance will be created. The bytecode is also loaded from Foundry-style JSON artifact files. ```rust // [!include ~/snippets/contracts/examples/deploy_from_contract.rs] ``` You can find a full list of attributes [here](https://docs.rs/alloy-sol-macro/latest/alloy_sol_macro/macro.sol.html#attributes). ## Reading a contract We shall leverage the `sol!` macro and its `rpc` attribute to get the [WETH](https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2) balance of an address. The RPC interaction is enabled via the [`CallBuilder`](https://docs.rs/alloy/latest/alloy/contract/struct.CallBuilder.html) which handles transaction creation, setting fees and inserting the correct calldata. ```rust showLineNumbers [read_contract.rs] //! Demonstrates reading a contract by fetching the WETH balance of an address. use alloy::{primitives::address, providers::ProviderBuilder, sol}; use std::error::Error; // Generate the contract bindings for the ERC20 interface. sol! { // [!code focus] // The `rpc` attribute enables contract interaction via the provider. [!code focus] #[sol(rpc)] // [!code focus] contract ERC20 { // [!code focus] function balanceOf(address owner) public view returns (uint256); // [!code focus] } // [!code focus] } // [!code focus] #[tokio::main] async fn main() -> Result<(), Box> { // Initialize the provider. let rpc_url = std::env::var("RPC_URL")?; let provider = ProviderBuilder::new().connect(&rpc_url).await?; // Instantiate the contract instance. let weth = address!("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); let erc20 = ERC20::new(weth, provider); // [!code focus] // Fetch the balance of WETH for a given address. let owner = address!("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"); // [!code focus] let balance = erc20.balanceOf(owner).call().await?; // [!code focus] println!("WETH Balance of {owner}: {balance}"); Ok(()) } ``` ## Writing to a contract The `sol!` macro also helps up building transactions and submit them to the chain seamless. Once again, this is enabled via the `rpc` attribute and the [`CallBuilder`](https://docs.rs/alloy/latest/alloy/contract/struct.CallBuilder.html) type similar to how they aided in [`reading a contract`](https://alloy.rs/contract-interactions/read-contract). The `CallBuilder` exposes various transaction setting methods such as [`.value(..)`](https://docs.rs/alloy/latest/alloy/contract/struct.CallBuilder.html#method.value) to modify the transaction before sending it. The calldata encoding is handled under the hood. We'll be forking mainnet using a local anvil node to avoid spending real ETH. ```rust showLineNumbers [write_contract.rs] //! Demonstrates writing to a contract by depositing ETH to the WETH contract. use alloy::{primitives::{address, utils::{format_ether, Unit}, U256}, providers::ProviderBuilder, signers::local::PrivateKeySigner, sol, }; use std::error::Error; // Generate bindings for the WETH9 contract. // WETH9: sol! { // [!code focus] #[sol(rpc)] // [!code focus] contract WETH9 { // [!code focus] function deposit() public payable; // [!code focus] function balanceOf(address) public view returns (uint256); // [!code focus] } // [!code focus] } // [!code focus] #[tokio::main] async fn main() -> Result<(), Box> { // Initialize a signer with a private key. let signer: PrivateKeySigner = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80".parse()?; let rpc_url = std::env::var("RPC_URL")?; // Instantiate a provider with the signer. let provider = ProviderBuilder::new() // [!code focus] // Signs transactions before dispatching them. .wallet(signer) // Signs the transactions // [!code focus] // Forking mainnet using anvil to avoid spending real ETH. .connect_anvil_with_config(|anvil| anvil.fork(rpc_url)); // Setup WETH contract instance. let weth = address!("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"); let weth = WETH9::new(weth, provider); // [!code focus] // Prepare deposit transaction. let amt = Unit::ETHER.wei().saturating_mul(U256::from(100)); // [!code focus] let deposit = weth.deposit().value(amt); // [!code focus] // Send the transaction and wait for it to be included. let deposit_tx = deposit.send().await?; // [!code focus] let receipt = deposit_tx.get_receipt().await?; // [!code focus] // Check balance by verifying the deposit. let balance = weth.balanceOf(receipt.from).call().await?; println!("Verified balance of {:.3} WETH for {}", format_ether(balance), receipt.from); // [!code focus] Ok(()) } ``` ## Querying Contracts ### Query Contract Storage ```rust // [!include ~/snippets/queries/examples/query_contract_storage.rs] ``` ### Query Contract Code ```rust // [!include ~/snippets/queries/examples/query_deployed_bytecode.rs] ``` ### Query Logs ```rust // [!include ~/snippets/queries/examples/query_logs.rs] ``` ## Primitives Alloy provides a set of performant EVM primitive types serving as the building block for crucial off-chain infrastructure and applications. These primitives are aided with various [macros](https://docs.rs/alloy-primitives/latest/alloy_primitives/#macros) and [aliases](https://docs.rs/alloy-primitives/latest/alloy_primitives/#reexports) to make them easier to work with. Here are the most basic ones that you will encounter: ### Address An Ethereum address, 20 bytes in length. ```rust use alloy::primitives::{address, Address}; // The address! macro provides an intuitive way to instantiate the Address type from a string literal. let expected = address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045"); // [!code hl] let checksummed = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; // Parse an Ethereum address, verifying its EIP-55 checksum. let address = Address::parse_checksummed(checksummed, None).expect("valid checksum"); assert_eq!(address, expected); ``` There are many other ways to instantiate an `Address` type, you can find them [here](https://docs.rs/alloy-primitives/latest/alloy_primitives/struct.Address.html#method.from_word). ### U256 256-bit unsigned integer type. This is a wrapper over [ruint::U256](https://docs.rs/ruint/latest/ruint/struct.Uint.html) with 4, 64 bit limbs. This is necessary because the EVM operates on a 256-bit word size, which is different from the usual 32-bit or 64-bit of modern machines `U256` implements the `std::ops::*` traits, meaning it supports all arithmetic operations. ```rust use alloy::primitives::U256; let a = U256::from(10); let b = U256::from(2); // addition let sum = a + b; assert_eq!(sum, U256::from(12)); // subtraction let difference = a - b; assert_eq!(difference, U256::from(8)); // multiplication let product = a * b; assert_eq!(product, U256::from(20)); // division let quotient = a / b; assert_eq!(quotient, U256::from(5)); // modulo let remainder = a % b; assert_eq!(remainder, U256::ZERO); // equivalent to `U256::from(0)` // exponentiation let power = a.pow(b); assert_eq!(power, U256::from(100)); ``` ### FixedBytes A byte array of fixed length `[u8; N]`. This type allows us to more tightly control serialization, deserialization. rlp encoding, decoding, and other type-level attributes for fixed-length byte arrays. Users looking to prevent type-confusion between byte arrays of different lengths should use the `wrap_fixed_bytes!` macro to create a new fixed-length byte array type. For example the aforementioned `Address` type is a wrapper around `FixedBytes<20>` built using the [wrap\_fixed\_bytes](https://docs.rs/alloy-primitives/latest/alloy_primitives/macro.wrap_fixed_bytes.html) macro. ```rust use alloy::primitives::{FixedBytes, fixed_bytes, b256}; use alloy_primitives::{fixed_bytes, FixedBytes}; const ZERO: FixedBytes <0> = fixed_bytes!(); assert_eq!(ZERO, FixedBytes::ZERO); // 32-bytes tx hash let byte_array = fixed_bytes!("0xda7f09ac9b43acb4eb7d7c74dd5de20906ddd33fd4d82d8cb96997694b2d8e79"); let b256 = b256!("0xda7f09ac9b43acb4eb7d7c74dd5de20906ddd33fd4d82d8cb96997694b2d8e79"); assert_eq!(byte_array, b256); ``` ## Basic hash and address types ### Bytes and Address ```rust // [!include ~/snippets/primitives/examples/bytes_and_address_types.rs] ``` ### Hashing ```rust // [!include ~/snippets/primitives/examples/hashing_functions.rs] ``` ## Initializing Big Numbers ```rust // [!include ~/snippets/big-numbers/examples/create_instances.rs] ``` ## Using big numbers Ethereum uses big numbers (also known as "bignums" or "arbitrary-precision integers") to represent certain values in its codebase and in blockchain transactions. This is necessary because the [EVM](https://ethereum.org/en/developers/docs/evm) operates on a 256-bit word size, which is different from the usual 32-bit or 64-bit of modern machines. This was chosen for the ease of use with 256-bit cryptography (such as [Keccak-256](https://github.com/ethereum/eth-hash) hashes or [secp256k1](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm) signatures). It is worth noting that Ethereum is not the only blockchain or cryptocurrency that uses big numbers. Many other blockchains and cryptocurrencies also use big numbers to represent values in their respective systems. ### Utilities In order to create an application, it is often necessary to convert between the representation of values that is easily understood by humans (such as ether) and the machine-readable form that is used by contracts and math functions (such as wei). This is particularly important when working with Ethereum, as certain values, such as balances and gas prices, must be expressed in wei when sending transactions, even if they are displayed to the user in a different format, such as ether or gwei. To help with this conversion, `alloy::primitives::utils` provides two functions, [`parse_units`](https://github.com/alloy-rs/core/blob/main/crates/primitives/src/utils/units.rs) and [`format_units`](https://github.com/alloy-rs/core/blob/main/crates/primitives/src/utils/units.rs), which allow you to easily convert between human-readable and machine-readable forms of values. parse\_units can be used to convert a string representing a value in ether, such as "1.1", into a big number in wei, which can be used in contracts and math functions. format\_units can be used to convert a big number value into a human-readable string, which is useful for displaying values to users. ### Math Operations ```rust // [!include ~/snippets/big-numbers/examples/math_operations.rs] ``` ### Parsing and formatting units ```rust // [!include ~/snippets/big-numbers/examples/math_utilities.rs] ``` ## Common conversions ```rust // [!include ~/snippets/big-numbers/examples/conversion.rs] ``` ## Comparisons and equivalence ```rust // [!include ~/snippets/big-numbers/examples/comparison_equivalence.rs] ``` # Feature flags The `alloy` meta-crate uses feature flags to expose focused crates and select implementations. Start with the default features for a typical HTTP application, then add only the capabilities your code uses. The exact feature graph can change between releases. For the version in your `Cargo.lock`, verify the [docs.rs feature list](https://docs.rs/crate/alloy/latest/features) or the [`alloy` Cargo manifest](https://github.com/alloy-rs/alloy/blob/main/crates/alloy/Cargo.toml). ## Recommended starting points ### Default: HTTP application ```toml // [!include ~/snippets/installation/alloy.toml] ``` The defaults enable `std`, the Reqwest HTTP client with rustls, Alloy Core defaults, and `essentials`. The `essentials` group includes contracts, an HTTP provider, standard Ethereum RPC types, and local signers. ### Broad application support ```toml // [!include ~/snippets/installation/alloy-full.toml] ``` `full` adds commonly used consensus and EIP types, WebSocket and IPC providers, pubsub, KZG, RLP, and the trace, txpool, debug, and Anvil RPC APIs. Despite its name, it is not every optional integration: node binaries, cloud and hardware signers, and several RPC namespaces remain opt-in. ### No default features ```toml // [!include ~/snippets/installation/alloy-minimal.toml] ``` Use this pattern only when you intend to assemble a minimal surface. Disabling defaults removes the HTTP provider, contracts, local signer, and `std` choices supplied by the default set. Feature requirements are additive, so compile every intended target after changing them. ## Task-to-feature map | Capability | Feature(s) to consider | Notes | | --- | --- | --- | | HTTP provider | `provider-http` | Included by `essentials` and the defaults | | WebSocket provider and subscriptions | `provider-ws` | Enables pubsub and the default WebSocket TLS backend | | WebSocket with ring or native TLS | `provider-ws-ring`, `provider-ws-native-tls` | Choose the backend required by your platform | | IPC provider | `provider-ipc` | Enables pubsub | | Contract calls and bindings | `contract` | Pulls in providers and ABI features | | Local private keys | `signer-local` | Included by `essentials` | | Mnemonics or keystores | `signer-mnemonic`, `signer-keystore` | Add to `signer-local` behavior | | AWS KMS, GCP KMS, or Turnkey | `signer-aws`, `signer-gcp`, `signer-turnkey` | Each integration is independent | | Ledger or Trezor | `signer-ledger`, `signer-trezor` | Ledger also has browser and Node variants | | Start Anvil, Geth, or Reth from Rust | `node-bindings` | Enables the process bindings, `ProviderBuilder::connect_anvil*`, and the `AnvilApi` trait; not in `full` | | Anvil helpers plus Anvil RPC types | `provider-anvil-node` | `node-bindings` plus `provider-anvil-api`, which adds the `anvil` RPC types | | `debug_*` RPC methods | `provider-debug-api` | Also enables debug and trace RPC types | | `trace_*` RPC methods | `provider-trace-api` | Enables trace RPC types | | `txpool_*` RPC methods | `provider-txpool-api` | Enables txpool RPC types | | Admin, Engine, MEV, or Net methods | `provider-admin-api`, `provider-engine-api`, `provider-mev-api`, `provider-net-api` | These namespaces are not included as a group by `full` | | Rate-limited transport | `transport-throttle` | Low-level transport capability | | Dynamic or JSON ABI | `dyn-abi`, `json-abi` | `contract` already enables both | | EIP-712 signing | `eip712` | Enables support across compatible configured signers | ## HTTP implementation and TLS The defaults select Reqwest with rustls. Advanced users can choose from `reqwest-rustls-tls`, `reqwest-native-tls`, `reqwest-default-tls`, or the `hyper` HTTP implementation. Disable default features before replacing the default combination, and test the target platforms you support. WebSocket TLS choices are expressed through the provider features listed above. Avoid enabling multiple TLS backends unless a dependency requires them. ## `std`, WebAssembly, and `no_std` The networking-focused meta-crate is designed primarily for `std`. The `wasm-bindgen` feature adapts supported transport behavior for WebAssembly; it does not make every Alloy crate available in every browser environment. For a `no_std` or otherwise constrained library, depend directly on the core or protocol crate you need, disable its default features, and verify its own feature list. Do not assume that disabling `std` on the `alloy` meta-crate makes provider, signer, or transport integrations `no_std`. ## Diagnose a missing feature If an import or method is unavailable: 1. Open the item on [docs.rs](https://docs.rs/alloy/latest/alloy/) and check its **Available on crate feature** annotation. 2. Inspect `cargo tree -e features -i alloy` to see which features are active. 3. Add the smallest owning feature and run `cargo check --all-targets`. 4. If the item belongs to an individual crate, check that crate's features rather than assuming the meta-crate uses the same flag name. # Protocol and RPC types Alloy models the same chain data at several boundaries. Choosing the type that belongs to the boundary avoids manual conversion and preserves network-specific fields. | Boundary | Primary crates or modules | Examples | | --- | --- | --- | | Values and ABI | `alloy-primitives`, `alloy-sol-types`, `alloy-dyn-abi`, `alloy-json-abi` | address, `U256`, bytes, Solidity bindings | | Execution consensus | `alloy-consensus` | transaction envelopes, blocks, receipts, headers | | Protocol extensions | `alloy-eips` | block identifiers and implemented EIP data structures | | Network behavior | `alloy-network`, `alloy-network-primitives` | associated request, response, envelope, and receipt types | | JSON-RPC wire data | `alloy-rpc-types-*` | `TransactionRequest`, RPC block and receipt responses | | Chain configuration | `alloy-genesis` | execution genesis files and allocations | | State proofs | `alloy-trie` | trie roots, proofs, and prefix-sorted updates | | Representation helpers | `alloy-serde` | quantity, bytes, and compatibility serializers | The `alloy` meta-crate re-exports enabled families as `alloy::primitives`, `alloy::consensus`, `alloy::eips`, `alloy::network`, and `alloy::rpc::types`. ## Primitives and ABI types Use primitives for chain-independent values: `Address`, `B256`, `Bytes`, fixed bytes, signed and unsigned integers, hashes, and maps. The `sol!` macro and Solidity type traits provide static ABI encoding, event and error decoding, and EIP-712 definitions. Dynamic ABI and JSON ABI types are for interfaces discovered at runtime. See [primitive types](https://alloy.rs/using-primitive-types/introduction), [`sol!`](https://alloy.rs/contract-interactions/using-sol!), and [static vs. dynamic ABI](https://alloy.rs/guides/static-dynamic-abi-in-alloy). ## Consensus types Consensus types represent execution-layer objects independently of their JSON-RPC metadata: * signed and unsigned transaction variants and EIP-2718 envelopes; * headers and blocks; * receipts, logs, withdrawals, and blob sidecars; * recovered transactions that pair an envelope with its signer. Enable the `consensus` feature when using these through the meta-crate. Add `rlp`, `k256`, `kzg`, or `consensus-secp256k1` only when the operation needs that codec or cryptographic implementation. Use consensus types for database storage, networking, hashing, roots, signing payloads, and protocol-level transformations. Use the network's RPC types at the provider boundary. ## RPC types wrap consensus data Ethereum RPC responses embed consensus values and add fields supplied by the node. For example, an RPC transaction includes block placement metadata while containing a recovered consensus envelope; an RPC receipt includes transaction and block metadata around the consensus receipt. Common conversion and access patterns include: * `block.into_consensus()` to discard RPC-only metadata and obtain a consensus block; * `transaction.into_recovered()` for the recovered consensus transaction; * `.inner` or `.into_inner()` on wrapper types; * `map_*` and `try_map_*` methods when replacing an embedded header or transaction type. See the runnable [consensus and RPC embedding example](https://alloy.rs/examples/providers/embed_consensus_rpc). Avoid re-serializing through JSON just to convert between these representations. ## Network-associated types `Provider` is generic over a `Network`. The network chooses the transaction type, envelope, receipt, header, request, and RPC response types used by provider methods. Ethereum is the default. Use: * `Ethereum` for Ethereum execution-layer responses; * a chain-specific implementation such as `op-alloy` for a supported ecosystem with extra transaction or receipt variants; * `AnyNetwork` when consuming heterogeneous responses and the catch-all representation is acceptable; * a custom `Network` implementation when a library owns a distinct typed protocol surface. Choosing `Ethereum` for a chain with extra transaction variants can fail deserialization. See [interacting with multiple networks](https://alloy.rs/guides/interacting-with-multiple-networks) and the [`AnyNetwork` example](https://alloy.rs/examples/advanced/any_network). ## EIP modules `alloy-eips` collects protocol structures and behavior that are shared across consensus, provider, and RPC crates. Support for a type does not imply that the connected chain has activated that EIP. Fork activation and RPC availability remain network and node concerns. Examples include block identifiers and tags, typed envelope encodings, access lists, authorizations, blob sidecars, requests, and hardfork-related structures. Consult the [`alloy-eips` module list](https://docs.rs/alloy-eips/latest/alloy_eips/) for the exact release. ## Genesis and trie data Use `alloy-genesis` for execution genesis configuration and account allocations. Genesis formats can contain client extensions, so preserve unknown or chain-specific fields when round-tripping a configuration. Use `alloy-trie` for Merkle-Patricia Trie roots and proofs. Trie APIs generally require keys and updates in the documented order; incorrect ordering can produce a different root rather than a helpful RPC error. Treat proof verification input as untrusted data and validate the expected root. These families are optional `genesis` and `trie` features on the meta-crate and are also available as direct dependencies for infrastructure libraries. ## Serialization Ethereum JSON-RPC quantities, fixed bytes, byte strings, and nullability do not follow ordinary human-readable JSON conventions. Prefer the provided RPC and serde helper types over custom hex-string logic. Enable `serde` for serde implementations and helpers. Compatibility formats such as `serde-bincode-compat` are opt-in; use the documented compatibility wrapper rather than assuming a type's normal serde representation is stable for non-self-describing storage. For persistent data: 1. Choose whether the stored form is consensus, RPC-enriched, or application-specific. 2. Version the schema independently of the Rust type name. 3. Test round trips across dependency upgrades. 4. Do not use debug output as a data format. ## Constrained and `no_std` users The network-facing meta-crate primarily targets `std`. Some core and protocol crates support `no_std` with default features disabled. Depend on the narrow crate directly, inspect its own feature list, and compile the exact target. See [feature flags](https://alloy.rs/reference/feature-flags). ## Example: `any_network` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example any_network` ```rust // [!include ~/snippets/advanced/examples/any_network.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/any_network.rs). ## Example: `decoding_json_abi` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example decoding_json_abi` ```rust // [!include ~/snippets/advanced/examples/decoding_json_abi.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/decoding_json_abi.rs). ## Example: `encoding_dyn_abi` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example encoding_dyn_abi` ```rust // [!include ~/snippets/advanced/examples/encoding_dyn_abi.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/encoding_dyn_abi.rs). ## Example: `encoding_sol_static` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example encoding_sol_static` ```rust // [!include ~/snippets/advanced/examples/encoding_sol_static.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/encoding_sol_static.rs). ## Example: `foundry_fork_db` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example foundry_fork_db` ```rust // [!include ~/snippets/advanced/examples/foundry_fork_db.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/foundry_fork_db.rs). ## Example: `uniswap_u256_alloy_profit` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example uniswap_u256_alloy_profit` ```rust // [!include ~/snippets/advanced/examples/uniswap_u256_alloy_profit.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/uniswap_u256_alloy_profit.rs). ## Example: `uniswap_u256_ethers_profit` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example uniswap_u256_ethers_profit` ```rust // [!include ~/snippets/advanced/examples/uniswap_u256_ethers_profit.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/uniswap_u256_ethers_profit.rs). ## Example: `uniswap_u256_alloy_simulation` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-advanced --example uniswap_u256_alloy_simulation` ```rust // [!include ~/snippets/advanced/examples/uniswap_u256_alloy_simulation.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/advanced/examples/uniswap_u256_alloy_simulation.rs). ## Example: `comparison_equivalence` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-big-numbers --example comparison_equivalence` ```rust // [!include ~/snippets/big-numbers/examples/comparison_equivalence.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/big-numbers/examples/comparison_equivalence.rs). ## Example: `conversion` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-big-numbers --example conversion` ```rust // [!include ~/snippets/big-numbers/examples/conversion.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/big-numbers/examples/conversion.rs). ## Example: `create_instances` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-big-numbers --example create_instances` ```rust // [!include ~/snippets/big-numbers/examples/create_instances.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/big-numbers/examples/create_instances.rs). ## Example: `math_operations` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-big-numbers --example math_operations` ```rust // [!include ~/snippets/big-numbers/examples/math_operations.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/big-numbers/examples/math_operations.rs). ## Example: `math_utilities` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-big-numbers --example math_utilities` ```rust // [!include ~/snippets/big-numbers/examples/math_utilities.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/big-numbers/examples/math_utilities.rs). ## Example: `compare_new_heads` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-comparison --example compare_new_heads` ```rust // [!include ~/snippets/comparison/examples/compare_new_heads.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/comparison/examples/compare_new_heads.rs). ## Example: `compare_pending_txs` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-comparison --example compare_pending_txs` ```rust // [!include ~/snippets/comparison/examples/compare_pending_txs.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/comparison/examples/compare_pending_txs.rs). ## Example: `deploy_from_artifact` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example deploy_from_artifact` ```rust // [!include ~/snippets/contracts/examples/deploy_from_artifact.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/deploy_from_artifact.rs). ## Example: `deploy_from_bytecode` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example deploy_from_bytecode` ```rust // [!include ~/snippets/contracts/examples/deploy_from_bytecode.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/deploy_from_bytecode.rs). ## Example: `deploy_from_contract` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example deploy_from_contract` ```rust // [!include ~/snippets/contracts/examples/deploy_from_contract.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/deploy_from_contract.rs). ## Example: `deploy_and_link_library` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example deploy_and_link_library` ```rust // [!include ~/snippets/contracts/examples/deploy_and_link_library.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/deploy_and_link_library.rs). ## Example: `interact_with_abi` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example interact_with_abi` ```rust // [!include ~/snippets/contracts/examples/interact_with_abi.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/interact_with_abi.rs). ## Example: `interact_with_contract_instance` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example interact_with_contract_instance` ```rust // [!include ~/snippets/contracts/examples/interact_with_contract_instance.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/interact_with_contract_instance.rs). ## Example: `jsonrpc_error_decoding` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example jsonrpc_error_decoding` ```rust // [!include ~/snippets/contracts/examples/jsonrpc_error_decoding.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/jsonrpc_error_decoding.rs). ## Example: `revert_decoding` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example revert_decoding` ```rust // [!include ~/snippets/contracts/examples/revert_decoding.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/revert_decoding.rs). ## Example: `unknown_return_types` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example unknown_return_types` ```rust // [!include ~/snippets/contracts/examples/unknown_return_types.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/unknown_return_types.rs). ## Example: `arb_profit_calc` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example arb_profit_calc` ```rust // [!include ~/snippets/contracts/examples/arb_profit_calc.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/arb_profit_calc.rs). ## Example: `simulation_uni_v2` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example simulation_uni_v2` ```rust // [!include ~/snippets/contracts/examples/simulation_uni_v2.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/simulation_uni_v2.rs). ## Example: `address_lookup` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-ens --example address_lookup` ```rust // [!include ~/snippets/ens/examples/address_lookup.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/ens/examples/address_lookup.rs). ## Example: `name_resolution` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-ens --example name_resolution` ```rust // [!include ~/snippets/ens/examples/name_resolution.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/ens/examples/name_resolution.rs). ## Example: `gas_filler` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-fillers --example gas_filler` ```rust // [!include ~/snippets/fillers/examples/gas_filler.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/fillers/examples/gas_filler.rs). ## Example: `nonce_filler` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-fillers --example nonce_filler` ```rust // [!include ~/snippets/fillers/examples/nonce_filler.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/fillers/examples/nonce_filler.rs). ## Example: `recommended_fillers` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-fillers --example recommended_fillers` ```rust // [!include ~/snippets/fillers/examples/recommended_fillers.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/fillers/examples/recommended_fillers.rs). ## Example: `wallet_filler` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-fillers --example wallet_filler` ```rust // [!include ~/snippets/fillers/examples/wallet_filler.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/fillers/examples/wallet_filler.rs). ## Example: `urgent_filler` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-fillers --example urgent_filler` ```rust // [!include ~/snippets/fillers/examples/urgent_filler.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/fillers/examples/urgent_filler.rs). ## Example: `hyper_http_layer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-layers --example hyper_http_layer` ```rust // [!include ~/snippets/layers/examples/hyper_http_layer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/layers/examples/hyper_http_layer.rs). ## Example: `logging_layer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-layers --example logging_layer` ```rust // [!include ~/snippets/layers/examples/logging_layer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/layers/examples/logging_layer.rs). ## Example: `retry_layer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-layers --example retry_layer` ```rust // [!include ~/snippets/layers/examples/retry_layer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/layers/examples/retry_layer.rs). ## Example: `fallback_layer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-layers --example fallback_layer` ```rust // [!include ~/snippets/layers/examples/fallback_layer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/layers/examples/fallback_layer.rs). ## Example: `delay_layer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-layers --example delay_layer` ```rust // [!include ~/snippets/layers/examples/delay_layer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/layers/examples/delay_layer.rs). ## Example: `anvil_deploy_contract` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example anvil_deploy_contract` ```rust // [!include ~/snippets/node-bindings/examples/anvil_deploy_contract.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/anvil_deploy_contract.rs). ## Example: `anvil_fork_instance` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example anvil_fork_instance` ```rust // [!include ~/snippets/node-bindings/examples/anvil_fork_instance.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/anvil_fork_instance.rs). ## Example: `anvil_fork_provider` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example anvil_fork_provider` ```rust // [!include ~/snippets/node-bindings/examples/anvil_fork_provider.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/anvil_fork_provider.rs). ## Example: `anvil_local_instance` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example anvil_local_instance` ```rust // [!include ~/snippets/node-bindings/examples/anvil_local_instance.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/anvil_local_instance.rs). ## Example: `anvil_local_provider` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example anvil_local_provider` ```rust // [!include ~/snippets/node-bindings/examples/anvil_local_provider.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/anvil_local_provider.rs). ## Example: `geth_local_instance` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example geth_local_instance` ```rust // [!include ~/snippets/node-bindings/examples/geth_local_instance.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/geth_local_instance.rs). ## Example: `reth_local_instance` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example reth_local_instance` ```rust // [!include ~/snippets/node-bindings/examples/reth_local_instance.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/reth_local_instance.rs). ## Example: `anvil_set_storage_at` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-node-bindings --example anvil_set_storage_at` ```rust // [!include ~/snippets/node-bindings/examples/anvil_set_storage_at.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/node-bindings/examples/anvil_set_storage_at.rs). ## Example: `bytes_and_address_types` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-primitives --example bytes_and_address_types` ```rust // [!include ~/snippets/primitives/examples/bytes_and_address_types.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/primitives/examples/bytes_and_address_types.rs). ## Example: `hashing_functions` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-primitives --example hashing_functions` ```rust // [!include ~/snippets/primitives/examples/hashing_functions.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/primitives/examples/hashing_functions.rs). ## Example: `builder` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example builder` ```rust // [!include ~/snippets/providers/examples/builder.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/builder.rs). ## Example: `builtin` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example builtin` ```rust // [!include ~/snippets/providers/examples/builtin.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/builtin.rs). ## Example: `http_with_auth` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example http_with_auth` ```rust // [!include ~/snippets/providers/examples/http_with_auth.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/http_with_auth.rs). ## Example: `http` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example http` ```rust // [!include ~/snippets/providers/examples/http.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/http.rs). ## Example: `ipc` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example ipc` ```rust // [!include ~/snippets/providers/examples/ipc.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/ipc.rs). ## Example: `mocking` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example mocking` ```rust // [!include ~/snippets/providers/examples/mocking.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/mocking.rs). ## Example: `wrapped_provider` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example wrapped_provider` ```rust // [!include ~/snippets/providers/examples/wrapped_provider.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/wrapped_provider.rs). ## Example: `dyn_provider` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example dyn_provider` ```rust // [!include ~/snippets/providers/examples/dyn_provider.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/dyn_provider.rs). ## Example: `multicall_batching` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example multicall_batching` ```rust // [!include ~/snippets/providers/examples/multicall_batching.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/multicall_batching.rs). ## Example: `multicall` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example multicall` ```rust // [!include ~/snippets/providers/examples/multicall.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/multicall.rs). ## Example: `ws` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example ws` ```rust // [!include ~/snippets/providers/examples/ws.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/ws.rs). ## Example: `ws_with_auth` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example ws_with_auth` ```rust // [!include ~/snippets/providers/examples/ws_with_auth.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/ws_with_auth.rs). ## Example: `ws_with_reconnect` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example ws_with_reconnect` ```rust // [!include ~/snippets/providers/examples/ws_with_reconnect.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/ws_with_reconnect.rs). ## Example: `batch_rpc` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example batch_rpc` ```rust // [!include ~/snippets/providers/examples/batch_rpc.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/batch_rpc.rs). ## Example: `embed_consensus_rpc` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example embed_consensus_rpc` ```rust // [!include ~/snippets/providers/examples/embed_consensus_rpc.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/embed_consensus_rpc.rs). ## Example: `basic_provider` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-providers --example basic_provider` ```rust // [!include ~/snippets/providers/examples/basic_provider.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/providers/examples/basic_provider.rs). ## Example: `query_contract_storage` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-queries --example query_contract_storage` ```rust // [!include ~/snippets/queries/examples/query_contract_storage.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/queries/examples/query_contract_storage.rs). ## Example: `query_deployed_bytecode` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-queries --example query_deployed_bytecode` ```rust // [!include ~/snippets/queries/examples/query_deployed_bytecode.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/queries/examples/query_deployed_bytecode.rs). ## Example: `query_logs` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-queries --example query_logs` ```rust // [!include ~/snippets/queries/examples/query_logs.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/queries/examples/query_logs.rs). ## Example: `query_logs_chunked` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-queries --example query_logs_chunked` ```rust // [!include ~/snippets/queries/examples/query_logs_chunked.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/queries/examples/query_logs_chunked.rs). ## Example: `events_errors` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-sol-macro --example events_errors` ```rust // [!include ~/snippets/sol-macro/examples/events_errors.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/sol-macro/examples/events_errors.rs). ## Example: `decode_returns` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-sol-macro --example decode_returns` ```rust // [!include ~/snippets/sol-macro/examples/decode_returns.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/sol-macro/examples/decode_returns.rs). ## Example: `structs_enums` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-sol-macro --example structs_enums` ```rust // [!include ~/snippets/sol-macro/examples/structs_enums.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/sol-macro/examples/structs_enums.rs). ## Example: `user_defined_types` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-sol-macro --example user_defined_types` ```rust // [!include ~/snippets/sol-macro/examples/user_defined_types.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/sol-macro/examples/user_defined_types.rs). ## Example: `all_derives` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-sol-macro --example all_derives` ```rust // [!include ~/snippets/sol-macro/examples/all_derives.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/sol-macro/examples/all_derives.rs). ## Example: `extra_derives` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-sol-macro --example extra_derives` ```rust // [!include ~/snippets/sol-macro/examples/extra_derives.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/sol-macro/examples/extra_derives.rs). ## Example: `subscribe_blocks` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-subscriptions --example subscribe_blocks` ```rust // [!include ~/snippets/subscriptions/examples/subscribe_blocks.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/subscriptions/examples/subscribe_blocks.rs). ## Example: `watch_canonical_blocks` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-subscriptions --example watch_canonical_blocks` ```rust // [!include ~/snippets/subscriptions/examples/watch_canonical_blocks.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/subscriptions/examples/watch_canonical_blocks.rs). ## Example: `poll_logs` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-subscriptions --example poll_logs` ```rust // [!include ~/snippets/subscriptions/examples/poll_logs.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/subscriptions/examples/poll_logs.rs). ## Example: `subscribe_logs` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-subscriptions --example subscribe_logs` ```rust // [!include ~/snippets/subscriptions/examples/subscribe_logs.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/subscriptions/examples/subscribe_logs.rs). ## Example: `subscribe_all_logs` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-subscriptions --example subscribe_all_logs` ```rust // [!include ~/snippets/subscriptions/examples/subscribe_all_logs.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/subscriptions/examples/subscribe_all_logs.rs). ## Example: `subscribe_pending_transactions` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-subscriptions --example subscribe_pending_transactions` ```rust // [!include ~/snippets/subscriptions/examples/subscribe_pending_transactions.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/subscriptions/examples/subscribe_pending_transactions.rs). ## Example: `event_multiplexer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-subscriptions --example event_multiplexer` ```rust // [!include ~/snippets/subscriptions/examples/event_multiplexer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/subscriptions/examples/event_multiplexer.rs). ## Example: `decode_input` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example decode_input` ```rust // [!include ~/snippets/transactions/examples/decode_input.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/decode_input.rs). ## Example: `decode_receipt_log` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example decode_receipt_log` ```rust // [!include ~/snippets/transactions/examples/decode_receipt_log.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/decode_receipt_log.rs). ## Example: `encode_decode_receipt_envelopes` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example encode_decode_receipt_envelopes` ```rust // [!include ~/snippets/transactions/examples/encode_decode_receipt_envelopes.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/4e58c21411ce2c6c151011c89c685d00df929f11/examples/transactions/examples/encode_decode_receipt_envelopes.rs). ## Example: `encode_decode_transaction_envelopes` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example encode_decode_transaction_envelopes` ```rust // [!include ~/snippets/transactions/examples/encode_decode_transaction_envelopes.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/4e58c21411ce2c6c151011c89c685d00df929f11/examples/transactions/examples/encode_decode_transaction_envelopes.rs). ## Example: `gas_price_usd` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example gas_price_usd` ```rust // [!include ~/snippets/transactions/examples/gas_price_usd.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/gas_price_usd.rs). ## Example: `debug_trace_call_many` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example debug_trace_call_many` ```rust // [!include ~/snippets/transactions/examples/debug_trace_call_many.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/debug_trace_call_many.rs). ## Example: `trace_call_many` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example trace_call_many` ```rust // [!include ~/snippets/transactions/examples/trace_call_many.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/trace_call_many.rs). ## Example: `trace_call` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example trace_call` ```rust // [!include ~/snippets/transactions/examples/trace_call.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/trace_call.rs). ## Example: `trace_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example trace_transaction` ```rust // [!include ~/snippets/transactions/examples/trace_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/trace_transaction.rs). ## Example: `transfer_erc20` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example transfer_erc20` ```rust // [!include ~/snippets/transactions/examples/transfer_erc20.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/transfer_erc20.rs). ## Example: `permit2_signature_transfer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example permit2_signature_transfer` ```rust // [!include ~/snippets/transactions/examples/permit2_signature_transfer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/permit2_signature_transfer.rs). ## Example: `transfer_eth` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example transfer_eth` ```rust // [!include ~/snippets/transactions/examples/transfer_eth.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/transfer_eth.rs). ## Example: `send_raw_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example send_raw_transaction` ```rust // [!include ~/snippets/transactions/examples/send_raw_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/send_raw_transaction.rs). ## Example: `send_legacy_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example send_legacy_transaction` ```rust // [!include ~/snippets/transactions/examples/send_legacy_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/send_legacy_transaction.rs). ## Example: `send_eip1559_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example send_eip1559_transaction` ```rust // [!include ~/snippets/transactions/examples/send_eip1559_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/send_eip1559_transaction.rs). ## Example: `send_eip4844_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example send_eip4844_transaction` ```rust // [!include ~/snippets/transactions/examples/send_eip4844_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/send_eip4844_transaction.rs). ## Example: `send_eip7594_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example send_eip7594_transaction` ```rust // [!include ~/snippets/transactions/examples/send_eip7594_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/send_eip7594_transaction.rs). ## Example: `send_eip7702_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example send_eip7702_transaction` ```rust // [!include ~/snippets/transactions/examples/send_eip7702_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/send_eip7702_transaction.rs). ## Example: `send_private_transaction` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example send_private_transaction` ```rust // [!include ~/snippets/transactions/examples/send_private_transaction.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/send_private_transaction.rs). ## Example: `with_access_list` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-transactions --example with_access_list` ```rust // [!include ~/snippets/transactions/examples/with_access_list.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/transactions/examples/with_access_list.rs). ## Example: `aws_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example aws_signer` ```rust // [!include ~/snippets/wallets/examples/aws_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/aws_signer.rs). ## Example: `gcp_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example gcp_signer` ```rust // [!include ~/snippets/wallets/examples/gcp_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/gcp_signer.rs). ## Example: `ledger_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example ledger_signer` ```rust // [!include ~/snippets/wallets/examples/ledger_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/ledger_signer.rs). ## Example: `private_key_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example private_key_signer` ```rust // [!include ~/snippets/wallets/examples/private_key_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/private_key_signer.rs). ## Example: `mnemonic_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example mnemonic_signer` ```rust // [!include ~/snippets/wallets/examples/mnemonic_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/mnemonic_signer.rs). ## Example: `ethereum_wallet` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example ethereum_wallet` ```rust // [!include ~/snippets/wallets/examples/ethereum_wallet.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/ethereum_wallet.rs). ## Example: `sign_message` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example sign_message` ```rust // [!include ~/snippets/wallets/examples/sign_message.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/sign_message.rs). ## Example: `verify_message` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example verify_message` ```rust // [!include ~/snippets/wallets/examples/verify_message.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/verify_message.rs). ## Example: `sign_permit_hash` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example sign_permit_hash` ```rust // [!include ~/snippets/wallets/examples/sign_permit_hash.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/sign_permit_hash.rs). ## Example: `trezor_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example trezor_signer` ```rust // [!include ~/snippets/wallets/examples/trezor_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/trezor_signer.rs). ## Example: `turnkey_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example turnkey_signer` ```rust // [!include ~/snippets/wallets/examples/turnkey_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/turnkey_signer.rs). ## Example: `yubi_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example yubi_signer` ```rust // [!include ~/snippets/wallets/examples/yubi_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/yubi_signer.rs). ## Example: `keystore_signer` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example keystore_signer` ```rust // [!include ~/snippets/wallets/examples/keystore_signer.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/keystore_signer.rs). ## Example: `create_keystore` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-wallets --example create_keystore` ```rust // [!include ~/snippets/wallets/examples/create_keystore.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/wallets/examples/create_keystore.rs). # v1.0 Changes ### Revamping the `sol!` macro bindings * [Contract and RPC codegen made cleaner by removal of the `T` transport generic](https://alloy.rs/migrating-to-core-v1/sol!-changes/removing-T-generic) * [Improving the function return types by removing the need for `_0`](https://alloy.rs/migrating-to-core-v1/sol!-changes/improving-function-return-types) * [Changes to function call bindings e.g `pub struct balanceOfCall { _0: Address }` to `pub struct balanceOfCall(pub Address)`](https://alloy.rs/migrating-to-core-v1/sol!-changes/changes-to-function-call-bindings) * [Changes to event bindings](https://alloy.rs/migrating-to-core-v1/sol!-changes/changes-to-event-bindings) * [Changes to error bindings](https://alloy.rs/migrating-to-core-v1/sol!-changes/changes-to-error-bindings) ### Simplify ABI encoding and decoding * [ABI encoding function return structs](https://alloy.rs/migrating-to-core-v1/encoding-decoding-changes/encoding-return-structs) * [Removing `validate: bool` from the `abi_decode` methods](https://alloy.rs/migrating-to-core-v1/encoding-decoding-changes/removing-validate-bool) ### Other breaking changes * [Removal of the deprecated `Signature` type. `PrimitiveSignature` is now aliased to `Signature`](https://github.com/alloy-rs/core/pull/899) * [Renaming methods in User-defined types (UDT)'s bindings and implementing `From` and `Into` traits for UDT's](https://github.com/alloy-rs/core/pull/905) * [Bumping `getrandom` and `rand`](https://github.com/alloy-rs/core/pull/869) * [Removal of `From` for `Bytes`](https://github.com/alloy-rs/core/pull/907) If you'd like to dive into the details of each change, please take a look at this [PR](https://github.com/alloy-rs/core/pull/895) ## Removing the `T` transport generic Since [alloy#1859](https://github.com/alloy-rs/alloy/pull/1859) the `Provider` is independent of the `Transport`, making it easier to roll types that wrap the `Provider`. This improvement was reflected in the [`CallBuilder`](https://docs.rs/alloy-contract/latest/alloy_contract/struct.CallBuilder.html) type but not carried to the `sol!` macro bindings. [core#865](https://github.com/alloy-rs/core/pull/865) removes the `T` transport generic from the `sol!` macro bindings, making the contract and RPC codegen cleaner. This can be demonstrated using a simple example that wraps an `ERC20Instance` type. ### Before ```rust struct Erc20 { instance: ERC20Instance<(), P>, } ``` ### After ```rust struct Erc20 { instance: ERC20Instance

, } ``` ## Improving function call return types With the inclusion of [core#855](https://github.com/alloy-rs/core/pull/855) return values of function calls with a *singular* value is more intuitive and easier to work with. Consider the following example of reading the balance of an ERC20: ```rust sol! { #[sol(rpc)] contract ERC20 { // Note: Only a single value is being returned function balanceOf(address) returns (uint256); } } ``` ## Before Calling the `balanceOf` fn would return a struct `balanceOfReturn` which encapsulated the actual balance value. ```rust // .. snip .. let balance_return: balanceOfReturn = erc20.balanceOf(owner).await?; let actual_balance = balance_return._0; ``` ## After Calling the `balanceOf` fn would now yield the balance directly instead of a struct wrapping it. ```rust // .. snip .. let balance: U256 = erc20.balanceOf(owner).await?; ``` It is important to note that this change only applies to function calls that have a **singular** return value. Function calls that **return multiple values** have their return types **unchanged**, i.e they still return a struct with values inside it. ```rust sol! { function multiValues() returns (uint256 a, address b, bytes c); } // The above function call will have the following return type. pub struct multiValuesReturn { pub a: U256, pub b: Address, pub c: Bytes, } ``` ## Changes to function call bindings With [core#884](https://github.com/alloy-rs/core/pull/884) the form of the generated call type (used for abi-encoding) is now dependent upon two factors: 1. Number of parameters/args does the function take 2. Whether the parameter is named or unnamed in case it has only **one** param Consider the following: ```rust sol! { // No params/args function totalSupply() returns (uint256) // Exactly one unnamed param function balanceOf(address) returns (uint256); // Multiple params - Bindings for this remain unchanged. function approve(address spender, uint256 amount) returns (bool); } ``` ### Before Generated bindings were independent of the number of parameters and names, and the following struct were generated for the above function calls ```rust // A struct with no fields as there are no parameters. pub struct totalSupplyCall { }; let encoding = totalSupplyCall { }.abi_encode(); pub struct balanceOfCall { _0: Address }; let encoding = balanceOfCall { _0: Address::ZERO }.abi_encode(); ``` ### After ```rust // A unit struct is generated when there are no parameters. pub struct totalSupplyCall; let encoding = totalSupplyCall.abi_encode(); // A tuple struct with a single value is generated in case of a SINGLE UNNAMED param. pub struct balanceOfCall(pub Address); let encoding = balanceOfCall(Address::ZERO).abi_encode(); ``` Now if the parameter in `balanceOf` was named like so: ```rust sol! { function balanceOf(address owner) returns (uint256); } ``` Then a regular struct would be generated like before: ```rust, ignore pub struct balanceOfCall { owner: Address }; ``` Bindings for function calls with **multiple parameters** are **unchanged**. ## Changes to event bindings [core#885](https://github.com/alloy-rs/core/pull/885) makes changes to the event bindings in a breaking but very minimal way. It changes the bindings for **only** events with no parameters Consider the following event: ```rust sol! { event Incremented(); } ``` ### Before The generated struct was an empty struct like below: ```rust pub struct Incremented { }; ``` ### After A unit struct is generated like below: ```rust pub struct Incremented; ``` Bindings for events with parameters remain **unchanged**. ## Changes to error bindings [core#883](https://github.com/alloy-rs/core/pull/883) makes similar changes to the error bindings that [core#884](https://github.com/alloy-rs/core/pull/884) did to function call bindings in the sense that the form of the generated type is dependent upon two factors: 1. Number of parameters the error has. 2. Whether the parameter is named or unnamed in case it has only **one** param Consider the following example: ```rust sol! { // No params/args error Some(); // Exactly one unnamed param error Another(uint256); // Exactly one named param - bindings for this remain unchanged error YetAnother(uint256 a); } ``` ## Before All of the above were generated as regular structs. ```rust // Empty struct pub struct SomeError { }; pub struct AnotherError { _0: U256 } pub struct YetAnotherError { a: U256 } ``` ## After ```rust // Unit struct for error with no params pub struct SomeError; // Tuple struct for SINGLE UNNAMED param pub struct AnotherError(pub U256); ``` Bindings remain **unchanged** for errors with **multiple params** and **single but named param**. ## Encoding return structs [core#909](https://github.com/alloy-rs/core/pull/909) improves return type encoding by allowing to pass the return struct directly into `SolCall::abi_encode_returns`. Consider the following: ```rust sol! { function something() returns (uint256, address); } ``` ### Before A tuple would need to passed of the fields from return type, `somethingReturn` ```rust let encoding = somethingCall::abi_encode_returns(&(somethingReturn._0, somethingReturn._1)); ``` ### After One can now pass the return struct directly without deconstructing it as a tuple. ```rust let encoding = somethingCall::abi_encode_returns(&somethingReturn); ``` ## Removing the `validate: bool` from the `abi_decode` methods [core#863](https://github.com/alloy-rs/core/pull/863) removes the `validate: bool` parameter from the `abi_decode_*` methods. The behavior of these `abi_decode_*` methods is now equivalent to passing `validate = false`. ## Other breaking changes * [Removal of the deprecated `Signature` type. `PrimitiveSignature` is now aliased to `Signature`](https://github.com/alloy-rs/core/pull/899) * [Renaming methods in User-defined types (UDT)'s bindings and implementing `From` and `Into` traits for UDT's](https://github.com/alloy-rs/core/pull/905) * [Bumping `getrandom` and `rand`](https://github.com/alloy-rs/core/pull/869) * [Removal of `From` for `Bytes`](https://github.com/alloy-rs/core/pull/907) ## Reference [ethers-rs](https://github.com/gakonst/ethers-rs/) has been deprecated in favor of [Alloy](https://github.com/alloy-rs/) and [Foundry](https://github.com/foundry-rs/). The following is a reference guide for finding the migration path for your specific crate, dependency or information source. ### Documentation * Book: [`ethers-rs/book`](https://github.com/gakonst/ethers-rs/tree/master/book) `->` [`alloy-rs/book`](https://github.com/alloy-rs/book) ### Examples * Examples: [`ethers-rs/examples`](https://github.com/gakonst/ethers-rs/tree/master/examples) `->` [`alloy-rs/examples`](https://github.com/alloy-rs/examples) ### Crates * Meta-crate: [`ethers`](https://github.com/gakonst/ethers-rs/tree/master/ethers) `->` [`alloy`](https://github.com/alloy-rs/alloy/tree/main/crates/alloy) * Address book: [`ethers::addressbook`](https://github.com/gakonst/ethers-rs/tree/master/ethers-addressbook) `->` Not planned * Compilers: [`ethers::solc`](https://github.com/gakonst/ethers-rs/tree/master/ethers-solc) `->` [`foundry-compilers`](https://github.com/foundry-rs/compilers) * Contract: [`ethers::contract`](https://github.com/gakonst/ethers-rs/tree/master/ethers-contract) `->` [`alloy::contract`](https://github.com/alloy-rs/alloy/tree/main/crates/contract) * Core: [`ethers::core`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core) `->` [`alloy::core`](https://github.com/alloy-rs/core) * Types: [`ethers::core::types::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types) `->` See [Types](https://alloy.rs/migrating-from-ethers/reference#types) section * Etherscan: [`ethers::etherscan`](https://github.com/gakonst/ethers-rs/tree/master/ethers-etherscan) `->` [`foundry-block-explorers`](https://github.com/foundry-rs/block-explorers) * Middleware: [`ethers::middleware`](https://github.com/gakonst/ethers-rs/tree/master/ethers-middleware) `->` Fillers [`alloy::provider::{fillers, layers}`](https://github.com/alloy-rs/alloy/tree/main/crates/provider/src) * Gas oracle: [`ethers::middleware::GasOracleMiddleware`](https://github.com/gakonst/ethers-rs/tree/master/ethers-middleware/src/gas_oracle/middleware.rs) `->` Gas filler [`alloy::provider::GasFiller`](https://github.com/alloy-rs/examples/tree/main/examples/fillers/examples/gas_filler.rs) * Gas escalator: [`ethers::middleware::GasEscalatorMiddleware`](https://github.com/gakonst/ethers-rs/tree/master/ethers-middleware/src/gas_escalator) `->` Not planned * Transformer: [`ethers::middleware::TransformerMiddleware`](https://github.com/gakonst/ethers-rs/tree/master/ethers-middleware/src/transformer) `->` Not planned * Policy: [`ethers::middleware::policy::*`](https://github.com/gakonst/ethers-rs/blob/master/ethers-middleware/src/policy.rs) `->` Not planned * Timelag: [`ethers::middleware::timelag::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-middleware/src/timelag) `->` Not planned * Nonce manager: [`ethers::middleware::NonceManagerMiddleware`](https://github.com/gakonst/ethers-rs/tree/master/ethers-middleware/src/nonce_manager.rs) `->` Nonce filler [`alloy::provider::NonceFiller`](https://github.com/alloy-rs/alloy/tree/main/crates/provider/src/fillers/nonce.rs) * Signer: [`ethers::middleware::Signer`](https://github.com/gakonst/ethers-rs/tree/master/ethers-middleware/src/signer.rs) `->` Wallet filler [`alloy::provider::WalletFiller`](https://github.com/alloy-rs/alloy/tree/main/crates/provider/src/fillers/wallet.rs) * Providers: [`ethers::providers`](https://github.com/gakonst/ethers-rs/tree/master/ethers-providers) `->` Provider [`alloy::providers`](https://github.com/alloy-rs/alloy/tree/main/crates/provider) * Transports: [`ethers::providers::transports`](https://github.com/gakonst/ethers-rs/tree/master/ethers-providers/src/rpc/transports) `->` [`alloy::transports`](https://github.com/alloy-rs/alloy/tree/main/crates/transport) * HTTP: [`ethers::providers::Http`](https://github.com/gakonst/ethers-rs/tree/master/ethers-providers/src/rpc/transports/http.rs) `->` [`alloy::transports::http`](https://github.com/alloy-rs/alloy/tree/main/crates/transport-http) * IPC: [`ethers::providers::Ipc`](https://github.com/gakonst/ethers-rs/tree/master/ethers-providers/src/rpc/transports/ipc.rs) `->` [`alloy::transports::ipc`](https://github.com/alloy-rs/alloy/tree/main/crates/transport-ipc) * WS: [`ethers::providers::Ws`](https://github.com/gakonst/ethers-rs/tree/master/ethers-providers/src/rpc/transports/ws) `->` [`alloy::transports::ws`](https://github.com/alloy-rs/alloy/tree/main/crates/transport-ws) * Signers: [`ethers::signers`](https://github.com/gakonst/ethers-rs/tree/master/ethers-signers) `->` Signer [`alloy::signers`](https://github.com/alloy-rs/alloy/tree/main/crates/signer) * AWS: [`ethers::signers::aws::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-signers/src/aws) `->` [`alloy::signers::aws`](https://github.com/alloy-rs/alloy/tree/main/crates/signer-aws) * Ledger: [`ethers::signers::ledger::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-signers/src/ledger) `->` [`alloy::signers::ledger`](https://github.com/alloy-rs/alloy/tree/main/crates/signer-ledger) * Trezor: [`ethers::signers::trezor::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-signers/src/trezor) `->` [`alloy::signer::trezor`](https://github.com/alloy-rs/alloy/tree/main/crates/signer-trezor) * Wallet: [`ethers::signers::wallet::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-signers/src/wallet) `->` [`alloy::signer::local`](https://github.com/alloy-rs/alloy/tree/main/crates/signer-local) ### Types #### Primitives * Address: [`ethers::types::Address`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::Address`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * U64: [`ethers::types::U64`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::U64`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * U128: [`ethers::types::U128`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::U128`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * U256: [`ethers::types::U256`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::U256`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * U512: [`ethers::types::U512`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::U512`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * H32: [`ethers::types::H32`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::aliases::B32`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * H64: [`ethers::types::H64`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::B64`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * H128: [`ethers::types::H128`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::B128`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * H160: [`ethers::types::H160`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::B160`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * H256: [`ethers::types::H256`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::B256`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * H512: [`ethers::types::H512`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::B512`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * Bloom: [`ethers::types::Bloom`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::Bloom`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * TxHash: [`ethers::types::TxHash`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) `->` [`alloy::primitives::TxHash`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) Due to a [limitation](https://github.com/alloy-rs/core/issues/554#issuecomment-1978620017) in `ruint`, BigEndianHash [`ethers::types::BigEndianHash`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/mod.rs) can be expressed as follows: ```rust use alloy_primitives::{U256, B256}; // `U256` => `B256` let x = B256::from(u256); // `B256` => `U256` let x: U256 = b256.into(); let x = U256::from_be_bytes(b256.into()) ``` Due to [Rust issue #50133](https://github.com/rust-lang/rust/issues/50133), the native `TryFrom` trait is not supported for `Uint`s. Instead, use [`UintTryFrom`](https://docs.rs/alloy/latest/alloy/primitives/ruint/trait.UintTryFrom.html) as follows: ```rust use alloy_primitives::ruint::UintTryFrom; let x: U512 = uint!(1234_U512); let y: U256 = U256::uint_try_from(x).unwrap(); let num = U16::from(300); // Wraps around the U16 value to fit it in the u8 type. let x = num.wrapping_to::(); assert_eq!(x, 44); // Saturates the expected type and returns the maximum value if the number is too large. let y = num.saturating_to::(); assert_eq!(y, 255); // Attempts to convert and panics if number is too large for the expected type. let z = num.to::(); ``` #### RPC * Bytes: [`ethers::types::bytes::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/bytes.rs) `->` [`alloy::primitives::Bytes`](https://github.com/alloy-rs/core/tree/main/crates/primitives/src/lib.rs) * Chains: [`ethers::types::Chain`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/chain.rs) `->` [`alloy-rs/chains`](https://github.com/alloy-rs/chains) * ENS: [`ethers::types::ens`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/ens.rs) `->` [`alloy-ens`](https://github.com/alloy-rs/alloy/blob/main/crates/ens/src/lib.rs) * Trace: [`ethers::types::trace::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/trace) `->` [`alloy::rpc::types::trace`](https://github.com/alloy-rs/alloy/tree/main/crates/rpc-types-trace) * {Block, Fee, Filter, Log, Syncing, Transaction, TxPool}: [`ethers::types::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types) `->` [`alloy::rpc::types::eth::*`](https://github.com/alloy-rs/alloy/tree/main/crates/rpc-types-eth/src/lib.rs) * Proof: [`ethers::types::proof::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/proof.rs) `->` Account [`alloy::rpc::types::eth::account::*`](https://github.com/alloy-rs/alloy/tree/main/crates/rpc-types-eth/src/lib.rs) * Signature: [`ethers::types::signature::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/signature.rs) `->` [`alloy::primitives::Signature*`](https://github.com/alloy-rs/core/blob/main/crates/primitives/src/signature/mod.rs) * Withdrawal [`ethers::types::withdrawal::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/withdrawal.rs) `->` EIP4895 [`alloy::eips::eip4895`](https://github.com/alloy-rs/alloy/tree/main/crates/eips/src/eip4895.rs) * Opcode: [`ethers::types::opcode::*`](https://github.com/gakonst/ethers-rs/tree/master/ethers-core/src/types/opcode.rs) `->` [`syn-solidity`](https://github.com/alloy-rs/core/tree/main/crates/syn-solidity) ### ABI * Bindings: [`abigen!`](https://github.com/gakonst/ethers-rs/tree/51fe937f6515689b17a3a83b74a05984ad3a7f11/ethers-contract/ethers-contract-abigen) `->` [`sol!`](https://github.com/alloy-rs/core/tree/main/crates/sol-types), available on [`alloy::sol`](https://github.com/alloy-rs/alloy/blob/aea7e07b4b335a3a35e3870a6c277d397d0f3932/crates/alloy/src/lib.rs#L52-L64). ## Conversions You can use the following traits to easily convert between ethers-rs and Alloy types. ```rust use alloy_primitives::{Address, Bloom, Bytes, B256, B64, I256, U256, U64}; use alloy_rpc_types::{AccessList, AccessListItem, BlockNumberOrTag}; use alloy_signer_wallet::LocalWallet; use ethers_core::types::{ transaction::eip2930::{ AccessList as EthersAccessList, AccessListItem as EthersAccessListItem, }, BlockNumber, Bloom as EthersBloom, Bytes as EthersBytes, H160, H256, H64, I256 as EthersI256, U256 as EthersU256, U64 as EthersU64, }; pub trait ToAlloy { /// The corresponding Alloy type. type To; /// Converts the Ethers type to the corresponding Alloy type. fn to_alloy(self) -> Self::To; } pub trait ToEthers { /// The corresponding Ethers type. type To; /// Converts the Alloy type to the corresponding Ethers type. fn to_ethers(self) -> Self::To; } impl ToAlloy for EthersBytes { type To = Bytes; #[inline(always)] fn to_alloy(self) -> Self::To { Bytes(self.0) } } impl ToAlloy for H64 { type To = B64; #[inline(always)] fn to_alloy(self) -> Self::To { B64::new(self.0) } } impl ToAlloy for H160 { type To = Address; #[inline(always)] fn to_alloy(self) -> Self::To { Address::new(self.0) } } impl ToAlloy for H256 { type To = B256; #[inline(always)] fn to_alloy(self) -> Self::To { B256::new(self.0) } } impl ToAlloy for EthersBloom { type To = Bloom; #[inline(always)] fn to_alloy(self) -> Self::To { Bloom::new(self.0) } } impl ToAlloy for EthersU256 { type To = U256; #[inline(always)] fn to_alloy(self) -> Self::To { U256::from_limbs(self.0) } } impl ToAlloy for EthersI256 { type To = I256; #[inline(always)] fn to_alloy(self) -> Self::To { I256::from_raw(self.into_raw().to_alloy()) } } impl ToAlloy for EthersU64 { type To = U64; #[inline(always)] fn to_alloy(self) -> Self::To { U64::from_limbs(self.0) } } impl ToAlloy for u64 { type To = U256; #[inline(always)] fn to_alloy(self) -> Self::To { U256::from(self) } } impl ToEthers for alloy_signer_wallet::LocalWallet { type To = ethers_signers::LocalWallet; fn to_ethers(self) -> Self::To { ethers_signers::LocalWallet::new_with_signer( self.signer().clone(), self.address().to_ethers(), self.chain_id().unwrap(), ) } } impl ToEthers for Vec { type To = Vec; fn to_ethers(self) -> Self::To { self.into_iter().map(ToEthers::to_ethers).collect() } } impl ToAlloy for EthersAccessList { type To = AccessList; fn to_alloy(self) -> Self::To { AccessList(self.0.into_iter().map(ToAlloy::to_alloy).collect()) } } impl ToAlloy for EthersAccessListItem { type To = AccessListItem; fn to_alloy(self) -> Self::To { AccessListItem { address: self.address.to_alloy(), storage_keys: self.storage_keys.into_iter().map(ToAlloy::to_alloy).collect(), } } } impl ToEthers for Address { type To = H160; #[inline(always)] fn to_ethers(self) -> Self::To { H160(self.0 .0) } } impl ToEthers for B256 { type To = H256; #[inline(always)] fn to_ethers(self) -> Self::To { H256(self.0) } } impl ToEthers for U256 { type To = EthersU256; #[inline(always)] fn to_ethers(self) -> Self::To { EthersU256(self.into_limbs()) } } impl ToEthers for U64 { type To = EthersU64; #[inline(always)] fn to_ethers(self) -> Self::To { EthersU64(self.into_limbs()) } } impl ToEthers for Bytes { type To = EthersBytes; #[inline(always)] fn to_ethers(self) -> Self::To { EthersBytes(self.0) } } impl ToEthers for BlockNumberOrTag { type To = BlockNumber; #[inline(always)] fn to_ethers(self) -> Self::To { match self { BlockNumberOrTag::Number(n) => BlockNumber::Number(n.into()), BlockNumberOrTag::Earliest => BlockNumber::Earliest, BlockNumberOrTag::Latest => BlockNumber::Latest, BlockNumberOrTag::Pending => BlockNumber::Pending, BlockNumberOrTag::Finalized => BlockNumber::Finalized, BlockNumberOrTag::Safe => BlockNumber::Safe, } } } ```

alloy

Connect applications to blockchains using performant, intuitive, and battle-tested APIs.
Get started GitHub
```bash [cargo] cargo add alloy ```
Simple Provider Interface
Wrap and pass `Provider` instances seamlessly
Handle Signers
Hold different signer types in one `EthereumWallet`
## Example: `deploy_from_contract` To run this example: * Clone the [examples](https://github.com/alloy-rs/examples) repository: `git clone git@github.com:alloy-rs/examples.git` * Run: `cargo run --locked -p examples-contracts --example deploy_from_contract` ```rust // [!include ~/snippets/contracts/examples/deploy_from_contract.rs] ``` Find the source code on Github [here](https://github.com/alloy-rs/examples/tree/5d087c1dd6ce42bbea7502ed3811efe389c91e10/examples/contracts/examples/deploy_from_contract.rs). ## Simply ABI encoding and decoding * [ABI encoding function return structs](https://alloy.rs/migrating-to-core-v1/encoding-decoding-changes/encoding-return-structs) * [Removing `validate: bool` from the `abi_decode` methods](https://alloy.rs/migrating-to-core-v1/encoding-decoding-changes/removing-validate-bool) ## sol! changes * [Removing the `T` transport generic](https://alloy.rs/migrating-to-core-v1/sol!-changes/removing-T-generic) * [Improving function return type](https://alloy.rs/migrating-to-core-v1/sol!-changes/improving-function-return-types) * [Changes to function call bindings](https://alloy.rs/migrating-to-core-v1/sol!-changes/changes-to-function-call-bindings) * [Changes to event bindings](https://alloy.rs/migrating-to-core-v1/sol!-changes/changes-to-event-bindings) * [Changes to error bindings](https://alloy.rs/migrating-to-core-v1/sol!-changes/changes-to-error-bindings)