### Install web3.py Tester and py-solc-x Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.contract.md Install the necessary packages for contract deployment examples. Ensure you have a compatible Solidity compiler installed. ```bash $ pip install -U "web3[tester]" ``` ```bash $ pip install py-solc-x ``` -------------------------------- ### Install Dependencies and Setup Virtual Environment Source: https://github.com/apeworx/web3.py/blob/main/docs/README-freebsd.md Installs necessary packages, creates a virtual environment, and activates it. Includes a workaround for a specific issue with alloca.h. ```shell sudo pkg install python3 py36-virtualenv git leveldb libxml2 libxslt pkgconf gmake secp256k1 # hack around https://github.com/ethereum/ethash/pull/107#issuecomment-445072692 sudo touch /usr/local/include/alloca.h mkdir -p /tmp/venv_python virtualenv-3.6 /tmp/venv_python/python3 source /tmp/venv_python/python3/bin/activate.csh pip install coincurve cd /tmp git clone https://github.com/ethereum/web3.py.git cd web3.py # assuming you're using tcsh pip install -e .[dev] ``` -------------------------------- ### Install web3.py Source: https://context7.com/apeworx/web3.py/llms.txt Install web3.py from PyPI. Include the 'tester' extra for local testing with EthereumTesterProvider. ```bash pip install web3 # For local testing with EthereumTesterProvider: pip install "web3[tester]" ``` -------------------------------- ### Run Async Example Source: https://github.com/apeworx/web3.py/blob/main/docs/providers.md This is the command to run an asynchronous example, likely involving a persistent connection provider. ```python asyncio.run(await_provider_connect_example()) ``` -------------------------------- ### Install web3.py Source: https://github.com/apeworx/web3.py/blob/main/README.md Use this command to install the web3.py library. Ensure you have Python 3.10+ installed. ```sh python -m pip install web3 ``` -------------------------------- ### Installing web3.py with Tester Extra Source: https://github.com/apeworx/web3.py/blob/main/docs/migration.md Shows the command to install web3.py with the necessary 'tester' extra for using `EthereumTesterProvider`. ```bash $ pip install web3[tester] ``` -------------------------------- ### Install Solidity Compiler Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.contract.md Install the latest version of the Solidity compiler using py-solc-x. ```python >>> from solcx import install_solc >>> install_solc(version='latest') ``` -------------------------------- ### Install and Configure geth for Integration Tests Source: https://github.com/apeworx/web3.py/blob/main/docs/README-freebsd.md Installs the Go compiler, clones the go-ethereum repository, builds the geth binary, and copies it to the system's PATH. ```shell pkg install go cd /tmp git clone https://github.com/ethereum/go-ethereum cd go-ethereum make geth cp build/bin/geth /usr/local/bin/ ``` -------------------------------- ### Ubuntu 16.04 web3.py Setup Script Source: https://github.com/apeworx/web3.py/blob/main/docs/README-linux.md A comprehensive script for setting up the web3.py development environment on Ubuntu 16.04. It updates the system, installs essential build tools and Python development headers, and clones and installs web3.py within a virtual environment. ```sh #!/bin/bash sudo apt-get update sudo apt-get -y upgrade sudo apt-get -y install build-essential #RESOLVES ERROR: unable to execute 'x86_64-linux-gnu-gcc': No such file or directory error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 sudo apt-get -y install python3-dev #RESOLVES ERROR: cytoolz/dicttoolz.c:17:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 sudo apt-get -y install python3-venv #RESOLVES ERROR: The virtual environment was not created successfully because ensurepip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command. cd ~ git clone https://github.com/ethereum/web3.py.git cd web3.py python3 -m venv venv . venv/bin/activate pip install --upgrade pip pip install -e ".[dev]" ``` -------------------------------- ### Install web3.py Source: https://github.com/apeworx/web3.py/blob/main/docs/quickstart.md Install the web3.py library using pip. It is recommended to do this within a virtual environment. ```shell $ pip install web3 ``` -------------------------------- ### Install and Set Up Virtual Environment Source: https://github.com/apeworx/web3.py/blob/main/docs/troubleshooting.md Commands to install pip and virtualenv, create a Python 3 virtual environment, activate it, and upgrade packaging tools. ```shell # Install pip if it is not available: $ which pip || curl https://bootstrap.pypa.io/get-pip.py | python # Install virtualenv if it is not available: $ which virtualenv || pip install --upgrade virtualenv # *If* the above command displays an error, you can try installing as root: $ sudo pip install virtualenv # Create a virtual environment: $ virtualenv -p python3 ~/.venv-py3 # Activate your new virtual environment: $ source ~/.venv-py3/bin/activate # With virtualenv active, make sure you have the latest packaging tools $ pip install --upgrade pip setuptools # Now we can install web3.py... $ pip install --upgrade web3 ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/apeworx/web3.py/blob/main/docs/contributing.md Install the necessary libraries for compiling contracts and formatting code. This includes `py-solc-x` and `black`. ```sh python -m pip install py-solc-x black ``` -------------------------------- ### Install LevelDB with Homebrew Source: https://github.com/apeworx/web3.py/blob/main/docs/README-osx.md Install the LevelDB database, a dependency for some web3.py functionalities, using Homebrew. ```shell brew install leveldb ``` -------------------------------- ### Full Subscription Example Source: https://github.com/apeworx/web3.py/blob/main/docs/subscriptions.md This example demonstrates subscribing to new block headers and transfer events from the WETH contract using WebSocketProvider. Ensure you provide a valid WebSocket RPC URL. ```python import asyncio from web3 import AsyncWeb3, WebSocketProvider from web3.utils.subscriptions import ( NewHeadsSubscription, NewHeadsSubscriptionContext, LogsSubscription, LogsSubscriptionContext, ) # -- declare handlers -- async def new_heads_handler( handler_context: NewHeadsSubscriptionContext, ) -> None: header = handler_context.result print(f"New block header: {header}\n") async def log_handler( handler_context: LogsSubscriptionContext, ) -> None: log_receipt = handler_context.result print(f"Log receipt: {log_receipt}\n") async def sub_manager(): # -- initialize provider -- w3 = await AsyncWeb3(WebSocketProvider("wss://... மதிப்பிடு")) # -- subscribe to event(s) -- await w3.subscription_manager.subscribe( [ NewHeadsSubscription( label="new-heads-mainnet", handler=new_heads_handler ), LogsSubscription( label="WETH transfers", address=w3.to_checksum_address( "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" ), topics=["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"], handler=log_handler, ), ] ) # -- listen for events -- await w3.subscription_manager.handle_subscriptions() asyncio.run(sub_manager()) ``` -------------------------------- ### Synchronous Event Listening Example Source: https://github.com/apeworx/web3.py/blob/main/docs/filters.md Example demonstrating how to synchronously listen for and process new events using filters. ```APIDOC ## Synchronous Event Listening ### Description This example shows how to set up a filter for new blocks and then poll for new entries, processing each event synchronously. ### Code Example ```python from web3 import Web3, IPCProvider import time # instantiate Web3 instance w3 = Web3(IPCProvider(...)) def handle_event(event): print(event) def log_loop(event_filter, poll_interval): while True: for event in event_filter.get_new_entries(): handle_event(event) time.sleep(poll_interval) def main(): block_filter = w3.eth.filter('latest') log_loop(block_filter, 2) if __name__ == '__main__': main() ``` ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/apeworx/web3.py/blob/main/docs/README-osx.md Install the Xcode command line tools necessary for development on macOS. ```shell xcode-select --install ``` -------------------------------- ### Initialize Web3 with EthereumTesterProvider Source: https://github.com/apeworx/web3.py/blob/main/docs/providers.md Instantiate the Web3 object using the EthereumTesterProvider for local testing. Ensure you have installed the necessary dependencies with `pip install "web3[tester]"`. ```python from web3 import Web3, EthereumTesterProvider w3 = Web3(EthereumTesterProvider()) ``` -------------------------------- ### Start HTTP JSON RPC Server - Geth Admin API Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.geth.md Starts the HTTP-based JSON RPC API webserver. It can be configured with host, port, CORS domains, and enabled APIs. Returns a boolean indicating if the server started successfully. Delegates to `admin_startHTTP`. ```python >>> web3.geth.admin.start_http() True ``` -------------------------------- ### Instantiate EthereumTesterProvider - Python Source: https://github.com/apeworx/web3.py/blob/main/docs/release_notes.md Provides an example of instantiating `EthereumTesterProvider`, which is a legitimate alternative to `web3.providers.tester.EthereumTesterProvider` for testing purposes. ```python web3.providers.eth_tester.main.EthereumTesterProvider() ``` -------------------------------- ### Install web3.py Testing Dependencies Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.contract.md Installs the necessary dependencies for contract unit testing with pytest, web3.py, eth-tester, and PyEVM. Use the '[test]' extra for a pinned version. ```bash $ pip install web3[test] pytest ``` -------------------------------- ### Get Web3 API Version Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.main.md Retrieves the current version of the Web3 library. No setup is required beyond having the library imported. ```python >>> web3.api "4.7.0" ``` -------------------------------- ### Get Genesis Information Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.beacon.md Retrieve the genesis information of the beacon chain, including the genesis time, validators root, and fork version. This method is useful for understanding the starting point of the chain. ```python beacon.get_genesis() ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/apeworx/web3.py/blob/main/docs/contributing.md Install the project's development dependencies, including linters and testing tools, using pip. This command installs the package in editable mode. ```sh $ python -m pip install -e ".[dev]" $ pre-commit install ``` -------------------------------- ### Compile and Deploy a Solidity Contract Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.contract.md Example demonstrating the compilation of a Solidity contract, deployment to a test network, and interaction with its functions. ```python >>> from web3 import Web3 >>> from solcx import compile_source # Solidity source code >>> compiled_sol = compile_source( ... ''' ... pragma solidity >0.5.0; ... ... contract Greeter { ... string public greeting; ... ... constructor() public { ... greeting = 'Hello'; ... } ... ... function setGreeting(string memory _greeting) public { ... greeting = _greeting; ... } ... ... function greet() view public returns (string memory) { ... return greeting; ... } ... }''', ... output_values=['abi', 'bin'] ... ) # retrieve the contract interface >>> contract_id, contract_interface = compiled_sol.popitem() # get bytecode / bin >>> bytecode = contract_interface['bin'] # get abi >>> abi = contract_interface['abi'] # web3.py instance >>> w3 = Web3(Web3.EthereumTesterProvider()) # set pre-funded account as sender >>> w3.eth.default_account = w3.eth.accounts[0] >>> Greeter = w3.eth.contract(abi=abi, bytecode=bytecode) # Submit the transaction that deploys the contract >>> tx_hash = Greeter.constructor().transact() # Wait for the transaction to be mined, and get the transaction receipt >>> tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash) >>> greeter = w3.eth.contract( ... address=tx_receipt.contractAddress, ... abi=abi ... ) >>> greeter.functions.greet().call() 'Hello' >>> tx_hash = greeter.functions.setGreeting('Nihao').transact() >>> tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash) >>> greeter.functions.greet().call() 'Nihao' ``` -------------------------------- ### Instantiate Web3 and AsyncWeb3 Source: https://github.com/apeworx/web3.py/blob/main/docs/migration.md Demonstrates the instantiation of both synchronous and asynchronous Web3 clients. Use `Web3` for synchronous operations and `AsyncWeb3` for asynchronous ones. ```python from web3 import Web3, AsyncWeb3 w3 = Web3(Web3.HTTPProvider()) async_w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider()) ``` -------------------------------- ### Deploy and Interact with a Smart Contract Source: https://github.com/apeworx/web3.py/blob/main/docs/transactions.md This example demonstrates deploying a simple contract and then interacting with it using both `transact()` for deployment and `build_transaction()` for subsequent function calls. It requires pre-compiled contract bytecode and ABI. ```python # After compiling the contract, initialize the contract factory: init_bytecode = "60806040523480156200001157600080fd5b5060..." abi = '[{"inputs": [{"internalType": "string","name": "_message",...]' Billboard = w3.eth.contract(bytecode=init_bytecode, abi=abi) # Deploy a contract using `transact` + the signer middleware: tx_hash = Billboard.constructor("gm").transact({"from": acct2.address}) receipt = w3.eth.get_transaction_receipt(tx_hash) deployed_addr = receipt["contractAddress"] # Reference the deployed contract: billboard = w3.eth.contract(address=deployed_addr, abi=abi) # Manually build and sign a transaction: unsent_billboard_tx = billboard.functions.writeBillboard("gn").build_transaction({ "from": acct2.address, "nonce": w3.eth.get_transaction_count(acct2.address), }) signed_tx = w3.eth.account.sign_transaction(unsent_billboard_tx, private_key=acct2.key) # Send the raw transaction: assert billboard.functions.message().call() == "gm" tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction) w3.eth.wait_for_transaction_receipt(tx_hash) assert billboard.functions.message().call() == "gn" ``` -------------------------------- ### Create and Use Local Account with Private Key Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.eth.account.md This script demonstrates how to load a private key from an environment variable, create an account object, and inject a signing middleware for sending transactions. Ensure the PRIVATE_KEY environment variable is set and starts with '0x'. ```python import os from eth_account import Account from eth_account.signers.local import LocalAccount from web3 import Web3, EthereumTesterProvider from web3.middleware import SignAndSendRawMiddlewareBuilder w3 = Web3(EthereumTesterProvider()) private_key = os.environ.get("PRIVATE_KEY") assert private_key is not None, "You must set PRIVATE_KEY environment variable" assert private_key.startswith("0x"), "Private key must start with 0x hex prefix" account: LocalAccount = Account.from_key(private_key) w3.middleware_onion.inject(SignAndSendRawMiddlewareBuilder.build(account), layer=0) print(f"Your hot wallet address is {account.address}") # Now you can use web3.eth.send_transaction(), Contract.functions.xxx.transact() functions # with your local private key through middleware and you no longer get the error # "ValueError: The method eth_sendTransaction does not exist/is not available ``` -------------------------------- ### Contract Code Example Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.contract.md Example Solidity contract code for demonstrating bytes array handling. ```python # pragma solidity >=0.4.22 <0.6.0; ... # contract ArraysContract { ... # bytes2[] public bytes2Value; ... ... # constructor(bytes2[] memory _bytes2Value) public { ... # bytes2Value = _bytes2Value; ... # } ... ... # function setBytes2Value(bytes2[] memory _bytes2Value) public { ... # bytes2Value = _bytes2Value; ... # } ... ... # function getBytes2Value() public view returns (bytes2[] memory) { ... # return bytes2Value; ... # } ... # } ... >>> # abi = "..." >>> # bytecode = "6080..." ``` -------------------------------- ### Configure Web3 Instance with HTTPProvider Source: https://github.com/apeworx/web3.py/blob/main/docs/troubleshooting.md Example of initializing a Web3 instance with an HTTPProvider to connect to a local Ethereum node. Ensure the instance is configured before use to avoid attribute errors. ```python >>> from web3 import Web3 >>> w3 = Web3(Web3.HTTPProvider('http://localhost:8545')) # now `w3` is available to use: >>> w3.is_connected() True >>> w3.eth.send_transaction(...) ``` -------------------------------- ### Async Formatter Builder Example Source: https://github.com/apeworx/web3.py/blob/main/docs/formatters.md Demonstrates how to build formatters asynchronously. This is useful when asynchronous operations are needed during the formatter building process. ```python async def async_build_formatters(async_w3, method): """Async version of formatter builder.""" chain_id = await async_w3.eth.chain_id # ... build formatters return { "request_formatters": {}, "result_formatters": {}, "error_formatters": {}, } custom_middleware = FormattingMiddlewareBuilder.build( sync_formatters_builder=build_formatters, async_formatters_builder=async_build_formatters, ) ``` -------------------------------- ### Start WebSocket JSON RPC Server - Geth Admin API Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.geth.md Starts the WebSocket-based JSON RPC API webserver. It can be configured with host, port, CORS domains, and enabled APIs. Returns a boolean indicating if the server started successfully. Delegates to `admin_startWS`. ```python >>> web3.geth.admin.start_ws() True ``` -------------------------------- ### Connect to Geth Dev PoA Instance (Sync) Source: https://github.com/apeworx/web3.py/blob/main/docs/providers.md Use this shortcut to connect to a `geth --dev` Proof of Authority instance with the POA middleware loaded by default. Confirms connection success. ```python >>> from web3.auto.gethdev import w3 # confirm that the connection succeeded >>> w3.is_connected() True ``` -------------------------------- ### Install Specific Geth Version Source: https://github.com/apeworx/web3.py/blob/main/docs/contributing.md Use py-geth to install a specific version of the Geth client locally, required for generating fixtures. ```sh $ python -m geth.install v1.16.7 ``` -------------------------------- ### Connect to Geth Dev PoA Instance (Async) Source: https://github.com/apeworx/web3.py/blob/main/docs/providers.md Use this shortcut to connect to an async `geth --dev` Proof of Authority instance with the POA middleware loaded by default. Confirms connection success. ```python >>> from web3.auto.gethdev import async_w3 >>> await async_w3.provider.connect() # confirm that the connection succeeded >>> await async_w3.is_connected() True ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/apeworx/web3.py/blob/main/docs/contributing.md Install dependencies specifically required for running tests. This ensures all necessary libraries are available for the testing environment. ```sh $ python -m pip install -e ".[test]" ``` -------------------------------- ### Error Formatters Example Source: https://github.com/apeworx/web3.py/blob/main/docs/formatters.md Provides an example of an error formatter that customizes error messages, specifically adding context for contract reverts. ```python from web3.middleware import FormattingMiddlewareBuilder def custom_error_formatter(error): """Add custom error handling.""" if "revert" in str(error.get("message", "")): error["message"] = f"Contract reverted: {error['message']}" return error custom_middleware = FormattingMiddlewareBuilder.build( error_formatters={ "eth_call": custom_error_formatter, } ) ``` -------------------------------- ### web3.geth.admin.start_http(host, port, cors, apis) Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.geth.md Starts the HTTP-based JSON RPC API webserver, configurable by host, port, CORS domains, and enabled APIs. ```APIDOC ## web3.geth.admin.start_http(host='localhost', port=8545, cors='', apis='eth,net,web3') ### Description Delegates to `admin_startHTTP` RPC Method. Starts the HTTP based JSON RPC API webserver on the specified `host` and `port`, with the `rpccorsdomain` set to the provided `cors` value and with the APIs specified by `apis` enabled. Returns boolean as to whether the server was successfully started. ### Method POST ### Endpoint /web3/geth/admin/start_http ### Parameters #### Query Parameters - **host** (string) - Optional - The host to bind the server to. Defaults to 'localhost'. - **port** (integer) - Optional - The port to bind the server to. Defaults to 8545. - **cors** (string) - Optional - The allowed CORS domains. Defaults to ''. - **apis** (string) - Optional - A comma-separated list of enabled APIs. Defaults to 'eth,net,web3'. ### Request Example { "host": "localhost", "port": 8545, "cors": "*", "apis": "eth,net,web3,admin" } ### Response #### Success Response (200) - **started** (boolean) - True if the server was successfully started, False otherwise. ### Response Example { "started": true } ``` -------------------------------- ### Get Contract Bytecode Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.eth.md Retrieves the bytecode for a given account address. Use this to check if an address is a contract or to get its deployed code. ```python web3.eth.get_code('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B') ``` ```python web3.eth.get_code('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') ``` -------------------------------- ### Install Package Dependencies with Homebrew Source: https://github.com/apeworx/web3.py/blob/main/docs/README-osx.md Install essential package dependencies like OpenSSL, libffi, autoconf, automake, and libtool using Homebrew. ```shell brew install openssl libffi autoconf automake libtool ``` -------------------------------- ### Generate Documentation Source: https://github.com/apeworx/web3.py/blob/main/docs/contributing.md Build the project's documentation. This command should be run before validating news fragments and releasing. ```sh make docs ``` -------------------------------- ### Initialize Web3 with HTTPProvider Source: https://github.com/apeworx/web3.py/blob/main/docs/internals.md Basic initialization of the Web3 instance using an HTTPProvider. Ensure the endpoint_uri is correctly set for your node. ```python from web3 import Web3, HTTPProvider from web3.utils import RequestCacheValidationThreshold w3 = Web3(HTTPProvider( endpoint_uri="...", ``` -------------------------------- ### Get Beacon Block Header Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.beacon.md Retrieves the header of a specific block. Use this to get block metadata without the full block content. ```python >>> beacon.get_block_header(1) { 'data': { 'root': '0x30c04689dd4f6cd4d56eb78f72727d2d16d8b6346724e4a88f546875f11b750d', 'canonical': True, 'header': { 'message': { 'slot': '1', 'proposer_index': '61090', 'parent_root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87', 'state_root': '0x7773ed5a7e944c6238cd0a5c32170663ef2be9efc594fb43ad0f07ecf4c09d2b', 'body_root': '0x30c04689dd4f6cd4d56eb78f72727d2d16d8b6346724e4a88f546875f11b750d' }, 'signature': '0xa30d70b3e62ff776fe97f7f8b3472194af66849238a958880510e698ec3b8a470916680b1a82f9d4753c023153fbe6db10c464ac532c1c9c8919adb242b05ef7152ba3e6cd08b730eac2154b9802203ead6079c8dfb87f1e900595e6c00b4a9a' } } } ``` -------------------------------- ### Create a New Account Source: https://github.com/apeworx/web3.py/blob/main/docs/troubleshooting.md Example of creating a new Ethereum account using the `eth-account` API provided by web3.py. Use caution with real value until security best practices are understood. ```python new_acct = w3.eth.account.create() ``` -------------------------------- ### Initialize Beacon API Instance Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.beacon.md Import and configure the Beacon API instance by providing the URL of your running beacon node. This is the first step to interacting with the Beacon API. ```python from web3.beacon import Beacon beacon = Beacon("http://localhost:5051") ``` -------------------------------- ### Install Unreleased Version for Manual Testing Source: https://github.com/apeworx/web3.py/blob/main/docs/contributing.md Install an unreleased version of web3.py from your development directory into another context. This is useful for manual testing before a release. ```sh python -m pip install -e ../path/to/web3py ``` -------------------------------- ### Install Linux Package Dependencies Source: https://github.com/apeworx/web3.py/blob/main/docs/README-linux.md Installs necessary development libraries for web3.py on Debian-like, ArchLinux, and Fedora systems. Ensure you use the command appropriate for your distribution. ```sh sudo apt-get install libssl-dev libffi-dev autoconf automake libtool # ^ This is for Debian-like systems. TODO: Add more platforms ``` ```sh sudo pacman -Sy libsecp256k1 # ^ This is for ArchLinux systems ``` ```sh sudo dnf install openssl-devel libffi-devel autoconf automake libtool # ^ This is for Fedora. ``` -------------------------------- ### ENS Setup Source: https://github.com/apeworx/web3.py/blob/main/docs/ens_overview.md Demonstrates different ways to create an ENS object for interacting with the Ethereum Name Service. ```APIDOC ## ENS Setup Create an `ENS` object (named `ns` below) in one of three ways: 1. Automatic detection 2. Specify an instance of a [provider](providers.md#providers) 3. From an existing [`web3.Web3`](web3.main.md#web3.Web3) object ```python # automatic detection from ens.auto import ns # or, with a provider from web3 import IPCProvider from ens import ENS provider = IPCProvider(...) ns = ENS(provider) # or, with a w3 instance # Note: This inherits the w3 middleware from the w3 instance and adds a stalecheck middleware to the middleware onion. # It also inherits the provider and codec from the w3 instance, as well as the ``strict_bytes_type_checking`` flag value. from ens import ENS w3 = Web3(...) ns = ENS.from_web3(w3) ``` Asynchronous support is available via the `AsyncENS` module: ```python from ens import AsyncENS ns = AsyncENS(provider) ``` Note that an `ens` module instance is also available on the `w3` instance. The first time it’s used, web3.py will create the `ens` instance using `ENS.from_web3(w3)` or `AsyncENS.from_web3(w3)` as appropriate. ```python # instantiate w3 instance from web3 import Web3, IPCProvider w3 = Web3(IPCProvider(...)) # use the module w3.ens.address('ethereum.eth') ``` #### ens.strict_bytes_type_checking The `ENS` instance has a `strict_bytes_type_checking` flag that toggles the flag with the same name on the `Web3` instance attached to the `ENS` instance. You may disable the stricter bytes type checking that is loaded by default using this flag. For more examples, see [Disabling Strict Checks for Bytes Types](web3.contract.md#disable-strict-byte-check) If instantiating a standalone ENS instance using `ENS.from_web3()`, the ENS instance will inherit the value of the flag on the Web3 instance at time of instantiation. However, if accessing the `ENS` class via the `Web3` instance as a module (`w3.ens`), since all modules use the same `Web3` object reference under the hood (the parent `w3` object), changing the `strict_bytes_type_checking` flag value on `w3` also changes the flag state for `w3.ens.w3` and all modules. ``` -------------------------------- ### Initialize and Run Event Scanner Source: https://github.com/apeworx/web3.py/blob/main/docs/filters.md Sets up the Web3 instance, contract, and event scanner, then initiates the block scanning process. It includes logic for handling chain reorgs and progress reporting. ```python def run(): if len(sys.argv) < 2: print("Usage: eventscanner.py http://your-node-url") sys.exit(1) api_url = sys.argv[1] # Enable logs to the stdout. # DEBUG is very verbose level logging.basicConfig(level=logging.INFO) provider = HTTPProvider(api_url) # Disable the default JSON-RPC retry configuration # as it correctly cannot handle eth_getLogs block range provider.exception_retry_configuration = None w3 = Web3(provider) # Prepare stub ERC-20 contract object abi = json.loads(ABI) ERC20 = w3.eth.contract(abi=abi) # Restore/create our persistent state state = JSONifiedState() state.restore() # chain_id: int, w3: Web3, abi: Dict, state: EventScannerState, events: List, filters: Dict, max_chunk_scan_size: int=10000 scanner = EventScanner( w3=w3, contract=ERC20, state=state, events=[ERC20.events.Transfer], filters={"address": RCC_ADDRESS}, # How many maximum blocks at the time we request from JSON-RPC # and we are unlikely to exceed the response size limit of the JSON-RPC server max_chunk_scan_size=10000 ) # Assume we might have scanned the blocks all the way to the last Ethereum block # that mined a few seconds before the previous scan run ended. # Because there might have been a minor Ethereum chain reorganisations # since the last scan ended, we need to discard # the last few blocks from the previous scan results. chain_reorg_safety_blocks = 10 scanner.delete_potentially_forked_block_data(state.get_last_scanned_block() - chain_reorg_safety_blocks) # Scan from [last block scanned] - [latest ethereum block] # Note that our chain reorg safety blocks cannot go negative start_block = max(state.get_last_scanned_block() - chain_reorg_safety_blocks, 0) end_block = scanner.get_suggested_scan_end_block() blocks_to_scan = end_block - start_block print(f"Scanning events from blocks {start_block} - {end_block}") # Render a progress bar in the console start = time.time() with tqdm(total=blocks_to_scan) as progress_bar: def _update_progress(start, end, current, current_block_timestamp, chunk_size, events_count): if current_block_timestamp: formatted_time = current_block_timestamp.strftime("%d-%m-%Y") ``` -------------------------------- ### web3.geth.admin.start_ws(host, port, cors, apis) Source: https://github.com/apeworx/web3.py/blob/main/docs/web3.geth.md Starts the WebSocket-based JSON RPC API webserver, configurable by host, port, CORS domains, and enabled APIs. ```APIDOC ## web3.geth.admin.start_ws(host='localhost', port=8546, cors='', apis='eth,net,web3') ### Description Delegates to `admin_startWS` RPC Method. Starts the WebSocket based JSON RPC API webserver on the specified `host` and `port`, with the `rpccorsdomain` set to the provided `cors` value and with the APIs specified by `apis` enabled. Returns boolean as to whether the server was successfully started. ### Method POST ### Endpoint /web3/geth/admin/start_ws ### Parameters #### Query Parameters - **host** (string) - Optional - The host to bind the server to. Defaults to 'localhost'. - **port** (integer) - Optional - The port to bind the server to. Defaults to 8546. - **cors** (string) - Optional - The allowed CORS domains. Defaults to ''. - **apis** (string) - Optional - A comma-separated list of enabled APIs. Defaults to 'eth,net,web3'. ### Request Example { "host": "localhost", "port": 8546, "cors": "*", "apis": "eth,net,web3,admin" } ### Response #### Success Response (200) - **started** (boolean) - True if the server was successfully started, False otherwise. ### Response Example { "started": true } ``` -------------------------------- ### Compile, Deploy, and Interact with a Solidity Contract Source: https://context7.com/apeworx/web3.py/llms.txt Demonstrates the full lifecycle of interacting with a Solidity contract: compilation, deployment, binding to an address, reading state, writing state, building transactions manually, and estimating gas. ```python from web3 import Web3 from solcx import compile_source, install_solc install_solc(version='latest') w3 = Web3(Web3.EthereumTesterProvider()) compiled = compile_source( ''' pragma solidity >0.5.0; contract Greeter { string public greeting; constructor() public { greeting = 'Hello'; } function setGreeting(string memory _greeting) public { greeting = _greeting; } function greet() view public returns (string memory) { return greeting; } } ''', output_values=['abi', 'bin'] ) _, contract_interface = compiled.popitem() bytecode = contract_interface['bin'] abi = contract_interface['abi'] # Create contract factory: Greeter = w3.eth.contract(abi=abi, bytecode=bytecode) # Deploy: tx_hash = Greeter.constructor().transact() receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(receipt['contractAddress']) # '0x...' # Bind to deployed address: greeter = w3.eth.contract(address=receipt['contractAddress'], abi=abi) # Read state (eth_call, no gas): print(greeter.functions.greet().call()) # 'Hello' # Write state (transaction, costs gas): tx = greeter.functions.setGreeting('Nihao').transact() w3.eth.wait_for_transaction_receipt(tx) print(greeter.functions.greet().call()) # 'Nihao' # Build transaction manually (for local signing): unsigned_tx = greeter.functions.setGreeting('gm').build_transaction({ 'nonce': w3.eth.get_transaction_count(w3.eth.accounts[0]), 'maxFeePerGas': w3.to_wei(100, 'gwei'), 'maxPriorityFeePerGas': w3.to_wei(2, 'gwei'), }) print(unsigned_tx['data']) # ABI-encoded calldata # Estimate gas cost: gas = greeter.functions.setGreeting('test').estimate_gas() print(gas) # e.g. 35412 ``` -------------------------------- ### WebSocket One-to-One Request Example Source: https://github.com/apeworx/web3.py/blob/main/docs/internals.md Demonstrates making a one-to-one request (fetching the latest block number) using AsyncWeb3 with a WebSocketProvider. This example requires an active WebSocket connection to a local node. ```python >>> async def ws_one_to_one_example(): ... async with AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")) as w3: ... # make a request and expect a single response returned on the same line ... latest_block_num = await w3.eth.block_number >>> asyncio.run(ws_one_to_one_example()) ``` -------------------------------- ### Initialize IPCProvider Source: https://github.com/apeworx/web3.py/blob/main/docs/providers.md Instantiate the IPCProvider with the filesystem path to the IPC socket. If no path is provided, a default path based on the OS will be used. ```python >>> from web3 import Web3 >>> w3 = Web3(Web3.IPCProvider("~/Library/Ethereum/geth.ipc")) ``` -------------------------------- ### Instantiate Web3 with Custom Middleware Source: https://github.com/apeworx/web3.py/blob/main/docs/middleware.md Allows initializing the Web3 instance with a custom list of middleware, replacing the default ones. ```APIDOC ## Instantiate with Custom Middleware ### Description Instead of working from the default list, you can specify a custom list of middleware when initializing Web3. This will replace the default middleware. ### Usage ```python Web3(middleware=[my_middleware1, my_middleware2]) ``` ### WARNING This will *replace* the default middleware. To keep the default functionality, either use `middleware_onion.add()` after initialization, or include the default middleware in your custom list. ```