web3.py

repository·main·Indexed 26 days ago

https://github.com/apeworx/web3.py

A Python library that enables developers to interact with the Ethereum blockchain, allowing for the creation of decentralized applications and smart contract interactions. It includes modules for common Ethereum constants and a comprehensive ENS (Ethereum Name Service) interface for resolving names to addresses, managing records, and handling text metadata via both synchronous and asynchronous APIs.

Tokens
60.7K
Snippets
162
Records
290
Agent score
90%

What's inside web3.py

  1. Overview of web3.py

    main

    web3.py is a Python library designed for interacting with the Ethereum blockchain and other EVM-compatible blockchains. It is primarily used in decentralized applications (dapps) for tasks such as:

    • Sending transactions
    • Interacting with smart contracts
    • Reading block data
    • Various other blockchain-related use cases
  2. Use the Gas Price API for legacy transactions

    main

    The Gas Price API allows you to define how Web3 populates the gasPrice for Ethereum (legacy) transactions using a "Gas Price Strategy".

    Warning: Gas price strategies are only supported for legacy transactions. For modern transactions (post-London fork), you should use maxFeePerGas and maxPriorityFeePerGas instead of gasPrice whenever possible.

  3. Explore Ethereum Python ecosystem tools and frameworks

    main

    For developers building on Ethereum with Python, consider these tools:

    Frameworks and Tooling

    • Ape: The Ethereum development framework for Python Developers, Data Scientists, and Security Professionals (apeworx.io)
    • Titanoboa: A Vyper interpreter and testing framework
    • Wake: A Python-based development and testing framework for Solidity
    • Brownie: [No longer actively maintained] A Python-based development and testing framework for smart contracts targeting EVM

    Smart Contract Languages

    • Vyper: A contract-oriented, pythonic programming language that targets EVM
  4. Understand AttributeDict behavior in web3.eth

    main

    By default, many web3.eth properties and methods return an AttributeDict. This object behaves like a standard Python dict but allows you to access keys as attributes. Note that AttributeDict objects are immutable; attempting to modify a field will raise a TypeError.

    Warning on Type Hinting: Accessing properties via attribute (e.g., block.number) will break type hinting. If your application requires strict typing, access values using standard dictionary key syntax (e.g., block['number']) or remove the AttributeDictMiddleware.

    >>> block = web3.eth.get_block('latest')
    AttributeDict({
      'hash': '0xe8ad537a261e6fff80d551d8d087ee0f2202da9b09b64d172a5f45e818eb472a',
      'number': 4022281,
    })
    
    >>> block['number']
    4022281
    >>> block.number
    4022281
    
    >>> block.number = 4022282
    Traceback ...
    TypeError: This data is immutable -- create a copy instead of modifying
  5. Understand the Web3 architecture layers

    main

    The Web3 library uses multiple layers of abstraction between the public API and the blockchain node. Understanding these layers is essential for advanced users looking to customize request behavior:

    • Providers: Handle the actual communication with the blockchain (e.g., sending JSON-RPC requests via HTTP or IPC sockets).
    • Middleware: Act as hooks to monitor or modify requests and responses as they pass to and from the provider.
    • Managers: Provide thread safety and primitives to enable asynchronous usage of the web3 object.
  6. Understand web3.py Formatters

    main

    Formatters are part of the data transformation pipeline in web3.py. They handle the conversion between Python-friendly types and the hexadecimal formats required by the Ethereum JSON-RPC specification.

    There are four types of formatters:

    1. Request Formatters: Convert Python types (like integers) to JSON-RPC compatible formats (like hex strings) before sending requests to the node.
    2. Result Formatters: Convert JSON-RPC responses (like hex strings) back into Python types (like integers or HexBytes).
    3. Error Formatters: Process error responses to raise appropriate exceptions.
    4. Null Result Formatters: Handle empty or None responses.
  7. Understand Web3 Middleware

    main

    Middleware layers sit between the public Web3 methods and the providers. They are used to perform tasks like sanity checks, data type conversion, and enabling ENS support.

    Each layer is invoked before a request reaches the provider and processes the response in reverse order (from the innermost layer back to the outermost). A middleware can return early, preventing the request from reaching the provider or deeper middleware layers.

  8. Use the Tracing API to interact with Erigon and Nethermind

    main
    The web3.tracing object provides access to JSON-RPC trace_ endpoints. This API is specifically designed for interacting with Ethereum clients that support tracing, such as Erigon and Nethermind. It allows for deep inspection of blockchain state changes by tracing transactions, blocks, and calls.
  9. Create or import accounts in web3.py

    main

    You have three primary ways to manage accounts:

    1. Create a new account via API: Use w3.eth.account.create().
    2. Import a keystore file: Import an existing account and extract the private key.
    3. Use external services (e.g., MetaMask): Export your private key from MetaMask and use web3.py's local private key tools to sign and send transactions.

    Warning: Do not store real value in an account until you are familiar with security best practices. If you lose your private key, you lose your account.

    new_acct = w3.eth.account.create()
  10. Develop using Docker

    main

    You can use the provided sandbox container defined in docker-compose.yml for your development workflow.

    1. Start the environment: docker compose up -d
    2. Run core tests: docker compose exec sandbox bash -c 'pytest tests/core'
    3. Run integration tests (excluding go-ethereum tests): docker compose exec sandbox bash -c 'pytest tests/integration -k "not goethereum"'
    4. Open an interactive session: docker compose exec sandbox bash
    $ docker compose up -d
    $ docker compose exec sandbox bash -c 'pytest tests/core'
    $ docker compose exec sandbox bash -c 'pytest tests/integration -k "not goethereum"'
  11. Install web3.py developer environment on FreeBSD

    main

    Follow these steps to set up a development environment for web3.py on FreeBSD (11.2). This process includes installing system dependencies, applying a necessary header hack, and setting up a virtual environment.

    Note: The installation steps assume you are using tcsh.

    1. Install system packages via pkg.
    2. Apply the alloca.h hack required for certain dependencies.
    3. Create and activate a Python 3 virtual environment.
    4. Install coincurve.
    5. Clone the repository and install in editable development mode.