### Install web3.py using pip Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/quickstart.rst Installs the web3.py library using pip. It is recommended to perform this installation within a virtual environment. ```shell $ pip install web3 ``` -------------------------------- ### Connect to EthereumTesterProvider Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/quickstart.rst Connects to a test Ethereum provider using EthereumTesterProvider. This provider is useful for quick prototyping and testing, offering pre-funded accounts and instant block inclusion. It requires additional dependencies to be installed. ```python from web3 import Web3, EthereumTesterProvider w3 = Web3(EthereumTesterProvider()) w3.is_connected() True ``` -------------------------------- ### Install XCode Command Line Tools Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/README-osx.md Installs the necessary command line developer tools for macOS. This is a prerequisite for many development tasks. ```shell xcode-select --install ``` -------------------------------- ### Ubuntu 16.04 web3.py Development Setup Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/README-linux.md A comprehensive script for setting up the web3.py development environment on Ubuntu 16.04. It updates the system, installs build essentials, Python development headers, virtual environment tools, and clones and installs web3.py. ```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]" ``` -------------------------------- ### Initialize AsyncIPCProvider and WebSocketProvider with AsyncWeb3 Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/providers.rst This example demonstrates how to initialize AsyncWeb3 with either an AsyncIPCProvider or a WebSocketProvider and use it as an asynchronous context manager. It includes optional debug logging setup for the providers. The context manager ensures the connection is properly closed upon exiting. ```python >>> import asyncio >>> from web3 import AsyncWeb3 >>> from web3.providers.persistent import ( ... AsyncIPCProvider, ... WebSocketProvider, ... ) >>> LOG = True # toggle debug logging >>> if LOG: ... import logging ... # logger = logging.getLogger("faster_web3.providers.AsyncIPCProvider") # for the AsyncIPCProvider ... logger = logging.getLogger("faster_web3.providers.WebSocketProvider") # for the WebSocketProvider ... logger.setLevel(logging.DEBUG) ... logger.addHandler(logging.StreamHandler()) >>> async def context_manager_subscription_example(): ... # async with AsyncWeb3(AsyncIPCProvider("./path/to.filename.ipc") as w3: # for the AsyncIPCProvider ... async with AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")) as w3: # for the WebSocketProvider ... # subscribe to new block headers ... subscription_id = await w3.eth.subscribe("newHeads") ... ... async for response in w3.socket.process_subscriptions(): ... ``` -------------------------------- ### Install Dev Dependencies for Benchmarks Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/benchmarks/README.md Installs all development dependencies required to run the benchmarks, including necessary testing and benchmarking tools. ```bash pip install .[dev] ``` -------------------------------- ### Install LevelDB with Homebrew Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/README-osx.md Installs the LevelDB key-value store using Homebrew. LevelDB is often used as a backend for databases or caching mechanisms. ```shell brew install leveldb ``` -------------------------------- ### Installing Web3.py with Tester Extra Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/migration.rst Shows the command to install web3.py with the necessary 'tester' extra, which is required for using the EthereumTesterProvider in v4. ```bash $ pip install web3[tester] ``` -------------------------------- ### Get Latest Block Information Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/quickstart.rst Retrieves and displays information about the latest block on the Ethereum blockchain using the web3.py library. This function requires a configured web3 instance connected to an Ethereum node. ```python w3.eth.get_block('latest') { 'difficulty': 1, 'gasLimit': 6283185, 'gasUsed': 0, 'hash': HexBytes('0x53b983fe73e16f6ed8178f6c0e0b91f23dc9dad4cb30d0831f178291ffeb8750'), 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'miner': '0x0000000000000000000000000000000000000000', 'mixHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'nonce': HexBytes('0x0000000000000000') } ``` -------------------------------- ### Install Web3 Tester and py-solc-x for Contract Deployment in Bash Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.contract.rst Installs necessary Python packages for testing smart contracts with web3.py and compiling Solidity code. Requires pip and a compatible Python environment. ```bash pip install -U "web3[tester]" pip install py-solc-x ``` -------------------------------- ### Install Linux Package Dependencies for web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/README-linux.md Installs necessary system packages required for building and running web3.py on different Linux distributions. This includes SSL and FFI libraries, build tools, and specific packages for ArchLinux and Fedora. ```sh sudo apt-get install libssl-dev libffi-dev autoconf automake libtool # ^ This is for Debian-like systems. TODO: Add more platforms sudo pacman -Sy libsecp256k1 # ^ This is for ArchLinux systems sudo dnf install openssl-devel libffi-devel autoconf automake libtool # ^ This is for Fedora. ``` -------------------------------- ### Install Test Dependencies for Web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/contributing.rst Installs the necessary test dependencies for the web3.py library using pip. This command ensures that all required packages for running tests, including those for Geth integration, are available in the current Python environment. The output is the installation of packages. ```sh $ python -m pip install -e ".[test]" ``` -------------------------------- ### Setup ENS Object - Python Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/ens_overview.rst Demonstrates three ways to create an ENS object: automatic detection, specifying a provider, or from an existing Web3 instance. This setup is crucial for interacting with ENS functionalities. ```python from ens.auto import ns from web3 import IPCProvider from ens import ENS provider = IPCProvider(...) ns = ENS(provider) from ens import ENS w3 = Web3(...) ns = ENS.from_web3(w3) ``` -------------------------------- ### Install Test Dependencies for web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/contributing.rst Installs the project in editable mode with test dependencies. This is a prerequisite for running the test suite. ```sh python -m pip install -e ".[test]" ``` -------------------------------- ### Initialize Web3 with EthereumTesterProvider (Python) Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/providers.rst This snippet demonstrates how to initialize the Web3.py library using the EthereumTesterProvider. This provider allows for testing smart contracts and dApps against an in-memory Ethereum blockchain. Ensure you have installed the necessary dependencies using 'pip install "web3[tester]"'. ```python from web3 import Web3, EthereumTesterProvider w3 = Web3(EthereumTesterProvider()) ``` -------------------------------- ### Example: Subscribe to Block Headers and Transfer Events Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/subscriptions.rst An example demonstrating how to subscribe to new block headers and WETH transfer events using AsyncWeb3 and WebSocketProvider. It includes defining handlers for each event type. ```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()) ``` -------------------------------- ### Install Web3.py Testing Dependencies - Bash Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.contract.rst Provides the bash command to install the necessary dependencies for unit testing with web3.py, pytest, and eth-tester. This command uses pip with the 'test' extra to ensure all testing-related packages are included. ```bash $ pip install web3[test] pytest ``` -------------------------------- ### Connect to Local Ethereum Nodes (IPC, HTTP, WebSocket) Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/quickstart.rst Demonstrates connecting to locally run Ethereum nodes using various providers: IPCProvider, HTTPProvider, and WebSocketProvider. It also shows asynchronous connections using AsyncWeb3 and its corresponding providers. Ensure the node is running and accessible at the specified endpoints. ```python from web3 import Web3, AsyncWeb3 # IPCProvider: w3 = Web3(Web3.IPCProvider('./path/to/filename.ipc')) w3.is_connected() True # HTTPProvider: w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545')) w3.is_connected() True # AsyncHTTPProvider: w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider('http://127.0.0.1:8545')) await w3.is_connected() True # -- Persistent Connection Providers -- # # WebSocketProvider: w3 = await AsyncWeb3(AsyncWeb3.WebSocketProvider('ws://127.0.0.1:8546')) await w3.is_connected() True # AsyncIPCProvider: w3 = await AsyncWeb3(AsyncWeb3.AsyncIPCProvider('./path/to/filename.ipc')) await w3.is_connected() True ``` -------------------------------- ### Connecting to Geth Development Instance Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/middleware.rst This example demonstrates connecting to a local geth --dev instance using IPCProvider on Linux. It initializes a Web3 instance and confirms the connection by printing the client version. The ExtraDataToPOAMiddleware is automatically loaded for geth development instances. ```python from web3 import Web3, IPCProvider # Example for a Linux geth dev instance with a specific IPC path # w3 = Web3(IPCProvider('/path/to/geth.ipc')) # Example using web3.auto.gethdev which handles default configurations from web3.auto.gethdev import w3 # Confirm connection # print(w3.client_version) ``` -------------------------------- ### Connect to Remote Ethereum Node Providers Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/quickstart.rst Shows how to connect to remote Ethereum node providers using HTTP and WebSocket protocols. This is a quick way to interact with the blockchain, typically requiring an account with a remote node service provider. Replace '' with your actual provider endpoint. ```python from web3 import Web3, AsyncWeb3 w3 = Web3(Web3.HTTPProvider('https://')) w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider('https://')) w3 = await AsyncWeb3(AsyncWeb3.WebSocketProvider('wss://')) ``` -------------------------------- ### Python WebSocket One-to-One Request Example Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/internals.rst Demonstrates making a one-to-one request using the eth module API over a WebSocket connection to get the latest block number. This example requires an active WebSocket provider running locally. ```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()) ``` -------------------------------- ### Create Web3 Instance with Various Providers (Python) Source: https://context7.com/bobthebuidler/faster-web3.py/llms.txt Demonstrates how to create a Web3 instance using different provider types: HTTP, WebSocket, and IPC. It also shows how to initialize an asynchronous Web3 instance. Ensure you replace placeholders like YOUR-PROJECT-ID and /path/to/geth.ipc with your actual values. ```python from web3 import Web3, HTTPProvider, WebSocketProvider, IPCProvider # HTTP Provider (most common) w3 = Web3(HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID')) # WebSocket Provider (for subscriptions) w3 = Web3(WebSocketProvider('wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID')) # IPC Provider (local node) w3 = Web3(IPCProvider('/path/to/geth.ipc')) # Async Web3 for async/await patterns from web3 import AsyncWeb3 async_w3 = await AsyncWeb3(WebSocketProvider('wss://...')) ``` -------------------------------- ### Install Package Dependencies with Homebrew Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/README-osx.md Installs essential libraries like openssl, libffi, autoconf, automake, and libtool using the Homebrew package manager. These are common dependencies for Python development, especially for libraries interacting with lower-level systems. ```shell brew install openssl libffi autoconf automake libtool ``` -------------------------------- ### Deploy and Interact with a Contract using faster-web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.contract.rst This snippet demonstrates deploying a contract, waiting for its receipt, and then interacting with it. It shows how to initialize a contract object using its ABI and bytecode, transact a deployment, and retrieve the contract's address from the receipt. ```python from web3 import Web3 import json # Assume w3 and bytecode are defined elsewhere # w3 = Web3(Web3.EthereumTesterProvider()) # bytecode = "0x..." ABI = json.loads('[{"constant":false,"inputs":[],"name":"return13","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"constant":true,"inputs":[],"name":"counter","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"amt","type":"uint256"}],"name":"increment","outputs":[{"name":"result","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"a","type":"int256"},{"name":"b","type":"int256"}],"name":"add","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"constant":false,"inputs":[],"name":"increment","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"a","type":"int256"}],"name":"multiply7","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"value","type":"uint256"}],"name":"increased","type":"event"}]') contract = w3.eth.contract(abi=ABI, bytecode=bytecode) deploy_txn = contract.constructor().transact() deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn) address = deploy_receipt.contractAddress ``` -------------------------------- ### Install web3.py Development Dependencies (ZSH Fix) Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/README-osx.md Installs the web3.py package in editable mode with development dependencies. This snippet includes a specific workaround for ZSH shell users on macOS Catalina or later, where the `.[dev]` syntax can cause errors. The fix involves quoting the `.[dev]` part. ```shell pip install -e .'[dev]' ``` -------------------------------- ### Python Version Check Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/release_notes.rst Implements a better error message when attempting to install on a Python version less than 3.5. This guides users to use compatible Python environments. ```python Better error message when trying to install on a python version <3.5 ``` -------------------------------- ### AsyncWeb3 with SignAndSendRawMiddlewareBuilder Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/middleware.rst Demonstrates the setup for AsyncWeb3 with SignAndSendRawMiddlewareBuilder, intended for asynchronous operations. This middleware automates the signing and sending of raw transactions when interacting with hosted nodes that require signed transactions. ```python from web3 import AsyncWeb3, AsyncHTTPProvider from web3.middleware import SignAndSendRawMiddlewareBuilder # async_w3 = AsyncWeb3(AsyncHTTPProvider('HTTP_ENDPOINT')) # from eth_account import Account # import os # acct = async_w3.eth.account.from_key(os.environ.get('PRIVATE_KEY')) # async_w3.middleware_onion.inject(SignAndSendRawMiddlewareBuilder.build(acct), layer=0) # async_w3.eth.default_account = acct.address ``` -------------------------------- ### Read Block Data with web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/quickstart.rst Demonstrates how to read block data using the web3.py library. This snippet shows the structure of a block object, including fields like 'number', 'parentHash', 'stateRoot', and 'transactionsRoot'. No external dependencies are required beyond web3.py. ```python { 'number': 0, 'parentHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'proofOfAuthorityData': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000dddc391ab2bf6701c74d0c8698c2e13355b2e4150000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'receiptsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 'size': 622, 'stateRoot': HexBytes('0x1f5e460eb84dc0606ab74189dbcfe617300549f8f4778c3c9081c119b5b5d1c1'), 'timestamp': 0, 'totalDifficulty': 1, 'transactions': [], 'transactionsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'uncles': []} ``` -------------------------------- ### Asynchronous Web3 Operations with AsyncWeb3 Source: https://context7.com/bobthebuidler/faster-web3.py/llms.txt Illustrates how to perform asynchronous Web3 operations using `AsyncWeb3` for non-blocking I/O. This example shows parallel execution of multiple Ethereum calls (getting balance, block, and gas price) using `asyncio.gather`. ```python import asyncio from web3 import AsyncWeb3, AsyncHTTPProvider async def async_operations(): w3 = AsyncWeb3(AsyncHTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID')) # Parallel execution of multiple calls balance_task = w3.eth.get_balance('vitalik.eth') block_task = w3.eth.get_block('latest') gas_task = w3.eth.gas_price balance, block, gas_price = await asyncio.gather( balance_task, block_task, gas_task ) print(f"Balance: {w3.from_wei(balance, 'ether')} ETH") print(f"Block: {block.number}") print(f"Gas: {w3.from_wei(gas_price, 'gwei')} Gwei") asyncio.run(async_operations()) ``` -------------------------------- ### Run asyncio Event Loop in Separate Thread (Python) Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/filters.rst This example demonstrates how to run the asyncio event loop in a separate thread, allowing the main thread to perform other tasks. It sets up a web3 instance, defines a function to handle events, and a loop to poll for new entries. The worker thread is started as a daemon. ```python from web3 import Web3, IPCProvider from threading import Thread import time # instantiate Web3 instance w3 = Web3(IPCProvider(...)) def handle_event(event): print(event) # and whatever 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') worker = Thread(target=log_loop, args=(block_filter, 5), daemon=True) worker.start() # .. do some other stuff if __name__ == '__main__': main() ``` -------------------------------- ### Listen to WebSocket Subscriptions (Python) Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/internals.rst This example shows how to establish an asynchronous WebSocket connection, subscribe to new block headers, and then iterate over incoming subscription responses using `w3.socket.process_subscriptions()`. It includes logic for unsubscribing based on a condition. ```python async def ws_subscription_example(): async with AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")) as w3: # Subscribe to new block headers and receive the subscription_id. # A one-to-one call with a trigger for many responses subscription_id = await w3.eth.subscribe("newHeads") # Listen to the socket for the many responses utilizing the # ``w3.socket`` ``PersistentConnection`` public API method # ``process_subscriptions()`` async for response in w3.socket.process_subscriptions(): # Receive only one-to-many responses here so that we don't # accidentally return the response for a one-to-one request in this # block print(f"{response}\n") if some_condition: # unsubscribe from new block headers, another one-to-one request is_unsubscribed = await w3.eth.unsubscribe(subscription_id) if is_unsubscribed: break asyncio.run(ws_subscription_example()) ``` -------------------------------- ### Python: Set up Account and Web3 Middleware Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.eth.account.rst This script demonstrates how to load a private key from an environment variable, create an Ethereum account object, and inject a signing middleware into the web3.py instance. This allows for sending transactions signed by the specified account without exposing the private key directly in transaction calls. ```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 ``` -------------------------------- ### Web3.py Automatic Initialization Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/release_notes.rst Demonstrates the convenience of automatic web3.py initialization using `from web3.auto import w3`. This allows for quick setup without manually configuring providers. ```python from web3.auto import w3 # Now you can use w3 directly for web3 operations print(w3.isConnected()) ``` -------------------------------- ### Set Up Python Virtual Environment with virtualenv Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/troubleshooting.rst Installs and configures a Python virtual environment using virtualenv for isolated package management. It ensures necessary tools like pip and virtualenv are installed, creates a new environment, activates it, and upgrades packaging tools before installing web3.py. ```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 ``` -------------------------------- ### Compile and Deploy a Smart Contract in Python Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.contract.rst Compiles Solidity code, deploys a contract, and interacts with its functions. This example demonstrates the full contract lifecycle from source to interaction using web3.py and solcx. ```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' ``` -------------------------------- ### Install Specific Geth Version with py-geth Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/contributing.rst Installs a specific version of the Geth client using the py-geth tool. This is a prerequisite for generating integration test fixtures for that Geth version. The command requires the desired Geth version as an argument. The output is the installation of the specified Geth version. ```sh $ python -m geth.install v1.16.2 ``` -------------------------------- ### Start Geth HTTP RPC Server Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.geth.rst Starts the HTTP-based JSON RPC API webserver on the specified host and port. It allows configuration of CORS domains and enables specific APIs. Returns a boolean indicating if the server started successfully. This method calls 'admin_startHTTP'. ```python >>> web3.geth.admin.start_http() True ``` -------------------------------- ### Web3 Instance Creation Source: https://context7.com/bobthebuidler/faster-web3.py/llms.txt Demonstrates how to create a Web3 instance using different provider types (HTTP, WebSocket, IPC) for both synchronous and asynchronous operations. ```APIDOC ## Web3 Instance Creation Creates the main Web3 object that serves as the entry point for all Ethereum interactions, establishing a connection to an Ethereum node through the specified provider. ### Method - **HTTP Provider**: `Web3(HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))` - **WebSocket Provider**: `Web3(WebSocketProvider('wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID'))` - **IPC Provider**: `Web3(IPCProvider('/path/to/geth.ipc'))` - **Async Web3**: `await AsyncWeb3(WebSocketProvider('wss://...'))` ### Parameters - **provider_url** (string) - The URL of the Ethereum node. - **provider_type** (enum) - The type of provider (HTTP, WebSocket, IPC). ### Request Example ```python from web3 import Web3, HTTPProvider, WebSocketProvider, IPCProvider from web3 import AsyncWeb3 # HTTP Provider w3_http = Web3(HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID')) # WebSocket Provider w3_ws = Web3(WebSocketProvider('wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID')) # IPC Provider w3_ipc = Web3(IPCProvider('/path/to/geth.ipc')) # Async Web3 async def create_async_w3(): async_w3 = await AsyncWeb3(WebSocketProvider('wss://...')) return async_w3 ``` ### Response - **Web3 instance** - An initialized Web3 object connected to the specified Ethereum node. ``` -------------------------------- ### Web3.py Currency Conversion Workflow Example Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/troubleshooting.rst Demonstrates a recommended workflow for handling multiple currency denominations in web3.py. It involves converting to wei first, then to the desired denomination, ensuring accuracy and consistency. ```python >>> web3.to_wei(Decimal('0.000000005'), 'ether') 5000000000 >>> web3.from_wei(5000000000, 'gwei') Decimal('5') ``` -------------------------------- ### Get Latest Block Number (Alias) with web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.eth.rst An alternative method to get the number of the most recent block on the blockchain. This is an alias for `web3.eth.get_block_number()`. ```python >>> web3.eth.block_number 2206939 ``` -------------------------------- ### Python: Prepare Message for Solidity ecrecover Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.eth.account.rst This example illustrates how to prepare a signed message for verification in Solidity using the `ecrecover` function. It details the necessary formatting for the `v`, `r`, and `s` components to be compatible with Solidity's expected types, including padding and hex encoding. ```python from web3 import Web3 # ecrecover in Solidity expects v as a uint8, but r and s as left-padded bytes32 # Remix / web3.js expect r and s to be encoded to hex # This convenience method will do the pad & hex for us: def to_32byte_hex(val): return Web3.to_hex(Web3.to_bytes(val).rjust(32, b'\0')) # Assuming signed_message is available from the previous signing step # ec_recover_args = (msghash, v, r, s) = (signed_message.message_hash.hex(), signed_message.v, to_32byte_hex(signed_message.r), to_32byte_hex(signed_message.s)) # print(f"For Solidity ecrecover, use: msghash={msghash}, v={v}, r={r}, s={s}") ``` -------------------------------- ### Windows Installation Improvement Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/release_notes.rst Includes `pypiwin32` during pip installation for a better Windows user experience. This resolves potential dependency issues on Windows systems. ```python Installs pypiwin32 during pip install, for a better Windows experience ``` -------------------------------- ### Connect to Geth Dev Instance (Python) Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/providers.rst Connect to a 'geth --dev' Proof of Authority instance with the POA middleware loaded by default. This snippet shows how to establish a synchronous connection and verify it. It also includes an asynchronous connection example. ```python from web3.auto.gethdev import w3 # confirm that the connection succeeded >>> w3.is_connected() True ``` ```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 Development Version of Web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/contributing.rst Installs an unreleased version of web3.py from a local development directory. This allows for manual testing of changes before merging them into the main branch. ```sh python -m pip install -e ../path/to/web3py ``` -------------------------------- ### Start Docker Test Environment for web3.py Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/contributing.rst Starts the Docker containers defined in the docker-compose.yml file in detached mode. This sets up an isolated environment for running tests. ```sh docker compose up -d ``` -------------------------------- ### Configure web3.py Instance with HTTPProvider Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/troubleshooting.rst Demonstrates how to instantiate and configure a web3.py instance using the HTTPProvider to connect to a local Ethereum node. This is a prerequisite for using most web3.py functionalities, such as interacting with the Ethereum network's state or sending transactions. ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('http://localhost:8545')) # now `w3` is available to use: w3.is_connected() w3.eth.send_transaction(...) ``` -------------------------------- ### Install Solidity Compiler (solc) in Python Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/web3.contract.rst Installs the latest version of the Solidity compiler using the py-solc-x library. This is a prerequisite for compiling Solidity code within a Python environment. ```python from solcx import install_solc install_solc(version='latest') ``` -------------------------------- ### Connect to Blockchain using Providers in Python Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/overview.rst Demonstrates how to connect to a blockchain using different provider types in web3.py. Includes examples for synchronous and asynchronous connections via IPC, HTTP, and WebSocket. ```python from web3 import Web3, AsyncWeb3 # IPCProvider: w3 = Web3(Web3.IPCProvider('./path/to/filename.ipc')) print(w3.is_connected()) # HTTPProvider: w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545')) print(w3.is_connected()) # AsyncHTTPProvider: w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider('http://127.0.0.1:8545')) print(await w3.is_connected()) # -- Persistent Connection Providers -- # # WebSocketProvider: w3 = await AsyncWeb3(AsyncWeb3.WebSocketProvider('ws://127.0.0.1:8546')) print(await w3.is_connected()) # AsyncIPCProvider w3 = await AsyncWeb3(AsyncWeb3.AsyncIPCProvider('./path/to/filename.ipc')) print(await w3.is_connected()) ``` -------------------------------- ### Initialize Web3.py with Custom Middleware Source: https://github.com/bobthebuidler/faster-web3.py/blob/master/docs/middleware.rst Initializes a new Web3 instance with a custom list of middleware, replacing the default middleware stack. To retain default functionality, include the default middleware in the custom list or add them using `middleware_onion.add()` after initialization. ```python Web3(middleware=[my_middleware1, my_middleware2]) ```