Alloy Examples

repository·main·Indexed 42 days ago

https://github.com/alloy-rs/examples

A 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.

Tokens
3.7K
Snippets
16
Records
23
Agent score
53%

What's inside Alloy

  1. Overview of Alloy Examples

    main
    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.
  2. Performance Benchmarks for Alloy

    main

    Alloy 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 Static encoding (up to 12.32x).
    • Serde: Highly optimized Serialize performance (up to 20.29x faster).
    • RLP: Faster Encoding and Decoding compared to Parity-Rlp.
    • U256 Operations: Faster arithmetic operations like amountIn and amountOut compared to Ethers.
  3. Explore Alloy Examples by Category

    main

    The 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_abi and json_abi.
  4. Configure network endpoints for Alloy examples

    main

    Many 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_URLS with a comma-separated list of endpoints.

    Note on Networks: Ensure the endpoint matches the network expected by the specific example. For instance, any_network expects an Arbitrum Sepolia endpoint, while mainnet contract and ENS examples 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
  5. Benchmark Serialize/Deserialize Function Signature performance

    main
    Alloy demonstrates superior performance when using serde to serialize and deserialize large function signatures compared to EthAbi. Specifically, serialization of large signatures is significantly faster in Alloy.
  6. Benchmark ABI Encoding performance

    main

    Alloy provides high-performance ABI encoding for both static and dynamic function calls. In benchmarks comparing the Uniswap V2 swap function against Ethers, Alloy demonstrates significant speed advantages, particularly in static encoding.

    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
  7. Benchmark U256 Operations performance

    main
    Alloy's U256 implementation is optimized for high-speed arithmetic operations. Benchmarks using Uniswap V2 swap calculations (computing amountIn and amountOut) show that Alloy is significantly faster than comparable implementations.
  8. Benchmark JSON-ABI Serialization and Deserialization performance

    main
    Alloy provides JSON-ABI serialization and deserialization capabilities. Performance is compared against ethabi using 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.
  9. Benchmark RLP Encoding and Decoding performance

    main

    Alloy's RLP (Recursive Length Prefix) implementation is designed for high performance. To use Alloy's RLP capabilities, derive the alloy_rlp::RlpEncodable and alloy_rlp::RlpDecodable traits on your structs. Benchmarks against Parity-Rlp show 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>,
    }
  10. Discover examples programmatically via examples-index.json

    main

    For automated discovery or programmatic access to the available examples, use the examples-index.json file. 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
  11. Calculate Uniswap V2 amount in

    main

    The get_amount_in function calculates the required amount_in to 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
    );