Alloy Examples
repository·main·Indexed 42 days ago
https://github.com/alloy-rs/examplesA collection of practical examples and performance benchmarks for the alloy and alloy-core libraries. Covers Ethereum development tasks including contract interaction via the sol! macro, transaction management (EIP-1559, EIP-4844, EIP-7702), provider configuration (HTTP, WS, IPC), wallet signers, and ENS resolution. Includes benchmarks for ABI encoding, RLP, and U256 operations comparing Alloy against Ethers and EthAbi.
What's inside Alloy
- This repository serves as a comprehensive collection of practical examples for the Alloy ecosystem. It covers a wide range of Ethereum-related development tasks, including contract interaction, transaction management, provider configuration, and advanced cryptographic operations. Developers can use these examples to understand how to implement specific features or to find boilerplate code for common blockchain workflows.
Performance Benchmarks for Alloy
mainAlloy provides performance comparisons against other common Ethereum libraries (such as
Ethers,EthAbi,Parity-Rlp) across several critical operations. Key performance advantages include:- ABI Encoding: Significantly faster for
Staticencoding (up to 12.32x). - Serde: Highly optimized
Serializeperformance (up to 20.29x faster). - RLP: Faster
EncodingandDecodingcompared toParity-Rlp. - U256 Operations: Faster arithmetic operations like
amountInandamountOutcompared toEthers.
- ABI Encoding: Significantly faster for
Explore Alloy Examples by Category
mainThe examples are organized into several functional categories to help you find specific implementation patterns:
Core Ethereum Operations
- Providers: Configuring HTTP, WS, IPC, and Mock providers, including batching and authentication.
- Transactions: Encoding/decoding envelopes, sending various transaction types (EIP-1559, EIP-4844, EIP-7702, etc.), and simulating calls.
- Contracts: Deploying from artifacts/bytecode, interacting with ABIs, and handling custom error decoding.
- Subscriptions: Watching blocks, logs, and the pending mempool.
- Wallets: Using various signers like Private Key, Mnemonic, Ledger, Trezor, and cloud-based signers (AWS, GCP, Turnkey).
Specialized Utilities
- Big Numbers: Math operations, conversions, and comparisons for large integers.
- ENS: Resolving names to addresses and vice versa.
- Fillers (Middleware): Automating gas estimation, nonce management, and wallet management.
- Layers: Adding functionality like logging, retries, fallbacks, and delays to providers.
- Queries: Querying contract storage, bytecode, and logs.
sol!macro: Using the macro for contracts, events, errors, and complex types like structs and enums.
Advanced Use Cases
- Node Bindings: Interacting with local Anvil, Geth, or Reth instances.
- Arbitrage: Simulating and calculating profits for Uniswap V2/Sushiswap pools.
- ABI Handling: Dynamic encoding/decoding with
dyn_abiandjson_abi.
Configure network endpoints for Alloy examples
mainMany examples require a connection to a live network or a local fork. You must provide the connection details via environment variables depending on the protocol used:
- HTTP/HTTPS: Use
RPC_URL. - WebSocket: Use
WS_URL. - IPC: Use
IPC_PATH. - Fallback Layer: Use
RPC_URLSwith a comma-separated list of endpoints.
Note on Networks: Ensure the endpoint matches the network expected by the specific example. For instance,
any_networkexpects an Arbitrum Sepolia endpoint, whilemainnetcontract andENSexamples expect Ethereum mainnet.# HTTP example RPC_URL=https://your-ethereum-endpoint cargo run --example http # WebSocket example WS_URL=wss://your-websocket-endpoint cargo run --example <example_name> # IPC example IPC_PATH=/tmp/eth.ipc cargo run --example <example_name> # Fallback layer with multiple endpoints RPC_URLS=https://first-endpoint,https://second-endpoint cargo run --example fallback_layer- HTTP/HTTPS: Use
Run Alloy examples
mainTo execute a specific example from the repository, use the
cargo runcommand with the--exampleflag followed by the name of the example.cargo run --example mnemonic_signerBenchmark Serialize/Deserialize Function Signature performance
mainAlloy demonstrates superior performance when usingserdeto serialize and deserialize large function signatures compared toEthAbi. Specifically, serialization of large signatures is significantly faster in Alloy.Benchmark ABI Encoding performance
mainAlloy provides high-performance ABI encoding for both static and dynamic function calls. In benchmarks comparing the Uniswap V2
swapfunction againstEthers, Alloy demonstrates significant speed advantages, particularly in static encoding.function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;Benchmark U256 Operations performance
mainAlloy'sU256implementation is optimized for high-speed arithmetic operations. Benchmarks using Uniswap V2swapcalculations (computingamountInandamountOut) show that Alloy is significantly faster than comparable implementations.Benchmark JSON-ABI Serialization and Deserialization performance
mainAlloy provides JSON-ABI serialization and deserialization capabilities. Performance is compared againstethabiusing complex contract structures like Seaport, Uniswap V4 Pool Manager, and Uniswap V3 Pool. While performance varies by contract type, Alloy remains competitive in serialization and deserialization tasks.Benchmark RLP Encoding and Decoding performance
mainAlloy's RLP (Recursive Length Prefix) implementation is designed for high performance. To use Alloy's RLP capabilities, derive the
alloy_rlp::RlpEncodableandalloy_rlp::RlpDecodabletraits on your structs. Benchmarks againstParity-Rlpshow Alloy is faster for both encoding and decoding.#[derive(alloy_rlp::RlpEncodable, alloy_rlp::RlpDecodable, rlp_derive::RlpDecodable, rlp_derive::RlpEncodable)] pub struct MyStruct { pub a: u128, pub b: Vec<u8>, }Discover examples programmatically via examples-index.json
mainFor automated discovery or programmatic access to the available examples, use the
examples-index.jsonfile. This index is generated from Cargo metadata and contains the following information for every example:- Summary
- Source path
- Exact command
- Required network
- Required environment variables
- Required binaries
- Required services
- Hardware requirements
Calculate Uniswap V2 amount in
mainThe
get_amount_infunction calculates the requiredamount_into receive a specific amount of output, given the current reserves and token ordering.use alloy::primitives::U256; use helpers::get_amount_in; let amount_in = get_amount_in( reserves00, // reserves00 reserves01, // reserves01 is_weth0, // is_weth0 reserves10, // reserves10 reserves11, // reserves11 );